<template>
  <div class="page">
    <van-sticky class="sticky">
      <div class="header flex">
        <div class="back">
          <backIcon/>
        </div>
        <!-- 交易 -->
        {{ $t('tab.tab3') }}
        <div class="right-box flex">
          <div v-if="type == '1'" @click="changeType('2')">
            <!-- 专业版 -->
            {{ $t('exchange.l65') }}<i class="el-icon-caret-bottom"></i></div>
          <div v-if="type == '2'" @click="changeType('1')">
            <!-- 简易版 -->
            {{ $t('exchange.l66') }}<i class="el-icon-caret-bottom"></i></div>
          <van-popover
            v-model="showPopover"
            placement="bottom-end"
            trigger="click"
          >
            <div class="popover-body">
              <div class="item flex item1">
                <img class="icon14" src="/img/product/icon6.png" alt="">
                <div>
                  <!-- 锁定交易 -->
                  {{ $t('exchange.l67') }}
                </div>
              </div>
              <div class="item flex">
                <img class="icon14" src="/img/product/icon7.png" alt="">
                <div>
                  <!-- 下单设置 -->
                  {{ $t('exchange.l68') }}
                </div>
              </div>
              <div class="item flex">
                <img class="icon14" src="/img/product/icon8.png" alt="">
                <div>
                  <!-- 我的行情 -->
                  {{ $t('exchange.l69') }}
                </div>
              </div>
              <div class="item flex" @click="$router.push('/chat')">
                <img class="icon14" src="/img/account/icon17.png" alt="">
                <div>
                  <!-- 帮助中心 -->
                  {{ $t('home.l26') }}
                </div>
              </div>
            </div>
            <template #reference>
              <img class="more" src="/img/icon/more.png" alt="">
            </template>
          </van-popover>
        </div>
      </div>
      <noticeView v-if="activeMarket && activeMarket.id && activeNoticeShow" :market="symbolInfo.market" :activeMarket="activeMarket" @close="activeNoticeShow = false" />
      <div class="box flex" v-if="accountInfo.account" @click="accountShow = true">
        <div class="left">
          <van-image
            width="17"
            height="17"
            round
            fit="cover"
            :src="`/img/user/${accountInfo.server}.png`"
          />
          <div>
            <div class="name">{{ serverName[accountInfo.server] || accountInfo.server }}({{ accountInfo.account }})</div>
            <div class="free flex">
              <!-- 现金 -->
              <div>{{ $t('exchange.l38') }}:{{ $numToThousand($handleDigits(accountInfo.margin_free)) }}{{ serverUtil[accountInfo.server] }}</div>
              <!-- 最大购买力 -->
              <div>{{ $t('account.l24') }}:{{ $numToThousand($handleDigits($bigDecimal.multiply(accountInfo.margin_free, accountInfo.serverBean.leverage))) }}{{ serverUtil[accountInfo.server] }}</div>
            </div>
          </div>
        </div>
        <i class="el-icon-arrow-right"></i>
      </div>
    </van-sticky>
    <complex @deposit="depositPop = true" v-if="type == '1'" :accountInfo="accountInfo" :symbol="symbol" :symbolInfo="symbolInfo" />
    <easy @deposit="depositPop = true" v-if="type == '2'" :accountInfo="accountInfo" :symbol="symbol" :symbolInfo="symbolInfo"/>
    <div class="order-box">
      <div class="tab-bar">
        <div class="flex" :class="{'active': listType == 1}" @click="listType = 1"><img v-show="listType == 1" class="tag" src="/img/exchange/tag.png" alt="">
          <!-- 持仓 -->
          {{ $t('exchange.l70') }}{{ positionList.length ? `(${positionList.length})` : ''}}
        </div>
        <div class="flex" :class="{'active': listType == 2}" @click="listType = 2"><img v-show="listType == 2" class="tag" src="/img/exchange/tag.png" alt="">
          <!-- 挂单 -->
          {{ $t('exchange.l71') }}{{ entrustList.length ? `(${entrustList.length})` : ''}}
        </div>
        <div class="flex" :class="{'active': listType == 3}" @click="listType = 3"><img v-show="listType == 3" class="tag" src="/img/exchange/tag.png" alt="">
          <!-- 历史订单 -->
          {{ $t('exchange.l72') }}
        </div>
      </div>
      <positionListView v-if="listType == 1" :list="positionList"/>
      <entrustListView v-if="listType == 2" :list="entrustList"/>
      <historyListView v-if="listType == 3" :accountInfo="accountInfo"/>
    </div>
    <div class="tip">
      <!-- 证券交易服务由极度证券提供 -->
      {{ $t('common.l43') }}
    </div>
    <van-popup v-model="accountShow" round position="bottom">
      <accountList :list="accountList" :info="accountInfo" @success="selectAccountBack"/>
    </van-popup>
    <van-popup v-model="depositPop" round position="bottom">
      <toDepositPop @cancel="depositPop = false" :info="accountInfo"/>
    </van-popup>
  </div>
