<template>
  <div class="list">
    <div class="li" v-if="cashInfo.uid" @click="$router.push('/usd-record')">
      <div class="top flex">
        <div class="flex">
          <img class="icon" src="/img/account/icon8.png" alt="极度证券">
          <div>
            <!-- 美元钱包账户 -->
            {{ $t('account.l1') }}
          </div>
        </div>
        <img class="arrow-right" src="/img/account/right.png" alt="极度证券">
      </div>
      <div class="detail flex">
        <div>
          <div class="label">{{ $t('account.l2') }}.USD</div>
          <div class="number" v-if="showAssets">{{ $numToThousand(cashInfo.balance) }}</div>
          <div class="number" v-else>*****</div>
        </div>
      </div>
    </div>
    <div class="title flex">
      <div>{{ $t('account.l3') }}{{ accountListLength }}</div>
      <img class="arrow-down" src="/img/account/down.png" alt="极度证券" @click="toggleList" :class="{'active': showAccountList == 2}">
    </div>
    <template v-if="showAccountList == 1">
      <div class="li" v-for="item in accountList" :key="item.id" @click="$router.push('/account-detail/' + item.id)">
        <div class="top flex">
          <div class="flex">
            <img class="icon" :src="`/img/user/${item.server}.png`" alt="极度证券">
            <div>{{serverName[item.server] || item.server}}({{ item.account }})</div>
          </div>
          <img class="arrow-right" src="/img/account/right.png" alt="极度证券">
        </div>
        <div class="detail flex">
          <div>
            <div class="label">{{ $t('account.l2') }}.{{serverUtil[item.server] || item.server}}</div>
            <div class="number" v-if="showAssets">{{ $numToThousand(item.equity) }}</div>
            <div class="number" v-else>*****</div>
          </div>
          <div class="right" v-if="profit[item.server] !== '' && !getUserDayLoading">
            <div class="label">
              <!-- 今日盈亏 -->
              {{ $t('account.l4') }}
            </div>
            <div class="label">
              {{ (item.equity - profit[item.server]) > 0 ? '+' : "" }}{{ (item.equity - profit[item.server]).toFixed(2) }}
            </div>
            <div class="label">
              {{ (item.equity - profit[item.server]) > 0 ? '+' : "" }}{{getPercentage(item.equity - profit[item.server], item.equity)}}%
            </div>
          </div>
        </div>
      </div>
      <div class="li" v-if="cashInfo.uid" @click="$router.push('/option-records/1')">
        <div class="top flex">
          <div class="flex">
            <img class="icon" src="/img/account/icon9.png" alt="极度证券">
            <div>
              <!-- 期权账户(USD钱包) -->
              {{ $t('account.l5') }}
            </div>
          </div>
          <img class="arrow-right" src="/img/account/right.png" alt="极度证券">
        </div>
        <div class="detail flex">
          <div>
            <div class="label">{{ $t('account.l6') }}.USD</div>
            <!-- <div class="number" v-if="showAssets">{{ $numToThousand(cashInfo.balance) }}</div> -->
            <div class="number" v-if="showAssets">{{ $numToThousand(optionAmountTotal) }}</div>
            <div class="number" v-else>*****</div>
          </div>
          <div class="right" v-if="!getOptionOrderLoading">
            <div class="label">
              <!-- 盈亏 -->
              {{ $t('account.l7') }}
            </div>
            <div class="label">
              {{ $numToThousand(optionCloseProfit) }}
            </div>
            <div class="label">
              {{getPercentage(optionCloseProfit, commissionTotal)}}%
            </div>
          </div>
        </div>
      </div>
      <div class="li" @click="$router.push('/market/follow/1')" v-if="followAccount.id">
        <div class="top flex">
          <div class="flex">
            <img class="icon" src="/img/copy/icon2.png" alt="">
            <!-- <div>跟单账户(654454454)</div> -->
            <div>{{ $t('follow.l146') }}({{ followAccount.uid }})</div>
          </div>
          <img class="arrow-right" src="/img/account/right.png" alt="">
        </div>
        <div class="detail flex">
          <div>
            <div class="label">{{ $t('account.l2') }}.USD</div>
            <div class="number" v-if="showAssets">{{ $numToThousand(followAccount.equity) }}</div>
            <div class="number" v-else>*****</div>
          </div>
          <div class="right">
            <div class="label">
              <!-- 今日盈亏 -->
              {{ $t('account.l4') }}
            </div>
            <div class="label">
              {{ (followAccount.equity - followAccount.profit) > 0 ? '+' : "" }}{{ (followAccount.equity - followAccount.profit).toFixed(2) }}
            </div>
            <div class="label">
              {{ (followAccount.equity - followAccount.profit) > 0 ? '+' : "" }}{{getPercentage(followAccount.equity - followAccount.profit, followAccount.equity)}}%
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>
<script>
import { getStorage, setStorage } from '@/utils/localStorage'
import { mapGetters } from "vuex";
import { getAccountList, getUserDayBalanceList } from '@/api/assets'
import { getOptionOrderList } from "@/api/option";
import bus from '@/utils/bus'
export default {
  inject: ['getproductDataObj'],
  data () {
    return {
      profit: {
        'CFD': '',
        'CN': '',
        'US': '',
        'HK': '',
        'USD': '',
      },
      loading: false,
      getUserDayLoading: false,
      getOptionOrderLoading: false,
      commissionTotal: 0,
      showAccountList: getStorage('showAccountList') || 1,
      optionPositionList: [],
      optionCloseList: [],
    }
  },
  computed: {
    ...mapGetters(['accountList', 'showAssets', 'cashInfo', 'currencyList', 'followAccount']),
    productDataObj() {
      return this.getproductDataObj()
    },
    accountListLength() {
      var length = 0
      length += this.accountList.length
      if (this.cashInfo.uid) {
        length += 1
      }
      if (this.followAccount.id) {
        length += 1
      }
      return length ? `(${length})` : ''
    },
    optionAmountTotal() {
      var amountTotal = 0
      this.optionPositionList.forEach(item => {
        amountTotal = Number(this.$bigDecimal.add(amountTotal, this.$bigDecimal.divide(item.amount, this.currencyList[this.serverUtil[item.market]] || 1)))
      })
      return amountTotal
    },
    optionCloseProfit() {
      var commissionTotal = 0
      var profitTotal = 0
      this.optionPositionList.forEach(item => {
        // if (item.status == 6) {
          var commission = item.commission + (item.amount * item.fee / 100)
          commissionTotal = Number(this.$bigDecimal.add(commissionTotal, this.$bigDecimal.divide(commission, this.currencyList[this.serverUtil[item.market]] || 1)))
          var profit = this.getProfit(item)
          profitTotal = this.$bigDecimal.add(profitTotal, profit)
        // }
      })
      this.commissionTotal = commissionTotal
      return profitTotal
    }
  },
  watch: {
    isLogin(val) {
      if (!val) {
        this.profit = {
          'CFD': '',
          'CN': '',
          'US': '',
          'HK': '',
          'USD': '',
        }
        this.commissionTotal = 0
        this.optionPositionList = []
        this.optionCloseList = []
      }
    }
  },
  beforeDestroy () {
    bus.$off('updateUserDayBalance', this.updateUserDayBalance)
  },
  deactivated() {
    bus.$off('updateUserDayBalance', this.updateUserDayBalance)
  },
  activated () {
    this.$store.dispatch('getFollowAccount')
    bus.$on('updateUserDayBalance', this.updateUserDayBalance)
    this.getUserDayBalanceList()
    this.getOptionOrderList()
  },
  created () {
    if (!this.accountList.length) {
      this.getAccountList()
    }
    this.getUserDayBalanceList()
  },
  methods: {
    getAccountList() {
      getAccountList().then((res) => {
        var list = res.list || []
        this.$store.commit('setAccountList',list)
      }).finally(() => {
        this.loading = true
      }).catch(() => {})
    },
    getUserDayBalanceList(){
      this.getUserDayLoading = true
      getUserDayBalanceList().then(res => {
        var obj = res || {}
        Object.keys(obj).forEach(item => {
          this.profit[item] = ((obj[item].yesterday_equity || 0) - (obj[item].today_out || 0) + (obj[item].today_into || 0))
        })
      }).catch(() => {}).finally(() => {
        this.getUserDayLoading = false
      })
    },
    getOptionOrderList() {
      this.getOptionOrderLoading = true
      getOptionOrderList({
        pageNum: 1,
        status:'[4]'
      }).then(res => {
        this.optionPositionList = res.list || []
        var symbolList = []
        this.optionPositionList.forEach(item => {
          if (this.updateSymbolList.indexOf(item.code) == -1) {
            symbolList.push(item.code)
          }
        })
        bus.$emit("alterProductData", {
          getData: symbolList,
          subscribeList: symbolList
        });
      }).catch(() => {}).finally(() => {
        this.getOptionOrderLoading = false
      })
    },
    getProfit(item) {
      if (this.productDataObj[item.code]) {
        var rate = (this.productDataObj[item.code].bid - item.open_price) / item.open_price
        if (item.standard == 105) {
          rate -= 0.05
        }
        var profit = item.amount * rate
        return profit > 0 ? profit : 0
      }
      return 0
    },
    getOptionOrderList1() {
      getOptionOrderList({
        closeDate: this.$parseTime(new Date(), '{y}/{m}/{d}'),
        pageNum: 1,
        status:'[6]'
      }).then(res => {
        this.optionCloseList = res.list || []
      }).catch(() => {})
    },
    updateUserDayBalance() {
      this.getUserDayBalanceList()
    },
    getPercentage(value, equity) {
      if (value === '' || !equity) {
        return '0.00'
      }
      return (value/equity * 100).toFixed(2)
    },
    toggleList() {
      this.showAccountList = this.showAccountList == 1 ? 2 : 1
      setStorage('showAccountList', this.showAccountList)
    }
  }
}
</script>
<style lang="less" scoped>
.title {
  padding: 15px 11px 10px 0;
  justify-content: space-between;
  font-size: 18px;
  line-height: 20px;
  font-weight: 600;
  color: var(--color-1-);
  .arrow-down {
    cursor: pointer;
    transform: rotateZ(180deg);
    transition: transform 0.5s;
    width: 17px;
    &.active {
      transform: rotateZ(0);
    }
  }
}
.li {
  padding: 16px 15px;
  border-radius: 10px;
  border: 1px solid var(--border1-);
  cursor: pointer;
  &+.li {
    margin-top: 10px;
  }
  .top {
    justify-content: space-between;
    color: var(--color-1-);
    font-size: 16px;
    margin-bottom: 15px;
    .flex {
      column-gap: 6px;
    }
    .icon {
      width: 18px;
    }
    .arrow-right {
      width: 8px;
    }
  }
}
.detail {
  justify-content: space-between;
  .number {
    font-size: 18px;
    font-weight: 600;
    margin-top: 9px;
  }
  .right {
    text-align: right;
  }
  .label {
    font-size: 12px;
    color: var(--color-3-);
    &+.label {
      margin-top: 5px;
    }
  }
}
</style>