<template>
  <div>
    <div class="box5 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 input-box">
          <div class="tip2" v-if="tip3Show">
            <div class="text">
              <!-- 至少与当前价相差0.50或5% -->
              {{ $t('exchange.l102').replace('{p}', $handleDigits(point, symbolInfo.digits)).replace('{p1}', percentage) }}
            </div>
            <div class="border"></div>
          </div>
          <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">
        <van-popover placement="bottom-start" v-model="showPopover" trigger="click">
          <div class="popover-ul">
            <div class="li" :class="{active: inputType == 1}" @click="selectInputType(1)">
              <!-- 数量 -->
              {{ $t('common.l25') }}
            </div>
            <div class="li" :class="{active: inputType == 2}" @click="selectInputType(2)">
              <!-- 金额 -->
              {{ $t('account.l40') }}
            </div>
          </div>
          <template #reference>
            <div>
              {{ inputType == 1 ? $t('common.l25') : $t('account.l40') }}<van-icon name="arrow-down" />
            </div>
          </template>
        </van-popover>
      </div>
      <div class="right flex" v-if="inputType == 1">
        <div class="flex input-box">
          <div class="tip1" v-if="tip1Show">
            <div class="text">
              <!-- 非整手数, 请输入500的倍数 -->
              {{ $t('exchange.l100').replace('{p}', symbolInfo.contract_size) }}
            </div>
            <div class="border"></div>
          </div>
          <!-- 请输入数量 -->
          <van-field :border="false" :placeholder="$t('exchange.l53')" v-model="volume" type="digit" />
        </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 class="right flex" v-if="inputType == 2">
        <div class="flex">
          <!-- 请输入金额 -->
          <van-field :border="false" :placeholder="$t('exchange.l99')" v-model="amount" type="number" />
        </div>
        <div class="icon-box flex">
          <i class="el-icon-minus" @click="addAmount(1)"></i>
          <i class="el-icon-plus" @click="addAmount(2)"></i>
        </div>
      </div>
    </div>
    <div class="box2 flex">
      <div class="label">
        {{ inputType == 2 ? $t('common.l25') : $t('account.l40') }}
      </div>
      <div class="right flex" v-if="inputType == 1">
        {{ $numToThousand(sumMoney) }}
      </div>
      <div class="right" v-if="inputType == 2">
        <div class="input-box">
          <div class="tip2" v-if="tip2Show && sumVolume1">
            <div class="text">
              <!-- 已向下取整 -->
              {{ $t('exchange.l101') }}
            </div>
            <div class="border"></div>
          </div>
          {{ sumVolume1 }}
        </div>
      </div>
    </div>
    <div class="box4">
      <van-row gutter="20">
        <van-col span="12">
          <div class="flex">
            <!-- 保证金说明 进行合约交易时，用于保证合约能顺利履行的最小金额。-->
            <div class="label lab1" @click="descriptionPopShow($t('exchange.l90'), $t('exchange.l91'))">
              <!-- 保证金 -->
              {{ $t('exchange.l89') }}
            </div>
            <div class="val" v-if="inputType == 1 && symbolCopy.symbol">{{ $numToThousand(this.$bigDecimal.divide(sumMoney, symbolInfo.margin_divider1 || symbolCopy.margin_divider))}}</div>
            <div class="val" v-if="inputType == 2 && symbolCopy.symbol">{{ $numToThousand(this.$bigDecimal.divide(amount, symbolInfo.margin_divider1 || symbolCopy.margin_divider))}}</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" v-if="orderType == 'buy'">
              <!-- 最大可买 -->
              {{ $t('exchange.l87') }}
            </div>
            <div class="label" v-else>
              <!-- 可卖空 -->
              {{ $t('exchange.l88') }}
            </div>
            <div class="val" v-if="accountInfo.account">{{ maxBuy }}</div>
            <div class="val" v-else>0</div>
          </div>
        </van-col>
      </van-row>
    </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" 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 class="box3" v-else>
      <div class="btn-box flex">
        <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 { setStorage, getStorage } from "@/utils/localStorage";
