<template>
  <div class="page" v-loading.body.fullscreen="fullscreenLoading" element-loading-background="rgba(255, 255, 255, 0)">
    <div class="sticky">
      <div class="header">
        <div class="back">
          <backIcon/>
        </div>
        <!-- 交易账户 -->
        {{$t('account.l25')}}
      </div>
      <div class="tabbar flex">
        <div class="bar" :class="{'active': item.id == id}" v-for="item in accountList" :key="item.id" @click="changeRouter(item.id)">
          {{ serverTitle[item.market] }}
          <div class="line"></div>
        </div>
      </div>
    </div>
    <div class="body">
      <headerView :positionSign="positionSign" :updateSign="updateSign" :allMarket="allMarket" :allProfit="allProfit" v-if="accountInfo.id" :accountInfo="accountInfo"/>
      <div class="section flex">
        <div class="item flex" @click="$router.push('/exchange/1/buy/' + accountInfo.id)">
          <img class="icon" src="/img/account/icon7.png" alt="极度证券">
          <div class="text">
            <!-- 交易 -->
            {{ $t('tab.tab3') }}
          </div>
        </div>
        <div class="item flex" @click="goUrl('/deposit/' + accountInfo.id)">
          <img class="icon" src="/img/account/icon4.png" alt="极度证券">
          <div class="text">
            <!-- 存入资金 -->
            {{ $t('account.l26') }}
          </div>
        </div>
        <div class="item flex" @click="goUrl('/withdraw')">
          <img class="icon" src="/img/account/icon21.png" alt="极度证券">
          <div class="text">
            <!-- 取款 -->
            {{ $t('home.l14') }}
          </div>
        </div>
        <div class="item flex" @click="goUrl('/convert/' + accountInfo.id)">
          <img class="icon" src="/img/account/icon3.png" alt="极度证券">
          <div class="text">
            <!-- 划转 -->
            {{ $t('home.l15') }}
          </div>
        </div>
        <div class="item flex" @click="$router.push('/account-records/1')">
          <img class="icon" src="/img/account/icon6.png" alt="极度证券">
          <div class="text">
            <!-- 资金记录 -->
            {{ $t('account.l9') }}
          </div>
        </div>
      </div>
      <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>
    </div>
    <!-- <authIdentity v-if="authShow" @cancel="authShow = false" /> -->
  </div>
