<template>
  <div class="profit-box">
    <div>
      <!-- 持仓盈亏 -->
      {{$t('account.l19')}}
    </div>
    <div class="profit" :class="{up: allProfit >= 0, down: allProfit < 0}">{{ allProfit > 0 ? '+' : '' }}{{ $numToThousand($handleDigits(allProfit)) }}({{ allProfit > 0 ? '+' : '' }}{{ getPercentage(allProfit, equity) }}%)</div>
  </div>
</template>
<script>
import { getPositionList } from "@/api/exchange";
import { getProductList } from "@/api/product";
import bus from '@/utils/bus'
export default {
  props: ['accountInfo'],
  inject: ['getproductDataObj'],
  data () {
    return {
      positionList: [],
      positionSign: false,
      updateSign: false,
    }
  },
  computed: {
    productDataObj() {
      return this.getproductDataObj()
    },
    equity() {
      if(!this.positionSign || !this.updateSign) {
        return this.accountInfo.equity
      }
      var a = this.$bigDecimal.add(this.accountInfo.balance, Number(this.allProfit))
      this.$emit('setEquity', a)
      return a
    },
    allProfit() {
      var positionList = this.positionList
      var allProfit = 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)
      })
      return allProfit
    }
  },
  beforeDestroy() {
    bus.$off('updateSymbol', this.updateSymbol)
  },
  created () {
    bus.$on('updateSymbol', this.updateSymbol)
    this.getPositionList()
  },
  methods: {
    getPositionList() {
      getPositionList({
        account: this.accountInfo.account,
        server: this.accountInfo.server
      }).then(res => {
        this.positionList = res.list || []
        var symbolList = []
        this.positionList.forEach(item => {
          if (symbolList.indexOf(item.symbol) === -1) {
            symbolList.push(item.symbol)
          }
        })
        this.positionSign = true
        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]
          });
        })
      }).catch(() => {})
    },
    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)
        }
      })
    },
    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'
    },
    getPercentage(value, equity) {
      if (!value || !Number(equity)) {
        return '0.00'
      }
      return (value/equity * 100).toFixed(2)
    },
  }
}
</script>
<style lang="less" scoped>
.profit-box {
  position: absolute;
  top: 15px;
  right: 12px;
  text-align: right;
  font-size: 10px;
  color: #9D9D9D;
  line-height: 14px;
  .profit {
    font-size: 12px;
    line-height: 16px;
    margin-top: 2px;
    &.up {
      color: #EA4A45;
    }
    &.down {
      color: #07AC3A;
    }
  }
}
</style>