import { marketPoint } from "@/utils/config";
export default {
  props: ['symbol', 'accountInfo', 'symbolCopy'],
  components: {
    priceType,
    termType,
    openPop,
    textDescription,
    maxLever
  },
  data () {
    return {
      price: '',
      volume: '1',
      amount: '',
      type: 2,
      term: 1,
      typeShow: false,
      termShow: false,
      orderType: '',
      openCmd: 0,
      openShow: false,
      openPopShowSign: false,
      textDescriptionPop: false,
      maxLeverPop: false,
      title: '',
      text: '',
      showPopover: false,
      inputType: 1,
      percentage: 5,
    }
  },
  inject: ['getproductDataObj'],
  computed: {
    productDataObj() {
      return this.getproductDataObj()
    },
    symbolInfo() {
      return this.productDataObj[this.symbol] || {}
    },
    maxBuy() {
      if (this.type == 1 && !Number(this.price)) {
        return '--'
      }
      var a = (this.type == 1 ? (Number(this.price)) : (this.orderType == 'buy' ? this.productDataObj[this.symbol].ask : this.productDataObj[this.symbol].bid))
      return Number(this.$bigDecimal.divide(this.$bigDecimal.multiply(this.accountInfo.margin_free, this.symbolCopy.margin_divider || 1), a)).toFixed(0)
    },
    sumVolume() {
      if (!Number(this.amount)) {
        return 0
      }
      return Number(this.$bigDecimal.divide(this.$bigDecimal.divide(this.amount, this.type == 1 ? this.price : (this.orderType == 'buy' ? this.productDataObj[this.symbol].ask : this.productDataObj[this.symbol].bid)), this.symbolInfo.contract_size))
    },
    sumVolume1() {
      if (!Number(this.sumVolume)) {
        return 0
      }
      return Number(this.$bigDecimal.multiply(Math.floor(this.sumVolume), this.symbolInfo.contract_size))
    },
    sumMoney() {
      if (this.type == 1 && !Number(this.price)) {
        return 0
      }
      return Number(this.$bigDecimal.multiply(this.type == 1 ? this.price : (this.orderType == 'buy' ? this.productDataObj[this.symbol].ask : this.productDataObj[this.symbol].bid), this.volume))
    },
    point() {
      var point1 = Number(this.$bigDecimal.multiply(this.symbolInfo.point, marketPoint[this.symbolInfo.market]))
      var point2 = Number(this.$bigDecimal.divide(this.$bigDecimal.multiply(this.percentage, this.productDataObj[this.symbol].ask), 100))
      return point1 > point2 ? point2 : point1
    },
    tip1Show() {
      return this.volume && !(Number.isInteger(Number(this.$bigDecimal.divide(this.volume, this.symbolInfo.contract_size))))
    },
    tip2Show() {
      return !(Number.isInteger(this.sumVolume))
    },
    tip3Show() {
      var price = Number(this.price)
      return price <= (this.productDataObj[this.symbol].ask + this.point) && price >= (this.productDataObj[this.symbol].ask - this.point)
    }
  },
  watch: {
    // 'symbolInfo.market'() {
      
    // },
  },
  created () {
    this.orderType = this.$route.params.type
    this.openPopShowSign = getStorage('openPopShowSign') || false;
    this.volume = this.symbolInfo.contract_size
  },
  methods: {
    submitClick(cmd) {
      if (!this.isLogin) {
        this.$router.push('/login?rejectUrl=' + this.$route.path)
        return
      }
      if (this.userInfo.group == 9999) {
        bus.$emit('abnormalPopSign')
        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 (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 (this.inputType == 1) {
        if (!Number(this.volume)) {
          this.$notify({
            // message: '请输入数量',
            message: this.$t('exchange.l53'),
            type: 'danger'
          })
          return
        }
        if (this.tip1Show) {
          return
        }
      } else {
        if (!Number(this.amount)) {
          this.$notify({
            // message: '请输入金额',
            message: this.$t('exchange.l99'),
            type: 'danger'
          })
          return
        }
        if (this.sumVolume1 < this.symbolInfo.contract_size) {
          this.$notify({
            // message: '非整手数, 请输入500的倍数',
            message: this.$t('exchange.l100').replace('{p}', this.symbolInfo.contract_size),
            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 (this.tip3Show) {
            return
          }
          if (price > this.productDataObj[this.symbol].ask) {
            cmd1 = 4
          } else {
            cmd1 = 2
          }
        } else {
          if (this.tip3Show) {
            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
      var volume = Number(this.$bigDecimal.divide(this.inputType == 1 ? this.volume : this.sumVolume1 , this.symbolInfo.contract_size))
      openPosition({
        account: this.accountInfo.account,
        symbol: this.symbol,
        cmd: this.openCmd,
        volume: volume,
        server: this.accountInfo.server
      }).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
      var volume = Number(this.$bigDecimal.divide(this.inputType == 1 ? this.volume : this.sumVolume1 , this.symbolInfo.contract_size))
      openEntrust({
        account: this.accountInfo.account,
        symbol: this.symbol,
        cmd: this.openCmd,
        price: this.price,
        expiration: this.term,
        volume: volume,
        server: this.accountInfo.server
      }).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)) + ''
      }
    },
    addVolume(type) {
      if (type == 1) {
        if (!Number(this.volume) || Number(this.volume) <= this.symbolInfo.contract_size) {
          this.volume = this.symbolInfo.contract_size
          return
        }
        this.volume = Number(this.$bigDecimal.subtract(Number(this.volume) || 0, this.symbolInfo.contract_size)) + ''
      }
      if (type == 2) {
        this.volume = Number(this.$bigDecimal.add(Number(this.volume) || 0, this.symbolInfo.contract_size)) + ''
      }
    },
    addAmount(type) {
      var price = this.$bigDecimal.multiply(this.symbolInfo.contract_size, this.type == 1 ? (Number(this.price)) : (this.orderType == 'buy' ? this.productDataObj[this.symbol].ask : this.productDataObj[this.symbol].bid))
      if (type == 1) {
        if (!Number(this.amount) || Number(this.amount) <= Number(price)) {
          this.amount = price
          return
        }
        this.amount = Number(this.$bigDecimal.subtract(Number(this.amount) || 0, price)) + ''
      }
      if (type == 2) {
        this.amount = Number(this.$bigDecimal.add(Number(this.amount) || 0, price)) + ''
      }
    },
    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.$bigDecimal.add(this.symbolInfo.ask, this.$bigDecimal.add(this.point, this.symbolInfo.point)), this.symbolInfo.digits) + ''
      } else {
        this.price = this.$handleDigits(this.$bigDecimal.subtract(this.symbolInfo.bid, this.$bigDecimal.add(this.point, this.symbolInfo.point)), this.symbolInfo.digits) + ''
      }
    },
    selectTypeBack(type) {
      this.type = type
      this.price = this.$handleDigits(this.$bigDecimal.add(this.symbolInfo.ask, this.$bigDecimal.add(this.point, this.symbolInfo.point)), this.symbolInfo.digits) + ''
      this.typeShow = false
    },
    selectTermBack(term) {
      this.term = term
      this.termShow = false
    },
    selectInputType(val) {
      this.showPopover = false
      if (this.inputType == val) {
        return
      }
      if (val == 2) {
        this.amount = this.sumMoney
      }
      if (val == 1) {
        this.volume = this.sumVolume1
      }
      this.inputType = val
    },
    descriptionPopShow(title, text) {
      this.title = title
      this.text = text
      this.textDescriptionPop = true
    }
  }
}
</script>
<style lang="less" scoped>
.box5 {
  padding-top: 17px;
  padding-bottom: 7px;
  column-gap: 7px;
  .label {
    width: 127px;
    color: #888888;
  }
  .right {
    flex: 1;
    justify-content: space-between;
    min-width: 10%;
    max-width: 100%;
  }
  .btn {
    flex: 1;
    text-align: center;
    background-color: #F6F6F6;
    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: var(--red-);
    border-left-color: var(--red-);
    border-right-color: #F6F6F6;
    border-bottom-color: #F6F6F6;
    &.sell1 {
      border-top-color: #F6F6F6;
      border-left-color: #F6F6F6;
      border-right-color: var(--green-);
      border-bottom-color: var(--green-);
    }
    .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: var(--red-);
    }
  }
  .sell{
    border-radius: 0 31px 31px 0;
    &.active {
      background-color: var(--green-);
    }
  }
}
.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%;
  }
  .type {
    font-size: 16px;
  }
  .el-icon-arrow-right {
    font-size: 18px;
    color: #B6B6B6;
    margin-right: -2px;
  }
  .icon-box {
    column-gap: 19px;
  }
  .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;
  font-size: 12px;
  .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: 15px 0 16px;
  .btn-box {
    justify-content: center;
  }
  .btn {
    cursor: pointer;
    color: #fff;
    height: 38px;
    text-align: center;
    border-radius: 19px;
    display: flex;
    align-items: center;
    justify-content: center;
    column-gap: 6px;
    flex: 1;
    max-width: 236px;
  }
  .buy {
    background-color: var(--red-);
  }
  .sell {
    background-color: var(--green-);
  }
  .dis {
    cursor: not-allowed;
    color: #A5A5A5;
    background-color: #f4f4f4;
  }
  .icon {
    width: 16px;
  }
}
.input-box {
  position: relative;
  line-height: 24px;
  .text {
    font-size: 10px;
    line-height: 1;
  }
  .border {
    position: absolute;
    left: 0;
    bottom: 1px;
    transform: translateY(100%);
    border-right: 4px solid transparent;
    border-bottom: 3px solid transparent;
    border-bottom-left-radius: 2px;
  }
  .tip1 {
    position: absolute;
    left: 5px;
    top: 0;
    transform: translateY(-100%);
    z-index: 4;
    .text {
      background-color: #FFE5CD;
      padding: 3px 5px;
      color: #FF6301;
      border-radius: 4px 4px 4px 0;
    }
    .border {
      border-left: 4px solid #FFE5CD;
      border-top: 3px solid #FFE5CD;
    }
  }
  .tip2 {
    position: absolute;
    left: 5px;
    top: 0;
    transform: translateY(-100%);
    z-index: 4;
    .text {
      background-color: #D8D8D8;
      padding: 7px 5px;
      border-radius: 4px 4px 4px 0;
    }
    .border {
      border-left: 4px solid #D8D8D8;
      border-top: 3px solid #D8D8D8;
    }
  }
}
.popover-ul {
  width: 68px;
  padding: 0 10px;
  .li {
    cursor: pointer;
    font-size: 14px;
    color: #B6B6B6;
    line-height: 33px;
    text-align: center;
    &+.li {
      border-top: 1px solid #F6F6F6;
    }
    &.active {
      color: #000000;
    }
  }
}
</style>