</template>
<script>
import positionListView from "@/components/positionList/index.vue";
import entrustListView from "@/components/entrustList/index.vue";
import historyListView from "@/components/historyList/index.vue";
import bus from '@/utils/bus'
import { mapGetters } from "vuex";
import headerView from "./components/header.vue";
import { getPositionList, getEntrustList } from "@/api/exchange";
import { getProductList } from "@/api/product";
// import authIdentity from "@/components/authIdentity";
export default {
  components: {
    headerView,
    positionListView,
    entrustListView,
    historyListView,
    // authIdentity
  },
  inject: ['getproductDataObj'],
  computed: {
    ...mapGetters(['accountList', 'userInfo']),
    serverTitle() {
      return {
        // 'CFD': '综合',
        // 'CN': 'A股通',
        // 'US': '美股通',
        // 'HK': '港股通',
        'CFD': this.$t('common.l40'),
        'CN': this.$t('share.l2'),
        'US': this.$t('common.l18'),
        'HK': this.$t('common.l19'),
      }
    },
    productDataObj() {
      return this.getproductDataObj()
    },
    accountInfo() {
      var info = {}
      this.accountList.forEach(item => {
        if(item.id == this.id) {
          info = item
        }
      })
      return info
    },
    allMarket() {
      var positionList = this.positionList
      var allProfit = 0
      var allMarket = 0
      positionList.forEach((item, index) => {
        var v = item
        allProfit = this.$bigDecimal.add(allProfit, v.profit)
        allProfit = this.$bigDecimal.add(allProfit, v.commission)
        allProfit = this.$bigDecimal.add(allProfit, v.swaps)
        allMarket = this.$bigDecimal.add(allMarket, this.formatMarket(item))
      })
      this.allProfit = allProfit
      return allMarket
    }
  },
  data () {
    return {
      id: null,
      authShow: false,
      positionList: [],
      entrustList: [],
      listType: 1,
      ajaxSign: 0,
      allProfit: 0,
      positionSign: false,
      updateSign: false,
    }
  },
  beforeDestroy() {
    bus.$off('updateOrder', this.updateOrder)
    bus.$off('updateSymbol', this.updateSymbol)
  },
  watch: {
    'accountInfo.account'(val) {
      if (val) {
        this.positionSign = false
        this.updateSign = false
        this.updateOrder()
      }
    },
  },
  created () {
    this.id = this.$route.params.id
    if (this.accountInfo.account) {
      // this.getPositionList()
      // this.getEntrustList()
    } else {
      bus.$emit('updateAssets', ['getAccountList'])
    }
    bus.$emit('updateAssets', ['getCash'])
    bus.$on('updateOrder', this.updateOrder)
    bus.$on('updateSymbol', this.updateSymbol)
  },
  methods: {
    getPositionList() {
      getPositionList({
        account: this.accountInfo.account,
        server: this.accountInfo.server
      }).then(res => {
        this.positionSign = true
        this.positionList = res.list || []
        this.updateSymbol(false)
      }).catch(() => {}).finally(() => {
        this.ajaxSign += 1
        this.loadedAll()
      })
    },
    getEntrustList() {
      getEntrustList({
        account: this.accountInfo.account,
        server: this.accountInfo.server
      }).then(res => {
        this.entrustList = res.list || []
      }).catch(() => {}).finally(() => {
        this.ajaxSign += 1
        this.loadedAll()
      })
    },
    loadedAll() {
      if (this.ajaxSign == 2) {
        var symbolList = []
        this.positionList.forEach(item => {
          if (symbolList.indexOf(item.symbol) === -1) {
            symbolList.push(item.symbol)
          }
        })
        this.entrustList.forEach(item => {
          if (symbolList.indexOf(item.symbol) === -1) {
            symbolList.push(item.symbol)
          }
        })
        if (symbolList.length == 0) {
          return
        }
        getProductList({
          symbol: JSON.stringify(symbolList)
        }).then(res => {
          var list = res.list || []
          var list1 = []
          if (this.accountInfo.server == 'CFD') {
            list.forEach(item => {
              if (item.profit_mode == 0) {
                var 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("alterProductData", {
              getData: list1
            });
          }
          bus.$emit("alterProductData", {
            setData: list,
            subscribeList: [...symbolList, ...list1]
          });
        })
      }
    },
    updateOrder() {
      this.ajaxSign = 0
      this.getPositionList()
      this.getEntrustList()
    },
    updateSymbol(sign) {
      var positionList = this.positionList
      positionList.forEach((item, index) => {
        var v = item
        if (sign) {
          this.updateSign = true
          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) || v.profit
          this.$set(this.positionList, index, v)
        }
      })
    },
    changeRouter(id) {
      if (this.id == id) {
        return
      }
      this.id = id
      this.$router.replace('/account-detail/' + id)
      this.listType = 1
      this.positionList = []
      this.entrustList = []
      this.allProfit = 0
      // this.updateOrder()
    },
    goUrl(url) {
      if (!this.isLogin) {
        this.$router.push('/login')
        return
      }
      // if (this.userInfo.identity_status == 1) {
        this.$router.push(url)
        return
      // }
      this.fullscreenLoading = true
      this.$store.dispatch('getUserInfo').then(() => {
        if (this.userInfo.identity_status !== 1) {
          this.authShow = true
        } else {
          this.$router.push(url)
        }
      }).catch(() => {}).finally(() => {
        this.fullscreenLoading = false
      })
    },
    formatMarket(item) {
      var currencyData = this.productDataObj[item.symbol]
      if (currencyData) {
        var market = this.$bigDecimal.multiply(item.close_price, this.$bigDecimal.multiply(this.$bigDecimal.divide(item.volume, 100), currencyData.contract_size))
        var rate;
        if (currencyData.market == 'CFD') {
          if (currencyData.profit_mode == '1') {
            var market1 = ''
            var 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 (market2) {
                market = market * rate
              } else if (market1) {
                market = market / rate
              }
            }
          } else if (currencyData.profit_mode == '0') {
            var symbol = currencyData.symbol.slice(3, 6)
            var market1 = this.productDataObj[`USD${symbol}`]
            var market2 = this.productDataObj[`${symbol}USD`]
            if (market1) {
              rate = (market1['ask'] + market1['bid']) / 2
            }
            if (market2) {
              rate = (market2['ask'] + market2['bid']) / 2
            }
            if (market2) {
              market = market * rate
            } else if (market1) {
              market = market / rate
            }
          }
        }
        return Number(market).toFixed(2)
      }
      return this.$bigDecimal.multiply(item.close_price, this.$bigDecimal.multiply(this.$bigDecimal.divide(item.volume, 100), item.productBean.contract_size))
    },
    formatProfit(data) {
      var currencyData = this.productDataObj[data.symbol]
      if (!currencyData) {
        return data.profit
      }
      var rate, profit;
      if (currencyData.market == 'CFD') {
        if (currencyData.profit_mode == '1') {
          var market1 = ''
          var 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') {
          var symbol = currencyData.symbol.slice(3, 6)
          var market1 = this.productDataObj[`USD${symbol}`]
          var 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: #F3F4F6;
}
.sticky {
  position: sticky;
  top: 0;
  z-index: 20;
  background-color: var(--bg2-);
}
.header {
  position: relative;
  text-align: center;
  padding-top: 15px;
  padding-bottom: 10px;
  font-size: 18px;
  font-weight: 600;
  background-color: var(--bg-);
  .back {
    position: absolute;
    left: 9px;
    top: 11px;
  }
}
.tabbar {
  margin-top: 1px;
  background-color: var(--bg-);
  justify-content: space-between;
  padding: 0 18px;
  white-space: nowrap;
  overflow-x: auto;
  column-gap: 12px;
  .bar {
    position: relative;
    line-height: 50px;
    font-size: 16px;
    color: #333333;
    cursor: pointer;
    &.active {
      color: #000;
      font-weight: 600;
      .line {
        display: block;
      }
    }
  }
  .line {
    display: none;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2px;
    background-color: #000000;
  }
}
.body {
  padding: 13px 17px 0;
}
.section {
  background-color: var(--bg-);
  height: 103px;
  border-radius: 12px;
  justify-content: space-between;
  padding: 0 4px;
  .item {
    width: calc(20% - 4px);
    justify-content: center;
    flex-direction: column;
    cursor: pointer;
    font-size: 12px;
    color: var(--color-d-);
    .icon {
      margin-bottom: 10px;
      width: 44px;
    }
  }
  .text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    text-align: center;
  }
}
.order-box {
  padding-top: 15px;
}
.tab-bar {
  display: flex;
  align-items: flex-end;
  column-gap: 22px;
  font-size: 14px;
  color: #6E6E6E;
  padding-bottom: 8px;
  white-space: nowrap;
  overflow-x: auto;
  .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;
}
</style>