<template>
  <div class="components" v-loading.body.fullscreen="fullscreenLoading" element-loading-background="rgba(255, 255, 255, 0)">
    <div class="place" v-if="!symbol">
      <div class="search-box flex" @click="searchShow = true">
        <img class="img" src="/img/exchange/search.png" alt="">
        <div>
          <!-- 请输入代码 -->
          {{ $t('exchange.l40') }}
        </div>
      </div>
    </div>
    <div class="section" v-if="symbol">
      <div class="box flex" @click="searchShow = true">
        <div>
          <div class="name" v-if="language == 'zh-CN'">
            {{ symbolInfo.title }}
          </div>
          <div class="name" v-else-if="language == 'zh-TW'">
            {{ symbolInfo.name_cht || symbolInfo.title }}
          </div>
          <div class="name" v-else>
            {{ symbolInfo.name_en || (symbolInfo.market == 'CFD' ? symbolInfo.symbol : symbolInfo.title) }}
          </div>
          <div class="code">{{ symbol }}</div>
        </div>
        <div class="flex right" v-if="symbolInfo.symbol">
          <chart :count="40" :info="symbolInfo" id="easychart" width="48px" height="27px" />
          <div>{{ $handleDigits(productDataObj[symbol].ask, symbolInfo.digits) }}</div>
          <div>{{ productDataObj[symbol].percentage > 0 ? '+' : ''  }}{{ productDataObj[symbol].percentage }}%</div>
        </div>
      </div>
      <div class="de-box">
        <div class="de-top flex">
          <div class="left" v-if="bidVolPer">{{ bidVolPer }}%</div>
          <div class="line-box flex">
            <div class="line1" :style="{ width: bidVolPer + '%' }" v-if="bidVolPer"></div>
            <div class="line2" :style="{ width: askVolPer + '%' }" v-if="askVolPer"></div>
          </div>
          <div class="right" v-if="askVolPer">{{ askVolPer }}%</div>
        </div>
        <div class="de-bottom flex">
          <div class="dep">
            <div class="left flex" v-for="(item, index) in bids" :key="'a' + index">
              <div class="flex">
                <div class="index">{{ index + 1 }}</div>
                <div class="price">{{ $handleDigits(item.price, symbolInfo.digits) }}</div>
              </div>
              <div>{{ Number(item.volume) }}</div>
            </div>
          </div>
          <div class="dep">
            <div class="right flex" v-for="(item, index) in asks" :key="index">
              <div class="flex">
                <div class="index">{{ index + 1 }}</div>
                <div class="price">{{ $handleDigits(item.price, symbolInfo.digits) }}</div>
              </div>
              <div>{{ Number(item.volume) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="section" v-if="symbolInfo.symbol">
      <div class="box2 flex">
        <div class="label">
          <!-- 方向 -->
          {{ $t('exchange.l18') }}
        </div>
        <div class="right flex">
          <div class="buy btn" :class="{'active': orderType == 'buy'}" @click="changeOrderType('buy')">
            <!-- 买入 -->
            {{ $t('exchange.l50') }}
          </div>
          <div class="tag-box" :class="orderType + '1'">
            <div class="tag"></div>
          </div>
          <div class="btn sell" :class="{'active': orderType == 'sell'}" @click="changeOrderType('sell')">
            <!-- 卖出 -->
            {{ $t('exchange.l51') }}
          </div>
        </div>
      </div>
      <div class="box2 flex">
        <div class="label">
          <!-- 类型 -->
          {{ $t('exchange.l41') }}
          <i class="el-icon-warning-outline"></i>
        </div>
        <div class="right flex" @click="typeShow = true">
          <div class="type">
            <!-- 限价单   市价单-->
            {{ type == 1 ? $t('exchange.l42') : $t('exchange.l43') }}
          </div>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="box2 flex" v-if="type == 1">
        <div class="label">
          <!-- 价格 -->
          {{ $t('market.l4') }}
        </div>
        <div class="right flex">
          <div class="flex">
            <van-field v-model="price" type="number" />
          </div>
          <div class="icon-box flex">
            <i class="el-icon-minus" @click="addPrice(1)"></i>
            <i class="el-icon-plus" @click="addPrice(2)"></i>
          </div>
        </div>
      </div>
      <div class="box2 flex">
        <div class="label">
          <!-- 手数 -->
          {{ $t('exchange.l16') }}
          <i class="el-icon-warning-outline"></i>
        </div>
        <div class="right flex">
          <div class=" flex">
            <van-field v-model="volume" type="number" />
          </div>
          <div class="icon-box flex">
            <i class="el-icon-minus" @click="addVolume(1)"></i>
            <i class="el-icon-plus" @click="addVolume(2)"></i>
          </div>
        </div>
      </div>
      
      <div class="box4 flex">
        <div class="left flex">
          <div>
            <div class="label mr">
              <!-- 数量 -->
              {{ $t('common.l25') }}
            </div>
            <div class="label mr">
              <!-- 当前杠杆 -->
              {{ $t('exchange.l44') }}
            </div>
          </div>
          <div>
            <div class="mr">{{ $bigDecimal.multiply(volume, symbolInfo.contract_size) }}</div>
            <div class="mr">{{ (symbolInfo.contract_size1 || symbolInfo.margin_divider).toFixed(0) }}</div>
          </div>
        </div>
        <div class="left flex">
          <div>
            <div class="label mr">
              <!-- 交易金额 -->
              {{ $t('exchange.l45') }}
            </div>
            <div class="label mr">
              <!-- 可用资金 -->
              {{ $t('exchange.l46') }}
            </div>
          </div>
          <div>
            <div class="mr" v-if="orderType == 'buy'">{{ sumMoney }}</div>
            <div class="mr" v-if="orderType == 'sell'">{{ sumMoney1 }}</div>
            <div class="mr" v-if="accountInfo.account">{{ $numToThousand($handleDigits(accountInfo.margin_free)) }}</div>
            <div class="mr" v-else>0.00</div>
          </div>
        </div>
      </div>
      <div class="box2 flex" v-if="type == 1">
        <div class="label">
          <!-- 期限 -->
          {{ $t('exchange.l47') }}
          <i class="el-icon-warning-outline"></i>
        </div>
        <div class="right flex" @click="termShow = true">
          <div class="type">
            <!-- 当日有效   撤单前有效-->
            {{ term == 1 ? $t('exchange.l48') : $t('exchange.l49') }}
          </div>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="box3">
        <div class="btn-box">
          <div class="btn buy" v-if="orderType == 'buy'" @click="submitClick(0)">
            <!-- 买入 -->
            {{ $t('exchange.l50') }}
          </div>
          <div class="btn sell" v-if="orderType == 'sell'" @click="submitClick(1)">
            <!-- 卖出 -->
            {{ $t('exchange.l51') }}
          </div>
        </div>
      </div>
    </div>
    <van-popup v-model="typeShow" round position="bottom">
      <priceType :type="type" @success="selectTypeBack"/>
    </van-popup>
    <van-popup v-model="termShow" round position="bottom">
      <termType :term="term" @success="selectTermBack"/>
    </van-popup>
    <van-popup v-model="searchShow" position="right" :style="{ width: '100%' }">
      <search :market="accountInfo.market || symbolInfo.market" v-if="searchShow" type="1" @success="searchBack" @cancel="searchShow = false"/>
    </van-popup>
  </div>
</template>
<script>
import chart from "@/components/eChart/index.vue";
import priceType from "./priceType.vue";
import termType from "./termType.vue";
import search from "./search.vue";
import { openPosition, openEntrust } from "@/api/exchange";
import { getPriceDepth } from "@/api/product";
import bus from '@/utils/bus'
export default {
  props: ['symbol', 'symbolInfo', 'accountInfo'],
  components: {
    priceType,
    termType,
    search,
    chart
  },
  data () {
    return {
      price: '',
      volume: '1.00',
      type: 2,
      term: 1,
      typeShow: false,
      searchShow: false,
      termShow: false,
      orderType: '',
      tooltipShow: false,
      asks: [],
      bids: [],
      askSign: false,
      bidSign: false
    }
  },
  inject: ['getproductDataObj'],
  computed: {
    productDataObj() {
      return this.getproductDataObj()
    },
    sumMoney() {
      if (this.type == 1 && !Number(this.price)) {
        return '--'
      }
      return Number(this.$bigDecimal.multiply(this.type == 1 ? this.price : this.productDataObj[this.symbol].ask, this.$bigDecimal.multiply(this.volume, this.symbolInfo.contract_size))).toFixed(2)
    },
    sumMoney1() {
      if (this.type == 1 && !Number(this.price)) {
        return '--'
      }
      return Number(this.$bigDecimal.multiply(this.type == 1 ? this.price : this.productDataObj[this.symbol].bid, this.$bigDecimal.multiply(this.volume, this.symbolInfo.contract_size))).toFixed(2)
    },
    availableBuy() {
      if (!Number(this.price)) {
        return '0.00'
      }
      return this.$bigDecimal.multiply(this.accountInfo.margin_free, 50)
    },
    availableSell() {
      if (!Number(this.price)) {
        return '0.00'
      }
      return this.$bigDecimal.multiply(this.accountInfo.margin_free, 50)
    },
    askVol() {
      return this.asks[0] ? Number(this.asks[0].volume) : 0
    },
    bidVol() {
      return this.bids[0] ? Number(this.bids[0].volume) : 0
    },
    askVolPer() {
      return this.allVol ? Number(this.$bigDecimal.divide(this.askVol, this.allVol) * 100).toFixed(2) : 0
    },
    bidVolPer() {
      return this.allVol ? Number(this.$bigDecimal.divide(this.bidVol, this.allVol) * 100).toFixed(2) : 0
    },
    allVol() {
      return Number(this.$bigDecimal.add(this.askVol, this.bidVol))
    },
    // buyDisable() {
    //   if (!this.isLogin || !Number(this.price) || !Number(this.volume)) {
    //     return false
    //   }
    //   return Number(this.volume) > Number(this.availableBuy)
    // },
    // sellDisable() {
    //   if (!this.isLogin || !Number(this.price) || !Number(this.volume)) {
    //     return false
    //   }
    //   return Number(this.volume) > Number(this.availableBuy)
    // },
  },
  watch: {
    symbol(val) {
      if (val) {
        this.getPriceDepth()
      }
    },
    'symbolInfo.market'() {
      if (this.appParams.marketVolume && this.symbolInfo.market) {
        this.volume = Number(this.appParams.marketVolume[this.symbolInfo.market]).toFixed(2)
      }
    },
    'appParams.marketVolume': {
      handler() {
        if (this.appParams.marketVolume && this.symbolInfo.market) {
          this.volume = Number(this.appParams.marketVolume[this.symbolInfo.market]).toFixed(2)
        }
      },
      deep: true
    }
  },
  beforeDestroy() {
    bus.$off('updateDepth', this.updateDepth)
  },
  created () {
    this.orderType = this.$route.params.type
    bus.$on('updateDepth', this.updateDepth)
    if (this.appParams.marketVolume && this.symbolInfo.market) {
      this.volume = Number(this.appParams.marketVolume[this.symbolInfo.market]).toFixed(2)
    }
    if (this.symbol) {
      this.getPriceDepth()
    }
  },
  methods: {
    submitClick(cmd) {
      if (!this.isLogin) {
        this.$router.push('/login?rejectUrl=' + this.$route.path)
        return
      }
      // if (cmd === 0 && this.buyDisable) {
      //   return
      // }
      // if (cmd === 1 && this.sellDisable) {
      //   return
      // }
      if (this.type == 1) {
        if (!Number(this.price)) {
          this.$notify({
            // message: '请输入价格',
            message: this.$t('exchange.l52'),
            type: 'danger'
          })
          return
        }
      }
      if (!Number(this.volume)) {
        this.$notify({
          // message: '请输入数量',
          message: this.$t('exchange.l53'),
          type: 'danger'
        })
        return
      }
      if (this.type == 2) {
        this.openPosition(cmd)
      }
      if (this.type == 1) {
        let cmd1 = 0
        let price = Number(this.price)
        if (cmd == 0) {
          if (price > this.productDataObj[this.symbol].ask) {
            cmd1 = 4
          } else {
            cmd1 = 2
          }
        } else {
          if (price > this.productDataObj[this.symbol].bid) {
            cmd1 = 3
          } else {
            cmd1 = 5
          }
        }
        this.openEntrust(cmd1)
      }
    },
    openPosition(cmd) {
      this.fullscreenLoading = true
      openPosition({
        account: this.accountInfo.account,
        symbol: this.symbol,
        cmd: cmd,
        volume: this.volume,
        server: this.accountInfo.server
      }).then(() => {
        this.$notify({
          // message: '下单成功',
          message: this.$t('exchange.l54'),
          type: 'success'
        })
        // bus.$emit('updateAssets', ['getAccountList'])
        // bus.$emit('updateOrder')
      }).finally(() => {
        this.fullscreenLoading = false
      }).catch((err) => {
        if (err.code && err.code == 134) {
          this.$emit('deposit')
        }
      })
    },
    openEntrust(cmd) {
      this.fullscreenLoading = true
      openEntrust({
        account: this.accountInfo.account,
        symbol: this.symbol,
        cmd: cmd,
        price: this.price,
        expiration: this.term,
        volume: this.volume,
        server: this.accountInfo.server
      }).then(() => {
        this.$notify({
          // message: '下单成功',
          message: this.$t('exchange.l54'),
          type: 'success'
        })
        // bus.$emit('updateOrder')
      }).finally(() => {
        this.fullscreenLoading = false
      }).catch(() => {

      })
    },
    addPrice(type) {
      if (type == 1) {
        if (!Number(this.price)) {
          return
        }
        this.price = Number(this.$bigDecimal.subtract(Number(this.price) || 0, this.symbolInfo.point)) + ''
      }
      if (type == 2) {
        this.price = Number(this.$bigDecimal.add(Number(this.price) || 0, this.symbolInfo.point)) + ''
      }
    },
    addVolume(type) {
      if (type == 1) {
        if (!Number(this.volume) || Number(this.volume) <= 0.01) {
          return
        }
        this.volume = Number(this.$bigDecimal.subtract(Number(this.volume) || 0, 0.01)) + ''
      }
      if (type == 2) {
        this.volume = Number(this.$bigDecimal.add(Number(this.volume) || 0, 0.01)) + ''
      }
    },
    changePrice() {
      this.price = this.$handleDigits(this.symbolInfo.ask, this.symbolInfo.digits) + ''
    },
    changeOrderType(type) {
      if (this.orderType == type) {
        return
      }
      this.orderType = type
      if (type == 'buy') {
        this.price = this.$handleDigits(this.symbolInfo.ask, this.symbolInfo.digits) + ''
      } else {
        this.price = this.$handleDigits(this.symbolInfo.bid, this.symbolInfo.digits) + ''
      }
    },
    selectTypeBack(type) {
      this.type = type
      this.price = this.$handleDigits(this.symbolInfo.ask, this.symbolInfo.digits) + ''
      this.typeShow = false
    },
    selectTermBack(term) {
      this.term = term
      this.termShow = false
    },
    searchBack(val) {
      this.$router.replace(`/exchange/${val}/buy`)
      this.searchShow = false
    },
    getPriceDepth() {
      getPriceDepth({
        symbol: this.symbol
      }).then(res => {
        this.asks = (res.asks || []).sort((a, b) => Number(a.price) - Number(b.price)).filter(item => Number(item.price)).slice(0, 1);
        this.bids = (res.bids || []).sort((a, b) => Number(b.price) - Number(a.price)).filter(item => Number(item.price)).slice(0, 1);
        // if (this.asks.length == 0 || this.bids.length == 0) {
        //   this.randomDetch()
        // } else {
        //   this.askSign = false
        //   this.bidSign = false
        // }
      }).catch(() => {})
    },
    updateDepth(msg) {
      if (msg.symbol != this.symbol) {
        return
      }
      this.asks = (msg.asks || []).sort((a, b) => Number(a.price) - Number(b.price)).filter(item => Number(item.price)).slice(0, 1)
      this.bids = (msg.bids || []).sort((a, b) => Number(b.price) - Number(a.price)).filter(item => Number(item.price)).slice(0, 1)
      // if (this.asks.length == 0 || this.bids.length == 0) {
      //   this.randomDetch()
      // } else {
      //   this.askSign = false
      //   this.bidSign = false
      // }
    },
    randomDetch() {
      this.asks = this.asks[0] || []
      this.bids = this.bids[0] || []
      if (!this.bids.length && Number(this.symbolInfo.bid)) {
        this.bidSign = true
        this.bids = [{
          price: this.symbolInfo.bid,
          volume: parseInt(Math.random() * 2700) + 300
        }]
      }
      if (!this.asks.length && Number(this.symbolInfo.ask)) {
        this.askSign = true
        this.asks = [{
          price: this.symbolInfo.ask,
          volume: parseInt(Math.random() * 2700) + 300
        }]
      }
    },
  }
}
</script>
<style lang="less" scoped>
.place {
  padding: 15px 18px 0;
  background-color: var(--bg-);
  color: #C3C3C3;
  .search-box {
    cursor: pointer;
    border-radius: 4px;
    border: 1px solid #D9D9D9;
    height: 38px;
    padding: 0 13px;
  }
  .img {
    width: 20px;
  }
}
.section {
  margin-bottom: 8px;
  background-color: var(--bg-);
}
.box {
  padding: 12px 18px;
  color: var(--color-1-);
  justify-content: space-between;
  .name {
    font-size: 15px;
    font-weight: 500;
    margin-bottom: 10px;
  }
  .code {
    color: #AEAEAE;
    font-size: 12px;
  }
  .right {
    column-gap: 26px;
    color: #F24040;
  }
}
.box2 {
  padding: 0 18px;
  column-gap: 7px;
  border-bottom: 1px solid #F0F0F0;
  font-size: 13px;
  height: 39px;
  .label {
    width: 110px;
    color: #7C7C7C;
  }
  .right {
    flex: 1;
    justify-content: space-between;
    min-width: 10%;
    max-width: 100%;
    color: #414141;
  }
  .btn {
    flex: 1;
    text-align: center;
    background-color: #F2F2F2;
    color: #979797;
    line-height: 30px;
    font-size: 16px;
    &.active {
      color: #fff;
    }
  }
  .tag-box {
    position: relative;
    min-width: 30px;
    max-width: 30px;
    height: 30px;
    border: 15px solid;
    border-top-color: #EA4A45;
    border-left-color: #EA4A45;
    border-right-color: #F2F2F2;
    border-bottom-color: #F2F2F2;
    &.sell1 {
      border-top-color: #F2F2F2;
      border-left-color: #F2F2F2;
      border-right-color: #07AC3A;
      border-bottom-color: #07AC3A;
    }
    // overflow: hidden;
    .tag {
      position: absolute;
      height: 50px;
      top: -25px;
      left: 50%;
      transform: translateX(-50%) rotate(45deg);
      width: 4px;
      background-color: #fff;
    }
  }
  .buy{
    border-radius: 31px 0 0 31px;
    &.active {
      background-color: #EA4A45;
    }
  }
  .sell{
    border-radius: 0 31px 31px 0;
    &.active {
      background-color: #07AC3A;
    }
  }
  .type {
    color: #333;
  }
  .el-icon-arrow-right {
    font-size: 18px;
    color: #AAAAAA;
  }
  .icon-box {
    column-gap: 19px;
    color: #313232;
  }
  .el-icon-plus, .el-icon-minus {
    font-size: 18px;
    color: #313232;
  }
  .icon {
    width: 18px;
  }
  .van-field {
    padding: 0 15px 0 0;
  }
}
.row {
  justify-content: flex-end;
  padding: 6px 18px 16px;
  column-gap: 20px;
  font-size: 10px;
  >.flex {
    column-gap: 4px;
  }
  .label {
    color: #7C7C7C;
  }
  .red {
    color: #F24040;
    font-weight: 500;
  }
  .green {
    color: #52C57A;
    font-weight: 500;
  }
  .href {
    color: #F24040;
    border: 0.7px solid #F24040;
    font-size: 8px;
    border-radius: 8px;
    padding: 4px 6px;
    .el-icon-arrow-right {
      font-weight: 600;
    }
  }
}
.box4 {
  justify-content: flex-end;
  padding: 12px 17px;
  font-size: 12px;
  color: #313232;
  column-gap: 48px;
  border-bottom: 1px solid #F0F0F0;
  .label {
    color: #9F9F9F;
  }
  .left {
    column-gap: 8px;
  }
  .mr + .mr {
    margin-top: 10px;
  }
}
.box3 {
  padding: 14px 18px 16px;
  .btn {
    cursor: pointer;
    font-size: 16px;
    color: #fff;
    height: 41px;
    text-align: center;
    border-radius: 21px;
    display: flex;
    align-items: center;
    justify-content: center;
    column-gap: 6px;
  }
  .buy {
    background-color: #FF6F30;
  }
  .sell {
    background-color: #07AC3A;
  }
  .icon {
    width: 16px;
  }
}
.de-box {
  padding: 0 18px 10px;
  .de-top {
    column-gap: 4px;
    justify-content: space-between;
    font-size: 12px;
    margin-bottom: 3px;
    .line-box {
      flex: 1;
      column-gap: 2px;
    }
    .left {
      color: #EA4A45;
    }
    .right {
      color: #07AC3A;
    }
    .line1, .line2 {
      height: 4px;
      border-radius: 2px;
    }
    .line1 {
      background: #EA4A45;
    }
    .line2 {
      background: #07AC3A;
    }
  }
  .de-bottom {
    border-radius: 4px;
    overflow: hidden;
    .dep {
      width: 50%;
      font-size: 12px;
      color: #262626;
    }
    .left {
      background-color: rgba(252, 81, 87, 0.13);
      height: 26px;
      padding-left: 3px;
      padding-right: 6px;
      justify-content: space-between;
      .index {
        background-color: #EA4A45;
      }
      .price {
        color: #EA4A45;
      }
    }
    .right {
      background-color: rgba(149, 198, 156, 0.13);
      height: 26px;
      padding-left: 3px;
      padding-right: 6px;
      justify-content: space-between;
      .index {
        background-color: #07AC3A;
      }
      .price {
        color: #07AC3A;
      }
    }
    .index {
      width: 11px;
      line-height: 11px;
      border-radius: 2px;
      font-size: 10px;
      margin-right: 4px;
      color: #fff;
      text-align: center;
    }
  }
}
</style>