<template>
  <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 :border="false" 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 :border="false" 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">
      <van-row gutter="20">
        <van-col span="12">
          <div class="flex">
            <div class="label">
              <!-- 数量 -->
              {{ $t('common.l25') }}
            </div>
            <div class="val">{{ $bigDecimal.multiply(volume, symbolInfo.contract_size) }}</div>
          </div>
        </van-col>
        <van-col span="12">
          <div class="flex">
            <!-- 可用现金说明：可用现金是客户账号中可以用于交易的资金。 -->
            <div class="label lab1" @click="descriptionPopShow($t('account.l88'), $t('account.l89'))">
              <!-- 可用资金 -->
              {{ $t('exchange.l46') }}
            </div>
            <div class="val" v-if="accountInfo.account">{{ $numToThousand(accountInfo.margin_free) }}</div>
            <div class="val" v-else>0.00</div>
          </div>
        </van-col>
      </van-row>
      <van-row gutter="20">
        <van-col span="12">
          <div class="flex">
            <div class="label lab1" @click="maxLeverPop = true">
              <!-- 最大杠杆 -->
              {{ $t('exchange.l86') }}
            </div>
            <div class="val" v-if="symbolCopy.symbol">{{ (symbolInfo.margin_divider1 || symbolCopy.margin_divider).toFixed(0) }}</div>
          </div>
        </van-col>
        <van-col span="12">
          <div class="flex">
            <div class="label">
              <!-- 最大可买 -->
              {{ $t('exchange.l87') }}
            </div>
            <div class="val" v-if="accountInfo.account">{{ maxBuy }} {{ $t('exchange.l98') }}</div>
            <div class="val" v-else>0 {{ $t('exchange.l98') }}</div>
          </div>
        </van-col>
      </van-row>
    </div>
    <div class="box2 flex">
      <div class="label">
        <!-- 止损 -->
        {{ $t('exchange.l4') }}
        <!-- <i class="el-icon-warning-outline"></i> -->
      </div>
      <div class="right flex">
        <div class="flex">
          <van-field :border="false" input-align="center" v-model="sl" type="number" />
        </div>
        <div class="icon-box flex">
          <i class="el-icon-minus" @click="addsl(1)"></i>
          <i class="el-icon-plus" @click="addsl(2)"></i>
        </div>
      </div>
    </div>
    <div class="box2 flex">
      <div class="label">
        <!-- 止盈 -->
        {{ $t('exchange.l5') }}
        <!-- <i class="el-icon-warning-outline"></i> -->
      </div>
      <div class="right flex">
        <div class="flex">
          <van-field :border="false" input-align="center" v-model="tp" type="number" />
        </div>
        <div class="icon-box flex">
          <i class="el-icon-minus" @click="addtp(1)"></i>
          <i class="el-icon-plus" @click="addtp(2)"></i>
        </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" v-if="symbolCopy.enable == 1">
      <div class="btn-box flex">
        <div class="btn buy" @click="submitClick(0)">
          <!-- 买入 -->
          {{ $t('exchange.l50') }}
        </div>
        <div class="btn sell" @click="submitClick(1)">
          <!-- 卖出 -->
          {{ $t('exchange.l51') }}
        </div>
      </div>
    </div>
    <div class="box3" v-else>
      <div class="btn-box">
        <div class="btn dis">
          <!-- 该标的暂不支持交易 -->
          {{ $t('product.l92') }}
        </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="openShow" round position="bottom">
      <openPop :type="type" @cancel="openShow = false" @success="openPosition" v-if="openShow"/>
    </van-popup>
    <van-popup v-model="textDescriptionPop" round position="bottom">
      <textDescription :title="title" :text="text"/>
    </van-popup>
    <van-popup v-model="maxLeverPop" round position="bottom">
      <maxLever/>
    </van-popup>
  </div>
