<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">
                <div>
                  下单设置
                  {{ $t('exchange.l68') }}
                </div>
              </div> -->
              <div class="item flex" @click="settingPop=true;showPopover=false">
                <div>
                  <!-- 通知设置 -->
                  {{ $t('market.l31') }}
                </div>
              </div>
              <div class="item flex" @click="$router.push('/help')">
                <div>
                  <!-- 帮助中心 -->
                  {{ $t('home.l26') }}
                </div>
              </div>
              <div class="item flex" @click="$router.push('/chat')">
                <div>
                  <!-- 客服中心 -->
                  {{ $t('market.l32') }}
                </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 class="right">
            <div class="name">{{ serverName[accountInfo.server] || accountInfo.server }}({{ accountInfo.account }})</div>
            <div class="free flex">
              <!-- 现金 -->
              <div>{{ $t('exchange.l38') }}:{{ $numToThousand(accountInfo.margin_free) }}{{ serverUtil[accountInfo.server] }}</div>
              <!-- 最大购买力 -->
              <div>{{ $t('account.l24') }}:{{ $numToThousand($bigDecimal.multiply(accountInfo.margin_free, (symbolInfo.margin_divider1 || symbolCopy.margin_divider || accountInfo.serverBean.leverage))) }}{{ serverUtil[accountInfo.server] }}</div>
            </div>
          </div>
        </div>
        <i class="el-icon-arrow-right"></i>
      </div>
    </van-sticky>
    <complex @serviceTipsPopshow="serviceTipsPop = true" @deposit="depositPop = true" v-if="type == '1'" :symbolCopy="symbolCopy" :accountInfo="accountInfo" :symbol="symbol"/>
    <easy @serviceTipsPopshow="serviceTipsPop = true" @deposit="depositPop = true" v-if="type == '2'" :symbolCopy="symbolCopy" :accountInfo="accountInfo" :symbol="symbol"/>
    <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>
    <van-popup v-model="serviceTipsPop" round position="bottom">
      <serviceTips @cancel="serviceTipsPop = false" v-if="serviceTipsPop"/>
    </van-popup>
    <van-popup get-container="body" v-model="settingPop" round position="bottom">
      <settingView @cancel="settingPop = false" v-if="settingPop" />
    </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 settingView from "@/view/market/favoriteView/components/setting.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";
import serviceTips from "@/view/productDetail/components/serviceTips.vue";
export default {
  components: {
    accountList,
    complex,
    easy,
    positionListView,
    entrustListView,
    historyListView,
    toDepositPop,
    noticeView,
    serviceTips,
    settingView
  },
  inject: ['getproductDataObj'],
  data () {
    return {
      symbol: '',
      type: '2',
      symbolCopy: {},
      positionList: [],
      entrustList: [],
      listType: 1,
      accountId: '',
      ajaxSign: 0,
      accountInfo1: {},
      accountShow: false,
      showPopover: false,
      depositPop: false,
      activeNoticeShow: true,
      serviceTipsPop: false,
      settingPop: false,
    }
  },
  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.symbolCopy.market]
    },
    accountInfo() {
      var info = this.accountInfo1
      this.accountList.forEach(item => {
        if (this.accountId) {
          if (this.accountId == item.id) {
            info = item
          }
          return
        }
        if(item.server == this.symbolInfo.market) {
          info = item
        }
      })
      return info
    }
  },
  beforeDestroy() {
    bus.$off('routerBack', this.routerBack)
    bus.$off('updateOrder', this.updateOrder)
    bus.$off('updateSymbol', this.updateSymbol)
  },
  watch: {
    'accountInfo.account'(val) {
      if (val) {
        this.updateOrder()
      }
    },
    'symbolInfo.market'() {
      if (this.symbolCopy.market && !this['market' + this.symbolCopy.market]) {
        this.$store.dispatch('getProductVacationList', this.symbolCopy.market)
      }
    },
    '$route'() {
      this.symbol = this.$route.params.symbol
      if (this.symbol) {
        this.getMargin()
      }
      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("alterProductData", {
          subscribeList: [this.symbol],
        });
      }
      this.getMargin()
    }
    this.type = getStorage('exchangeType') || '2'
    if (this.isLogin) {
      bus.$emit('updateAssets', ['getAccountList'])
      // if (this.accountInfo.account) {
      //   this.getPositionList()
      //   this.getEntrustList()
      // }
      var serviceTipsPop = sessionStorage.getItem('serviceTipsPop')
      if (serviceTipsPop) {
        this.serviceTipsPop = JSON.parse(serviceTipsPop)
        sessionStorage.removeItem('serviceTipsPop')
      }
    }
    bus.$on('routerBack', this.routerBack)
    bus.$on('updateOrder', this.updateOrder)
    bus.$on('updateSymbol', this.updateSymbol)
  },
  methods: {
    getMargin() {
      getProductList({
        symbol: JSON.stringify([this.symbol])
      }).then(res => {
        var list = res.list || []
        bus.$emit("alterProductData", {
          setData: list,
        });
        this.symbolCopy = list[0] || {}
        if (this.symbolCopy.market == 'CFD') {
          var list1 = []
          if (this.symbolCopy.profit_mode == 0) {
            var symbol = this.symbolCopy.symbol.slice(3, 6)
            if (symbol != 'USD') {
              list1.push(symbol + 'USD')
              list1.push('USD' + symbol)
            }
          } else {
            if (this.symbolCopy.currency != 'USD') {
              list1.push(this.symbolCopy.currency + 'USD')
              list1.push('USD' + this.symbolCopy.currency)
            }
          }
          if (list1.length == 1 && list1.indexOf(this.symbolCopy.symbol) !== -1) {
            return
          }
          bus.$emit("alterProductData", {
            getData: list1
          });
        }
      }).catch(() => {})
    },
    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) {
        return
      }
      if (this.ajaxSign == 2) {
        var symbolList = this.symbol ? [this.symbol] : [];
        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() {
      var positionList = this.positionList
      positionList.forEach((item, index) => {
        var 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) {
      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'
    },
    routerBack() {
      if (!this.symbol) {
        this.symbol = this.$route.params.symbol
      }
    }
  }
}
</script>
<style lang="less" scoped>
.page {
  min-height: 100vh;
  background-color: #F6F6F6;
}
.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 16px 9px;
  cursor: pointer;
  .left {
    display: flex;
    align-items: flex-start;
    column-gap: 5px;
    font-size: 12px;
    color: #A4A4A4;
  }
  .right {
    flex: 1;
    min-width: 0px;
  }
  .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: #B6B6B6;
    font-size: 20px;
    margin-right: -2px;
  }
}
.order-box {
  background-color: var(--bg-);
  padding: 16px 16px 0;
}
.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 16px 17px;
  text-align: center;
  font-size: 12px;
  color: #AEAEAE;
  background-color: #fff;
}
.popover-body {
  padding: 0 10px;
  .item {
    cursor: pointer;
    height: 46px;
    font-size: 14px;
    width: 100px;
    line-height: 1;
    text-align: center;
    justify-content: center;
    &+.item {
      border-top: 1px solid #F6F6F6;
    }
  }
}
</style>