</template>
<script>
import complex from "./components/complex.vue";
import easy from "./components/easy.vue";
import toDepositPop from "./components/toDepositPop.vue";
import positionListView from "@/components/positionList/index.vue";
import entrustListView from "@/components/entrustList/index.vue";
import historyListView from "@/components/historyList/index.vue";
import { setStorage, getStorage } from "@/utils/localStorage";
import { mapGetters } from "vuex";
import bus from '@/utils/bus'
import accountList from "./components/accountList.vue";
import { getProductList } from "@/api/product";
import { getPositionList, getEntrustList } from "@/api/exchange";
import noticeView from "@/components/closedMarket/notice.vue";
export default {
  components: {
    accountList,
    complex,
    easy,
    positionListView,
    entrustListView,
    historyListView,
    toDepositPop,
    noticeView,
  },
  inject: ['getproductDataObj'],
  data () {
    return {
      symbol: '',
      type: '2',
      positionList: [],
      entrustList: [],
      listType: 1,
      accountId: '',
      ajaxSign: 0,
      accountInfo1: {},
      accountShow: false,
      showPopover: false,
      depositPop: false,
      activeNoticeShow: true,
    }
  },
  computed: {
    ...mapGetters(['accountList', 'marketCN', 'marketHK', 'marketUS', 'marketCFD', 'marketPopCN', 'marketPopHK', 'marketPopUS', 'marketPopCFD']),
    productDataObj() {
      return this.getproductDataObj()
    },
    symbolInfo() {
      return this.productDataObj[this.symbol] || {}
    },
    activeMarket() {
      return this['market' + this.symbolInfo.market]
    },
    accountInfo() {
      let info = this.accountInfo1
      this.accountList.forEach(item => {
        if (this.accountId) {
          if (this.accountId == item.id) {
            info = item
          }
          return
        }
        if (this.symbolInfo.market == 'CN') {
          if (this.symbolInfo.symbol.indexOf(item.server) !== -1) {
            info = item
          }
          return
        }
        if(item.server == this.symbolInfo.market) {
          info = item
        }
      })
      return info
    }
  },
  beforeDestroy() {
    bus.$off('updateOrder', this.updateOrder)
    bus.$off('updateSymbol', this.updateSymbol)
  },
  watch: {
    'accountInfo.account'(val) {
      if (val) {
        this.updateOrder()
      }
    },
    'symbolInfo.market'() {
      if (this.symbolInfo.market && !this['market' + this.symbolInfo.market]) {
        this.$store.dispatch('getProductVacationList', this.symbolInfo.market)
      }
    },
    '$route'() {
      this.symbol = this.$route.params.symbol
      this.loadedAll()
    }
  },
  created () {
    if (this.$route.params.id) {
      this.accountId = this.$route.params.id
    } else {
      this.symbol = this.$route.params.symbol
      if (!this.symbolInfo.symbol) {
        bus.$emit('updateSubscribe', [this.symbol], true, true)
      }
    }
    this.type = getStorage('exchangeType') || '2'
    if (this.isLogin) {
      bus.$emit('updateAssets', ['getAccountList'])
      // if (this.accountInfo.account) {
      //   this.getPositionList()
      //   this.getEntrustList()
      // }
    }
    bus.$on('updateOrder', this.updateOrder)
    bus.$on('updateSymbol', this.updateSymbol)
  },
  methods: {
    getPositionList() {
      getPositionList({
        account: this.accountInfo.account,
        server: this.accountInfo.server
      }).then(res => {
        this.positionList = res.list || []
      }).catch(() => {}).finally(() => {
        if (this.ajaxSign != 2) {
          this.ajaxSign += 1
        }
        this.loadedAll()
      })
    },
    getEntrustList() {
      getEntrustList({
        account: this.accountInfo.account,
        server: this.accountInfo.server
      }).then(res => {
        this.entrustList = res.list || []
      }).catch(() => {}).finally(() => {
        if (this.ajaxSign != 2) {
          this.ajaxSign += 1
        }
        this.loadedAll()
      })
    },
    loadedAll() {
      if (!this.isLogin) {
        bus.$emit('updateSubscribe', [this.symbol], true, false)
        return
      }
      if (this.ajaxSign == 2) {
        let list = [this.symbol]
        this.positionList.forEach(item => {
          if (list.indexOf(item.symbol) === -1) {
            list.push(item.symbol)
          }
        })
        this.entrustList.forEach(item => {
          if (list.indexOf(item.symbol) === -1) {
            list.push(item.symbol)
          }
        })
        if (list.length == 0) {
          return
        }
        getProductList({
          symbol: JSON.stringify(list)
        }).then(res => {
          let list = res.list || []
          let list1 = []
          if (this.accountInfo.server == 'CFD') {
            list.forEach(item => {
                if (item.profit_mode == 0) {
                  let symbol = item.symbol.slice(3, 6)
                  if (symbol != 'USD') {
                    list1.push(symbol + 'USD')
                    list1.push('USD' + symbol)
                  }
                } else {
                  if (item.currency != 'USD') {
                    list1.push(item.currency + 'USD')
                    list1.push('USD' + item.currency)
                  }
                }
            })
            bus.$emit('updateSubscribe', list1, false, true)
          }
          bus.$emit('updateSubscribe', list, false, false, list1)
        })
      }
    },
    updateOrder() {
      this.ajaxSign = 0
      this.getPositionList()
      this.getEntrustList()
    },
    updateSymbol() {
      let positionList = this.positionList
      positionList.forEach((item, index) => {
        let v = item
        if (this.productDataObj[item.symbol]) {
          if (item.cmd == 0) {
            v.close_price = this.productDataObj[item.symbol].bid
          }
          if (item.cmd == 1) {
            v.close_price = this.productDataObj[item.symbol].ask
          }
        }
        v.profit = this.formatProfit(v)
        this.$set(this.positionList, index, v)
      })
    },
    selectAccountBack(val) {
      this.accountInfo1 = val
      if (this.accountInfo.server !== this.accountInfo1.server) {
        this.symbol = ''
        this.accountId = ''
        // this.updateOrder()
      }
      this.accountShow = false
    },
    changeType(type) {
      if (this.type == type) {
        return
      }
      this.type = type
      setStorage('exchangeType', type)
    },
    formatProfit(data) {
      let currencyData = this.productDataObj[data.symbol]
      if (!currencyData) {
        return data.profit
      }
      let rate, profit;
      if (currencyData.market == 'CFD') {
        if (currencyData.profit_mode == '1') {
          let market1 = ''
          let market2 = ''
          if (currencyData.currency != 'USD') {
            market1 = this.productDataObj[`USD${currencyData.currency}`]
            market2 = this.productDataObj[`${currencyData.currency}USD`]
            if (market1) {
              rate = (market1['ask'] + market1['bid']) / 2
            }
            if (market2) {
              rate = (market2['ask'] + market2['bid']) / 2
            }
          }
          if (data.cmd == '1') {
            if (market2) {
              profit = (data.open_price - currencyData.ask) * (data.volume / 100) * currencyData.contract_size * rate
            } else if (market1) {
              profit = ((data.open_price - currencyData.ask) * (data.volume / 100) * currencyData.contract_size) / rate
            } else {
              profit = (data.open_price - currencyData.ask) * (data.volume / 100) * currencyData.contract_size
            }
          } else if (data.cmd == '0') {
            if (market2) {
              profit = (currencyData.bid - data.open_price) * (data.volume / 100) * currencyData.contract_size * rate
            } else if (market1) {
              profit = ((currencyData.bid - data.open_price) * (data.volume / 100) * currencyData.contract_size) / rate
            } else {
              profit = (currencyData.bid - data.open_price) * (data.volume / 100) * currencyData.contract_size
            }
          }
        } else if (currencyData.profit_mode == '0') {
          let symbol = currencyData.symbol.slice(3, 6)
          let market1 = this.productDataObj[`USD${symbol}`]
          let market2 = this.productDataObj[`${symbol}USD`]
          if (market1) {
            rate = (market1['ask'] + market1['bid']) / 2
          }
          if (market2) {
            rate = (market2['ask'] + market2['bid']) / 2
          }
          if (data.cmd == '1') {
            if (market2) {
              profit = (data.open_price - currencyData.ask) * (data.volume / 100) * currencyData.contract_size * rate
            } else if (market1) {
              profit = (( data.open_price - currencyData.ask) * (data.volume / 100) * currencyData.contract_size) / rate
            } else {
              profit = ((data.open_price - currencyData.ask) * (data.volume / 100) * currencyData.contract_size)
            }
          } else if (data.cmd == '0') {
            if (market2) {
              profit = (currencyData.bid - data.open_price) * (data.volume / 100) * currencyData.contract_size * rate
            } else if (market1) {
              profit = ((currencyData.bid - data.open_price) * (data.volume / 100) * currencyData.contract_size) / rate
            } else {
              profit = ((currencyData.bid - data.open_price) * (data.volume / 100) * currencyData.contract_size)
            }
          }
        }
      } else {
        if (data.cmd == '1') {
          profit = (data.open_price - currencyData.ask) * (data.volume / 100) * currencyData.contract_size
        } else if (data.cmd == '0') {
          profit = (currencyData.bid - data.open_price) * (data.volume / 100) * currencyData.contract_size
        }
      }
      if (profit) {
        return profit.toFixed(2)
      }
      return '0.00'
    },
  }
}
</script>
<style lang="less" scoped>
.page {
  min-height: 100vh;
  background-color: var(--bg2-);
}
.sticky {
  background-color: var(--bg-);
  margin-bottom: 8px;
}
.header {
  position: relative;
  height: 38px;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
  background-color: var(--bg-);
  .back {
    position: absolute;
    left: 9px;
    top: 50%;
    transform: translateY(-50%);
  }
  .right-box {
    position: absolute;
    right: 19px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--color-3-);
    font-size: 12px;
    font-weight: 400;
    column-gap: 19px;
  }
  .more {
    cursor: pointer;
    width: 20px;
    display: block;
  }
}
.box {
  background-color: var(--bg-);
  justify-content: space-between;
  padding: 6px 18px 9px;
  cursor: pointer;
  .left {
    display: flex;
    align-items: flex-start;
    column-gap: 5px;
    font-size: 12px;
    color: #A4A4A4;
  }
  .name {
    font-size: 15px;
    font-weight: 600;
    color: var(--color-1-);
    margin-bottom: 9px;
  }
  .free {
    column-gap: 20px;
    flex-wrap: wrap;
    row-gap: 8px;
  }
  .el-icon-arrow-right {
    color: #AAAAAA;
    font-size: 20px;
  }
}
.order-box {
  background-color: var(--bg-);
  padding: 16px 18px 0;
}
.tab-bar {
  display: flex;
  align-items: flex-end;
  column-gap: 22px;
  font-size: 14px;
  color: #6E6E6E;
  padding-bottom: 8px;
  white-space: nowrap;
  .active {
    font-size: 15px;
    font-weight: 600;
    color: var(--color-1-);
  }
  .tag {
    width: 10px;
    margin-right: 2px;
  }
}
.tip {
  padding: 25px 18px 17px;
  text-align: center;
  font-size: 12px;
  color: #AEAEAE;
  background-color: #fff;
}
.popover-body {
  .item {
    cursor: pointer;
    height: 42px;
    padding-left: 16px;
    color: #2C2C2C;
    font-size: 14px;
    width: 140px;
    line-height: 1;
    &+.item {
      border-top: 1px solid #E9E9E9;
    }
    &.item1 {
      color: #7A7A7A;
    }
  }
  .icon14 {
    width: 22px;
    margin-right: 8px;
  }
}
</style>