</template>
<script>
import priceType from "./priceType.vue";
import termType from "./termType.vue";
import openPop from "./openPop.vue";
import textDescription from "@/components/textDescription";
import maxLever from "@/components/textDescription/maxLever.vue";
import bus from '@/utils/bus'
import { openPosition, openEntrust } from "@/api/exchange";
import { marketPoint } from "@/utils/config";
import { getStorage, setStorage } from '@/utils/localStorage'
export default {
  props: ['symbol', 'accountInfo', 'symbolCopy'],
  components: {
    priceType,
    termType,
    openPop,
    textDescription,
    maxLever
  },
  data () {
    return {
      price: '',
      volume: '1.00',
      tp: '0',
      sl: '0',
      type: 2,
      term: 1,
      openCmd: 0,
      openShow: false,
      openPopShowSign: false,
      termShow: false,
      typeShow: false,
      textDescriptionPop: false,
      maxLeverPop: false,
      title: '',
      text: '',
    }
  },
  inject: ['getproductDataObj'],
  computed: {
    productDataObj() {
      return this.getproductDataObj()
    },
    symbolInfo() {
      return this.productDataObj[this.symbol] || {}
    },
    rate() {
      var rate = 1
      var currencyData = this.productDataObj[this.symbol]
      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
          }
        }
      } 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
        }
      }
      return rate
    },
    maxBuy() {
      if (this.type == 1 && !Number(this.price)) {
        return '--'
      }
      var a = this.$bigDecimal.multiply(this.type == 1 ? (Number(this.price)) : this.productDataObj[this.symbol].ask, this.symbolInfo.contract_size)
      if(this.symbolInfo.margin_initial == 0){
        a = this.$bigDecimal.multiply(a, this.rate)
      } else if(this.symbolInfo.margin_initial > 0 ){
        a = this.$bigDecimal.multiply(this.symbolInfo.margin_initial, this.rate)
      }
      return Number(this.$bigDecimal.divide(this.$bigDecimal.multiply(this.accountInfo.margin_free, this.symbolInfo.margin_divider1 || (this.symbolCopy.margin_divider || 1)), a)).toFixed(2)
    },
  },
  watch: {
    'symbolInfo.market'() {
      if (this.appParams.marketVolume && this.symbolInfo.market) {
        if (this.symbolInfo.market !== 'CFD') {
          this.volume = 1
          return
        }
        this.volume = Number(this.appParams.marketVolume[this.symbolInfo.market]).toFixed(2)
      }
    },
    'appParams.marketVolume': {
      handler() {
        if (this.appParams.marketVolume && this.symbolInfo.market) {
          if (this.symbolInfo.market !== 'CFD') {
          this.volume = 1
          return
        }
          this.volume = Number(this.appParams.marketVolume[this.symbolInfo.market]).toFixed(2)
        }
      },
      deep: true
    }
  },
  created () {
    this.openPopShowSign = getStorage('openPopShowSign') || false;
    if (this.appParams.marketVolume && this.symbolInfo.market) {
      if (this.symbolInfo.market !== 'CFD') {
        this.volume = 1
        return
      }
      this.volume = Number(this.appParams.marketVolume[this.symbolInfo.market]).toFixed(2)
    }
  },
  methods: {
    submitClick(cmd) {
      if (!this.isLogin) {
        this.$router.push('/login?rejectUrl=' + this.$route.path)
        return
      }
      if (this.userInfo.group == 9999) {
        bus.$emit('abnormalPopSign')
        return
      }
      // if (cmd === 0 && this.buyDisable) {
      //   return
      // }
      // if (cmd === 1 && this.sellDisable) {
      //   return
      // }
      var trade_protocol = this.userInfo.trade_protocol ? JSON.parse(this.userInfo.trade_protocol) : [];
      var sign = 0
      trade_protocol.forEach(item => {
        if (['user', 'tradeconfirm', 'risk', 'legal'].indexOf(item.code) !== -1 && item.status == 1) {
          sign += 1
        }
      })
      if (sign !== 4) {
        this.$emit('serviceTipsPopshow')
        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
      }
      var point = Number(this.$bigDecimal.multiply(this.symbolInfo.point, marketPoint[this.symbolInfo.market]))
      var tp = Number(this.tp)
      var sl = Number(this.sl)
      if (tp) {
        if (cmd == 0) {
          if (tp <= Number(this.productDataObj[this.symbol].ask + point)) {
            this.$notify({
              // message: '止盈价至少高于现价' + point,
              message: this.$t('exchange.l82').replace('{p}', this.$handleDigits(point, this.symbolInfo.digits)),
              type: 'danger'
            })
            return
          }
        } else {
          if (tp >= Number(this.productDataObj[this.symbol].ask - point)) {
            this.$notify({
              // message: '止盈价至少低于现价' + point,
              message: this.$t('exchange.l83').replace('{p}', this.$handleDigits(point, this.symbolInfo.digits)),
              type: 'danger'
            })
            return
          }
        }
      }
      if (sl) {
        if (cmd == 0) {
          if (sl >= Number(this.productDataObj[this.symbol].ask - point)) {
            this.$notify({
              // message: '止损价至少低于现价' + point,
              message: this.$t('exchange.l84').replace('{p}', this.$handleDigits(point, this.symbolInfo.digits)),
              type: 'danger'
            })
            return
          }
        } else {
          if (sl <= Number(this.productDataObj[this.symbol].ask + point)) {
            this.$notify({
              // message: '止损价至少高于现价' + point,
              message: this.$t('exchange.l85').replace('{p}', this.$handleDigits(point, this.symbolInfo.digits)),
              type: 'danger'
            })
            return
          }
        }
      }
      if (this.type == 2) {
        this.openCmd = cmd
        if (this.openPopShowSign) {
          this.openPosition()
        } else {
          this.openShow = true
        }
      }
      if (this.type == 1) {
        var cmd1 = 0
        var price = Number(this.price)
        if (cmd == 0) {
          if (price <= Number(this.productDataObj[this.symbol].ask + point) && price >= Number(this.productDataObj[this.symbol].ask - point)) {
            this.$notify({
              // message: '价格与现价至少相差' + point,
              message: this.$t('exchange.l81').replace('{p}', this.$handleDigits(point, this.symbolInfo.digits)),
              type: 'danger'
            })
            return
          }
          if (price > this.productDataObj[this.symbol].ask) {
            cmd1 = 4
          } else {
            cmd1 = 2
          }
        } else {
          if (price <= Number(this.productDataObj[this.symbol].bid + point) && price >= Number(this.productDataObj[this.symbol].bid - point)) {
            this.$notify({
              // message: '价格与现价至少相差' + point,
              message: this.$t('exchange.l81').replace('{p}', this.$handleDigits(point, this.symbolInfo.digits)),
              type: 'danger'
            })
            return
          }
          if (price > this.productDataObj[this.symbol].bid) {
            cmd1 = 3
          } else {
            cmd1 = 5
          }
        }
        this.openCmd = cmd1
        if (this.openPopShowSign) {
          this.openEntrust()
        } else {
          this.openShow = true
        }
      }
    },
    openPosition(sign) {
      if (this.type == 1) {
        this.openEntrust(sign)
        return
      }
      this.fullscreenLoading = true
      openPosition({
        account: this.accountInfo.account,
        symbol: this.symbol,
        cmd: this.openCmd,
        volume: this.volume,
        server: this.accountInfo.server,
        tp: Number(this.tp) === 0 ? '' : Number(this.tp),
        sl: Number(this.sl) === 0 ? '' : Number(this.sl),
      }).then(() => {
        this.$notify({
          // message: '下单成功',
          message: this.$t('exchange.l54'),
          type: 'success'
        })
        this.openShow = false
        if (sign) {
          this.openPopShowSign = true
          setStorage('openPopShowSign', true)
        }
        // bus.$emit('updateAssets', ['getAccountList'])
        // bus.$emit('updateOrder')
      }).finally(() => {
        this.fullscreenLoading = false
      }).catch((err) => {
        if (err.code && (err.code == 134 || err.code == 3004)) {
          this.$emit('deposit')
        }
      })
    },
    openEntrust(sign) {
      this.fullscreenLoading = true
      openEntrust({
        account: this.accountInfo.account,
        symbol: this.symbol,
        cmd: this.openCmd,
        price: this.price,
        expiration: this.term,
        volume: this.volume,
        server: this.accountInfo.server,
        tp: Number(this.tp) === 0 ? '' : Number(this.tp),
        sl: Number(this.sl) === 0 ? '' : Number(this.sl),
      }).then(() => {
        this.$notify({
          // message: '下单成功',
          message: this.$t('exchange.l54'),
          type: 'success'
        })
        this.openShow = false
        if (sign) {
          this.openPopShowSign = true
          setStorage('openPopShowSign', true)
        }
        // 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)) + ''
      }
    },
    addsl(type) {
      if (type == 1) {
        if (!Number(this.sl)) {
          return
        }
        this.sl = Number(this.$bigDecimal.subtract(Number(this.sl) || 0, this.symbolInfo.point)) + ''
      }
      if (type == 2) {
        this.sl = Number(this.$bigDecimal.add(Number(this.sl) || 0, this.symbolInfo.point)) + ''
      }
    },
    addtp(type) {
      if (type == 1) {
        if (!Number(this.tp)) {
          return
        }
        this.tp = Number(this.$bigDecimal.subtract(Number(this.tp) || 0, this.symbolInfo.point)) + ''
      }
      if (type == 2) {
        this.tp = Number(this.$bigDecimal.add(Number(this.tp) || 0, this.symbolInfo.point)) + ''
      }
    },
    addVolume(type) {
      if (type == 1) {
        if (this.symbolInfo.market !== 'CFD') {
          if (!Number(this.volume) || Number(this.volume) <= 1) {
            return
          }
          this.volume = Number(this.$bigDecimal.subtract(Number(this.volume) || 0, 1)) + ''
          return
        }
        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) {
        if (this.symbolInfo.market !== 'CFD') {
          this.volume = Number(this.$bigDecimal.add(Number(this.volume) || 0, 1)) + ''
          return
        }
        this.volume = Number(this.$bigDecimal.add(Number(this.volume) || 0, 0.01)) + ''
      }
    },
    changePrice() {
      this.price = this.$handleDigits(this.symbolInfo.ask, this.symbolInfo.digits) + ''
    },
    selectTypeBack(type) {
      this.typeShow = false
      if (this.type == type) {
        return
      }
      this.tp = '0'
      this.sl = '0'
      this.type = type
      this.price = this.$handleDigits(this.symbolInfo.ask, this.symbolInfo.digits) + ''
    },
    selectTermBack(term) {
      this.term = term
      this.termShow = false
    },
    descriptionPopShow(title, text) {
      this.title = title
      this.text = text
      this.textDescriptionPop = true
    }
  }
}
</script>
<style lang="less" scoped>
.box2 {
  column-gap: 7px;
  border-bottom: 1px solid #F6F6F6;
  font-size: 13px;
  height: 45px;
  .label {
    width: 127px;
    color: #888888;
  }
  .right {
    flex: 1;
    justify-content: space-between;
    min-width: 10%;
    max-width: 100%;
  }
  .el-icon-arrow-right {
    font-size: 18px;
    color: #AAAAAA;
  }
  .icon-box {
    column-gap: 13px;
  }
  .el-icon-plus, .el-icon-minus {
    font-size: 18px;
    color: #B6B6B6;
  }
  .icon {
    width: 18px;
  }
  .van-field {
    padding: 0 15px 0 0;
  }
}
.box4 {
  padding: 15px 0 19px;
  font-size: 12px;
  border-bottom: 1px solid #F6F6F6;
  .van-row + .van-row {
    margin-top: 10px;
  }
  .flex {
    column-gap: 7px;
  }
  .label {
    color: #888888;
    max-width: 50%;
    &.lab1 {
      cursor: pointer;
      text-decoration: underline dotted #979797;
      text-underline-offset: 3px;
    }
  }
  .val {
    flex: 1;
    min-width: 0;
    text-align: right
  }
}
.box3 {
  padding: 18px 0 16px;
  .btn-box {
    flex: 1;
    column-gap: 11px;
    position: relative;
  }
  .btn {
    flex: 1;
    cursor: pointer;
    font-size: 16px;
    color: #fff;
    line-height: 41px;
    text-align: center;
    border-radius: 21px;
    font-weight: 600;
  }
  .buy {
    background-color: var(--red-);
    &.dis {
      cursor: not-allowed;
      opacity: 0.5;
    }
  }
  .sell {
    background-color: var(--green-);
    &.dis {
      cursor: not-allowed;
      opacity: 0.5;
    }
  }
  .dis {
    cursor: not-allowed;
    color: #A5A5A5;
    font-weight: 400;
    background-color: #f4f4f4;
  }
  .icon1 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 24px;
  }
  .img-box {
    column-gap: 3px;
  }
  .icon {
    width: 22px;
  }
}
</style>