<template>
  <div>
    <!-- 跟单详情 -->
    <BackBar1 :title="$t('follow.l25')"/>
    <div class="header">
      <div class="top">
        <div class="box flex" @click="$router.push('/trade/detail/' + id)">
          <div class="left flex">
            <van-image
              width="36"
              height="36"
              round
              fit="cover"
              :src="expertInfo.header || '/img/home/user.png'"
            />
            <div class="right">
              <div class="flex name-box">
                <div class="name">
                  {{ expertInfo.expert_title }}
                </div>
                <div class="level">
                  {{ expertInfo.expert_level }}
                </div>
              </div>
              <div class="time">
                <!-- 跟单时间 2024-04-17 09:09 -->
                {{ $t('follow.l17') }} {{ expertInfo.insert_datetime }}
              </div>
            </div>
          </div>
          <van-icon name="arrow" />
        </div>
        <div class="box1">
          <van-row gutter="6">
            <van-col span="12">
              <div class="lab">
                <!-- 账户结余(USD) -->
                {{ $t('account.l20') }}(USD)
              </div>
              <div>
                2,000.36
              </div>
            </van-col>
            <van-col span="12">
              <div class="lab">
                <!-- 分润比例 -->
                {{ $t('follow.l26') }}
              </div>
              <div>
                10%
              </div>
            </van-col>
          </van-row>
          <van-row gutter="6">
            <van-col span="12">
              <div class="lab">
                <!-- 已结算盈亏(USD) -->
                {{ $t('follow.l27') }}(USD)
              </div>
              <div :class="expertInfo.profit > 0 ? 'up' : 'down'">
                {{ expertInfo.profit > 0 ? '+' : '' }} {{ $numToThousand(expertInfo.profit) }}
              </div>
            </van-col>
            <van-col span="12">
              <div class="lab">
                <!-- 分润金额(USD) -->
                {{ $t('follow.l28') }}(USD)
              </div>
              <div>
                {{ $numToThousand(expertInfo.expert_profit) }}
              </div>
            </van-col>
          </van-row>
        </div>
        <div class="box2">
          <van-row gutter="6">
            <van-col span="8">
              <div class="lab">
                <!-- 资产净值(USD) -->
                {{ $t('account.l2') }}(USD)
              </div>
              <div>{{ $numToThousand(equity) }}</div>
            </van-col>
            <van-col span="8">
              <div class="lab">
                <!-- 持仓盈亏(USD) -->
                {{ $t('account.l19') }}(USD)
              </div>
              <div :class="{up: allProfit >= 0, down: allProfit < 0}">{{ $numToThousand(allProfit) }} ({{ getPercentage(allProfit, equity) }}%)</div>
            </van-col>
            <van-col span="8">
              <div class="lab">
                <!-- 持仓市值(USD) -->
                {{ $t('account.l21') }}(USD)
              </div>
              <div>{{ $numToThousand(allMarket) }}</div>
            </van-col>
          </van-row>
          <van-row gutter="6">
            <van-col span="8">
              <div class="lab">
                <!-- 可用现金(USD) -->
                {{ $t('account.l23') }}(USD)
              </div>
              <div>{{ $numToThousand(marginFree) }}</div>
            </van-col>
            <van-col span="8">
              <div class="lab">
                <!-- 占用保证金(USD) -->
                {{ $t('account.l22') }}(USD)
              </div>
              <div class="up">{{ $numToThousand(followAccount.margin) }}</div>
            </van-col>
            <van-col span="8">
              <div class="lab">
                <!-- 保证金比例 -->
                {{ $t('account.l84') }}
              </div>
              <div>{{ getPercentage(equity, followAccount.margin) }}%</div>
            </van-col>
          </van-row>
        </div>
        <div class="btns flex">
          <div class="btn ltn" @click="$router.push('/copy/alter/' + id)">
            <!-- 修改设置 -->
            {{ $t('follow.l29') }}
          </div>
          <div class="btn rtn" @click="cancelPop = true">
            <!-- 取消跟单 -->
            {{ $t('follow.l30') }}
          </div>
        </div>
      </div>
      <div class="tabbar flex">
        <div class="bar" :class="{active: type == '1'}" @click="type = '1'">
          <!-- 当前持仓(3) -->
          {{ $t('follow.l31') }}{{ positionList.length ? `(${positionList.length})` : ''}}
        </div>
        <div class="bar" :class="{active: type == '2'}" @click="type = '2'">
          <!-- 历史跟单 -->
          {{ $t('follow.l16') }}{{ historyTotal ? `(${historyTotal})` : ''}}
        </div>
      </div>
    </div>
    <openList :list="positionList" v-if="type == 1" />
    <historyList v-if="type == 2" />
    <van-popup v-model="cancelPop" round position="bottom">
      <cancelCopy :info="expertInfo" @success="cancelBack"/>
    </van-popup>
  </div>
