<template>
  <div class="fx-left">
    <div class="left-top">
      <el-button type="primary" size="medium" @click="valuation" :loading="btnLoading">估值</el-button>
    </div>
    <div class="middle" v-loading="formLoading">
      <el-form :model="form" label-position="left" label-width="80px">
        <el-form-item label="货币对" prop="currencyPair">
          <el-select v-model="form.currencyPair" filterable  placeholder="请选择" style="width:100%" @change="pairChange">
            <el-option 
              v-for="(i, index) in pairData" 
              :key="index" :label="i.label" :value="i.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="定价日" prop="priceDay">
          <el-date-picker v-model="form.priceDay" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" @change="priceDayChange" style="width:100%" />
        </el-form-item>
        <el-form-item label="交易种类" prop="tradeType">
          <el-select v-model="form.tradeType" placeholder="请选择" style="width:100%" @change="tradeTypeChange">
            <el-option 
              v-for="(i, index) in tradeType" 
              :key="index" :label="i.label" :value="i.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-collapse v-model="tradeTerms" :accordion="true">
          <el-collapse-item title="交易条款" name="1" >
            <el-form-item label="买卖方向" prop="tradeDirection">
              <el-select v-model="form.tradeDirection" placeholder="请选择" style="width:100%">
                <el-option 
                  v-for="(i, index) in tradeDirectionData" 
                  :key="index" :label="i.label" :value="i.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="起息日" prop="valueDate" v-if="valueDateShow">
              <el-date-picker v-model="form.valueDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" @change="valueDateChange" style="width:100%" />
            </el-form-item>
            <el-form-item label="到期日" prop="expireDate" v-if="expireDateShow">
              <el-date-picker v-model="form.expireDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" @change="expireDateChange" style="width:100%" />
            </el-form-item>
            <el-form-item label="即期价格" prop="spotPrice" v-if="spotPriceShow" >
              <el-input type="number" v-model="form.spotPrice" @blur="inputBlur($event, 'spotPrice', '6')"  :precision="2" controls-position="right" style="width:100%" />
            </el-form-item>
            <el-form-item label="汇率" prop="exRate" v-if="exRateShow">
              <el-input type="number" v-model="form.exRate" @blur="inputBlur($event, 'exRate', '6')"  :precision="2" controls-position="right" style="width:100%" />
            </el-form-item>
            <el-form-item label="名义本金" prop="principal">
              <div class="principal-box">
                <el-select v-model="form.principal" placeholder="请选择" style="width:40%">
                  <el-option 
                    v-for="(i, index) in principalOptions" 
                    :key="index" :label="i.label" :value="i.value">
                  </el-option>
                </el-select>
                <el-input type="number" v-model="form.money" :precision="2" controls-position="right" @blur="inputBlur($event, 'money', '2')"  />
              </div>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>
    <trialDiallogStandard  ref="trialDialogStandard" :rawData="valuationData" :isQueryAction="false" :disabled="true"></trialDiallogStandard>
  </div>