</template>
<script>
import BackBar1 from '@/components/backBar1'
import openList from "./components/openList.vue";
import historyList from "./components/historyList.vue";
import cancelCopy from "./components/cancelCopy.vue";
import { getFollowList, getFollowPositionTradeList, getFollowHistoryTradeList } from "@/api/copy";
import { getProductList } from "@/api/product";
import { mapGetters } from "vuex";
import bus from '@/utils/bus'
export default {
  components: {
    BackBar1,
    openList,
    historyList,
    cancelCopy,
  },
  inject: ['getproductDataObj'],
  data () {
    return {
      type: '1',
      expertInfo: {},
      positionList: [],
      historyTotal: 0,
      cancelPop: false,
      id: '',
      positionSign: false,
      updateSign: false,
      allProfit: 0,
    }
  },
  computed: {
    ...mapGetters(['followAccount']),
    productDataObj() {
      return this.getproductDataObj()
    },
    equity() {
      if(!this.positionSign || !this.updateSign) {
        return this.followAccount.equity
      }
      var equity = Number(this.$bigDecimal.add(this.followAccount.balance, Number(this.allProfit)))
      return equity
    },
    marginFree() {
      if(!this.positionSign || !this.updateSign) {
        return this.followAccount.margin_free
      }
      return this.$bigDecimal.add(this.$bigDecimal.subtract(this.followAccount.balance, Number(this.followAccount.margin)), Number(this.allProfit))
    },
    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
    }
  },
  beforeDestroy() {
    bus.$off('updateSymbol', this.updateSymbol)
  },
  created () {
    this.id = this.$route.params.id
    this.getFollowList()
    this.getFollowPositionTradeList()
    this.getFollowHistoryTradeList()
    this.$store.dispatch('getFollowAccount')
    bus.$on('updateSymbol', this.updateSymbol)
  },
  methods: {
    getFollowPositionTradeList() {
      getFollowPositionTradeList({
        eid: this.id
      }).then(res => {
        this.positionList = res.list || []
        var symbolList = []
        this.positionList.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 = []
          this.positionSign = true
          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)
                symbolList.push(symbol + 'USD')
                symbolList.push('USD' + symbol)
              }
            } else {
              if (item.currency != 'USD') {
                list1.push(item.currency + 'USD')
                symbolList.push(item.currency + 'USD')
                list1.push('USD' + item.currency)
                symbolList.push('USD' + item.currency)
              }
            }
          })
          bus.$emit("alterProductData", {
            getData: list1,
            setData: list,
            subscribeList: [...symbolList]
          });
          this.updateSymbol()
        })
      }).catch(() => {})
    },
    updateSymbol() {
      var positionList = this.positionList
      positionList.forEach((item, index) => {
        var v = item
        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)
      })
    },
    formatMarket(item) {
      var currencyData = this.productDataObj[item.symbol]
      if (currencyData) {
        var market = this.$bigDecimal.multiply(item.close_price, this.$bigDecimal.multiply(item.volume, 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(item.volume, 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) * currencyData.contract_size * rate
            } else if (market1) {
              profit = ((data.open_price - currencyData.ask) * (data.volume) * currencyData.contract_size) / rate
            } else {
              profit = (data.open_price - currencyData.ask) * (data.volume) * currencyData.contract_size
            }
          } else if (data.cmd == '0') {
            if (market2) {
              profit = (currencyData.bid - data.open_price) * (data.volume) * currencyData.contract_size * rate
            } else if (market1) {
              profit = ((currencyData.bid - data.open_price) * (data.volume) * currencyData.contract_size) / rate
            } else {
              profit = (currencyData.bid - data.open_price) * (data.volume) * 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) * currencyData.contract_size * rate
            } else if (market1) {
              profit = (( data.open_price - currencyData.ask) * (data.volume) * currencyData.contract_size) / rate
            } else {
              profit = ((data.open_price - currencyData.ask) * (data.volume) * currencyData.contract_size)
            }
          } else if (data.cmd == '0') {
            if (market2) {
              profit = (currencyData.bid - data.open_price) * (data.volume) * currencyData.contract_size * rate
            } else if (market1) {
              profit = ((currencyData.bid - data.open_price) * (data.volume) * currencyData.contract_size) / rate
            } else {
              profit = ((currencyData.bid - data.open_price) * (data.volume) * currencyData.contract_size)
            }
          }
        }
      } else {
        if (data.cmd == '1') {
          profit = (data.open_price - currencyData.ask) * (data.volume) * currencyData.contract_size
        } else if (data.cmd == '0') {
          profit = (currencyData.bid - data.open_price) * (data.volume) * 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)
    },
    getFollowHistoryTradeList() {
      getFollowHistoryTradeList({
        eid: this.id,
        pageNum: 1,
        pageSize: 1,
      }).then(res => {
        this.historyTotal = res.total
      }).catch(() => {})
    },
    getFollowList() {
      getFollowList({
        eid: this.id
      }).then(res => {
        var list = res.list || []
        this.expertInfo = list[0] || {}
      }).catch(() => {})
    },
    cancelBack() {
      this.cancelPop = false
      this.$router.back()
    }
  }
}
</script>
<style lang="less" scoped>
.header {
  background-color: #fff;
  padding: 0 16px;
  .top {
    border-radius: 8px;
    border: 1px solid #F6F6F6;
    padding: 9px 9px 15px;
  }
}
.box {
  column-gap: 6px;
  justify-content: space-between;
  .left,.right {
    flex: 1;
    min-width: 0;
    max-width: 100%;
  }
  .right {
    padding-left: 10px;
  }
  .name-box {
    column-gap: 4px;
    margin-bottom: 4px;
  }
  .name {
    min-width: 0;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .level {
    border-radius: 2px;
    border: 1px solid #F6F6F6;
    padding: 2px 3px;
    font-weight: 300;
    font-size: 10px;
  }
  .time {
    font-size: 10px;
    color: #888888;
  }
  .van-icon {
    font-size: 18px;
    margin-right: -2px;
    color: #B6B6B6;
  }
}
.box1 {
  padding: 16px 0 16px 20px;
  border-bottom: 1px solid #F6F6F6;
  font-size: 12px;
  .lab {
    color: #B6B6B6;
    margin-bottom: 4px;
  }
  .van-row + .van-row {
    margin-top: 14px;
  }
}
.box2 {
  padding: 13px 0 16px 10px;
  font-size: 10px;
  .lab {
    color: #B6B6B6;
    margin-bottom: 4px;
  }
  .van-row + .van-row {
    margin-top: 14px;
  }
}
.btns {
  column-gap: 7px;
  .btn {
    border: 1px solid #F6F6F6;
    flex: 1;
    text-align: center;
    cursor: pointer;
    line-height: 36px;
  }
}
.tabbar {
  background-color: var(--bg-);
  white-space: nowrap;
  flex-wrap: nowrap;
  overflow-x: auto;
  column-gap: 24px;
  .bar {
    line-height: 52px;
    color: #888888;
    cursor: pointer;
    &.active {
      color: #000000;
      font-weight: 600;
      .line {
        display: block;
      }
    }
  }
}
.up {
  color: var(--red-);
}
.down {
  color: var(--green-);
}
</style>