</template>
<script>
import request from '@/http/request.js'
import {debounce} from '@/utils/index.js'
import trialDiallogStandard from '@/components/trialDialogStandard/index.vue'
export default {
  components: {
    trialDiallogStandard
  },
  name: 'fxLeft',
  data() {
    return {
      sysDate: '',
      currentTime: '',      // 毫秒数
      pairData: [], // 货币对数据
      priceDay: '', // 定价日
      tradeType: [
        {label: '即期', value: 'FXSPOT'}, 
        {label: '远期', value: 'FXFWD'}, 
        {label: '掉期', value: 'FXSWAP'}
      ], // 交易种类
      tradeDirectionData: [], // 买卖方向
      valueDate: '', // 起息日
      expireDate: '', // 到期日
      spotPrice: '', // 即期价格
      exRate: '', // 汇率
      tradeTerms: ['1'], // 交易条款
      principalOptions: [], // 名义本金
      valueDateShow: true, // 起息日是否显示
      expireDateShow: false, // 到期日是否显示
      spotPriceShow: true, // 即期价格是否显示
      exRateShow: false, // 汇率是否显示
      form: {
        currencyPair: '', // 货币对
        priceDay: '', // 定价日
        tradeType: 'FXSPOT', // 交易种类
        tradeDirection: '', // 买卖方向
        valueDate: '', // 起息日
        expireDate: '', // 到期日
        spotPrice: '', // 即期价格
        exRate: '', // 汇率
        principal: '', // 名义本金
        money: '1000000.00', // 本金
      },
      btnLoading: false, // 按钮加载状态
      formLoading: true, // 表单加载状态
      rightTableData: {},
      trialDialogShow: false, // 估值弹窗
      valuationData: {}, // 估值数据

    };
  },
  watch: {
    form: {
      deep: true,
      handler: debounce(function(newVal) {
        // 监听表单数据变化
        let data = JSON.parse(JSON.stringify(newVal))
        this.$bus.$emit('sendLeftData', data)
      }, 500),
    },
  },
  mounted() {
    this.initForm()
    this.$bus.$on('sendRightData', data => {
      this.rightTableData = data
    })
  },
  
  methods: {
    // 初始化表单
    initForm() {
      this.formLoading = true
      Promise.all([this.queryComboxData(), this.querySysDate()]).then(res => {
        // console.log(res);
        if (res[0].success) {
          this.pairData = res[0].data.result.allPairs.map(item => {
            if (item.value === 'USDCNY') this.form.currencyPair = item.value
            return {label: item.value, value: item.value}
          })
          if (this.form.currencyPair === '') this.form.currencyPair = this.pairData[0].value
          // 买卖方向数据处理
          this.tradeDirectionData = res[0].data.result.BuySellRcs.map(item => {
            return {label: item.text, value: item.value}
          })
          this.form.tradeDirection = this.tradeDirectionData[0].value
          this.calcPrincipal()
        }
        if (res[1].success) {
          this.sysDate = res[1].data.result.date
          this.currentTime = Number(res[1].data.result.currentTime) // 毫秒数
          this.form.priceDay = res[1].data.result.datetime.substring(0, 10)
          this.calcExpireDate() // 计算到期日
          this.getValueDate() // 获取起息日
        }
      }).catch(err => {
        console.log(err);
        
      }).finally(() => {
        this.formLoading = false
      })
    },
    // 货币对变化
    pairChange() {
      this.calcPrincipal()
      this.getValueDate()
      this.queryPrice('expireDate', this.form.expireDate.replace(/-/g, ''))
    },
    // 交易种类变化
    tradeTypeChange(val) {
      switch (val) {
        case 'FXSPOT':
          this.valueDateShow = true
          this.expireDateShow = false
          this.spotPriceShow = true
          this.exRateShow = false
          break;
        case 'FXFWD':
          this.valueDateShow = false
          this.expireDateShow = true
          this.spotPriceShow = false
          this.exRateShow = true
          break;
        case 'FXSWAP':
          this.valueDateShow = true
          this.expireDateShow = true
          this.spotPriceShow = true
          this.exRateShow = true
          break;
      }
    },
    // 查询系统日期
    querySysDate() {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await request({
            url: 'pms/getSystemDate.action',
            method: 'post'
          })
          // const res = await this.$apis.getSystemDate()
          if (res.success) {
            resolve(res)
          } else {
            reject(res)
          }
        } catch (error) {
         reject(error) 
        }
      })
    },
    calcExpireDate() {
      // 计算到期日，当前时间加3个月
      const expireDate = new Date(this.currentTime + 3 * 30 * 24 * 60 * 60 * 1000) 
      this.form.expireDate = expireDate.toISOString().split('T')[0] // 格式化为yyyy-MM-dd
      this.queryPrice('expireDate', this.form.expireDate.replace(/-/g, ''))
    },
    // 货币对和买卖方向数据
    async queryComboxData() {
      return new Promise(async (resolve, reject) => {
        try {
          const param = {
            codifierGrpCodes: 'allPairs,BuySellRcs'
          }
          const res = await request({
            url: 'pms/baseRcs/queryComboxData.action',
            method: 'post',
            data: param
          })
          if (res.success) {
            resolve(res)
          } else {
            reject(res)
          }
        } catch (error) {
          reject(error)
        }
      })
    },
    calcPrincipal() {
      // 计算名义本金
      let arr = (this.form.currencyPair.substring(0, 3) + '-' + this.form.currencyPair.substring(3, 6)).split('-')
      this.principalOptions = arr.map(item => {
        return {label: item, value: item}
      })
      this.form.principal = arr[0]
    },
    // 获取起息日
    async getValueDate() {
      const param = {
        tradeDate: this.form.priceDay.replace(/-/g, '').toString(),
        code: this.form.currencyPair,
        type: 'PAIR'
      }
      const res = await request({
        url: 'pms/getValueDate.action',
        method: 'post',
        data: param
      })
      // console.log('getValueDate==========>', res);
      if (res.success) {
        const date =  res.data.result.toString()
        this.form.valueDate = date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 8)
        this.queryPrice('valueDate', date)
      }
    },
    // 查询即期价格、汇率
    async queryPrice(type,date) {
      let param = {
        maturityDate: date,
        code: this.form.currencyPair
      }
      const res = await request({
        url: 'pms/getForwardRate.action',
        method: 'post',
        data: param
      })
      if (res.success) {
        type === 'valueDate' ? this.form.spotPrice = res.data.result.fwdMid.toFixed(6) : this.form.exRate = res.data.result.fwdMid.toFixed(6)
      } else {
        type === 'valueDate' ? this.form.spotPrice = '' : this.form.exRate = ''
      }
    },
    // 定假日变化
    priceDayChange(val) {
      this.getValueDate()
    },
    // 起息日变化
    valueDateChange(val) {
      this.queryPrice('valueDate', val.replace(/-/g, ''))
    },
    // 到期日变化
    expireDateChange(val) {
      this.queryPrice('expireDate', val.replace(/-/g, ''))
    },
    // 估值逻辑
    async valuation() {
      this.btnLoading = true
      let deal = {
        instrument: this.form.tradeType,
        priceDate: this.form.priceDay.replace(/-/g, ''),
        deliveryDate: this.form.expireDate.replace(/-/g, ''),
        underlying: this.form.currencyPair,
        profitCcy: this.form.currencyPair.substring(0, 3),
        ccy: this.form.principal,
        nominal: this.form.money,
        buySell: this.form.tradeDirection,
        isUseMid: 'MID',
        spotRate: this.form.spotPrice,
        fwdRate: this.form.exRate,
        valueDate: this.form.valueDate.replace(/-/g, ''),
      }
      const params = { 
        'queryParam.deal': deal,
        'queryParam.priceDate': this.form.priceDay.replace(/-/g, ''),
        'queryParam.market': this.rightTableData,
      }
      try {
        const res = await request({
          url: 'mds/simulationValuationAnalysis.action',
          method: 'post',
          data: params
        })
        if (res.success) {  
          this.trialDialogShow = true
          this.valuationData = res.data
          this.$nextTick(() => {
            this.$refs.trialDialogStandard.init({}, '估值', {})
          })
        } else {
          this.$message({message: res.message, type: 'error'})
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.btnLoading = false
      }
      
    },
    inputBlur (e, item, num) {
      this.form[item] = parseFloat(e.target.value).toFixed(num)
    },
  },
  beforeDestroy () {
    this.$bus.$off('sendRightData');
  },
}
</script>
<style lang="scss" scoped>
.fx-left {
  padding: 20px;
  background-color: var(--bg-color-2);
  height: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: auto;
  .left-top {
  margin-bottom: 10px;
}

.principal-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

}
.el-form-item {
  margin-bottom: 5px;
  width: 100%;
}
::v-deep .el-date-editor .el-input__inner {
  padding-left: 28px;
}
::v-deep .el-collapse{
    border: none;
  }
::v-deep .el-collapse-item__wrap {
  border: none;
}
::v-deep .el-collapse-item__header{
  border: none;
  font-size: 14px;
  font-weight: bold;
  padding-left: 0;
}
 
</style>