<template>
  <div class="swap-left">
    <div style="margin-bottom: 10px;">
      <el-button type="primary" @click="valuation" size="medium" :loading="btnLoading">{{$t('field.valuation')}}</el-button>
    </div>
    <div class="top-form" v-loading="loading">
      <el-form :model="comForm" label-position="right" label-width="90px">
        <el-row>
          <el-col span="12" class="pd-r-5">
            <el-form-item :label="$t('field.pricingDate')" props="priceDate">
              <el-date-picker v-model="comForm.priceDate" type="date" placeholder="Select date" @change="pricingDateChange" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col span="12" class="pd-l-5">
            <el-form-item :label="$t('field.tradeKinds')" props="instrument">
              <el-select v-model="comForm.instrument" placeholder="" style="width:100%" @change="tradeKindsChange">
                <el-option v-for="item in tradeOptions" :key="item.value" :label="item.label" :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col span="12" class="pd-r-5">
            <el-form-item :label="$t('field.underlyingAsset')" props="underlying">
              <el-select v-model="comForm.underlying"  filterable placeholder="" style="width:100%" @change="underlyingChange">
                <el-option v-for="item in underlyingOptions" :key="item.value" :label="item.text" :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="12" class="pd-l-5">
            <el-form-item :label="$t('field.valueDate')" props="valueDate">
              <el-date-picker v-model="comForm.valueDate" type="date" placeholder="Select date" @change="valueDateChange" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col span="12" class="pd-r-5">
            <el-form-item :label="$t('field.maturityDate')" props="maturityDate">
              <el-date-picker v-model="comForm.maturityDate" type="date" placeholder="Select date" @change="maturityDateChange" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col span="12" class="pd-l-5">
            <el-form-item :label="$t('field.nominalChangeType')" props="nominalChangeType">
              <el-select v-model="comForm.nominalChangeType" filterable placeholder="" style="width:100%" @change="notionalExchange" :disabled="comForm.instrument === 'IRS'">
                <el-option v-for="item in notionalExchangeOptions" :key="item.value" :label="item.text" :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-collapse v-model="terms">
        <el-row>
          <el-col span="12" class="pd-r-5">
            <el-collapse-item :title="'leg1'" name="interestTerms-leg1" >
              <interestTerm v-if="!loading" :legItems="legItems" :buySell="'P'" :floatType="'FLOAT'" :legCurrency="leg1Currency" :sysTimes="sysTimes"  componentkey="leg1" ref="leg1" @payDirectionChange="payDirectionChange" @backData="handleBack"></interestTerm>
            </el-collapse-item>
          </el-col>
          <el-col span="12" class="pd-l-5">
            <el-collapse-item :title="'leg2'" name="interestTerms-leg2" >
              <interestTerm v-if="!loading" :legItems="legItems" :buySell="'R'" :floatType="'FIXED'" :legCurrency="leg2Currency" :sysTimes="sysTimes" componentkey="leg2" ref="leg2" @payDirectionChange="payDirectionChange" @backData="handleBack"></interestTerm>
            </el-collapse-item>
          </el-col>
        </el-row>
        </el-collapse>
    </div>
    <trialDiallogStandard ref="trialDialogStandard" :rawData="valuationData" :isQueryAction="false" :sysDate="sysDate" :disabled="true"></trialDiallogStandard>
  </div>
</template>
<script>
import request from '@/http/request.js'
import {debounce} from '@/utils/index.js'
export default {
  name: 'swapLeft',
  components: {
    interestTerm: () => import('./interestTerm.vue'),
    trialDiallogStandard: () => import('@/components/trialDialogStandard/index.vue')
  },
  data() {
    return {
      comForm: {
        instrument: 'IRS',
        underlying: '',
        priceDate: '',
        valueDate: '',
        maturityDate: '',
        nominalChangeType: ''
      },
      terms: [ 'interestTerms-leg1', 'interestTerms-leg2'],
      tradeOptions: [
        { label: '利率掉期', value: 'IRS' },
        { label: '货币掉期', value: 'CCS' },
      ],
      underlyingData: {
        'IRS': [],
        'CCS': []
      },
      underlyingOptions: [],
      notionalExchangeOptions: [],
      loading: false,
      sysTimes: 0,
      sysDate: 0,
      legItems: { 
        'IndexFVRcs': [],           // 固息，浮息
        'FloatingIndexValue': [],         // 浮动利率指标
        'CompoundType': [],         // 计息频率
        'FrequencyTypeRcs': [],     // 付息频率
        'RollConventionRcs': [],    // 支付惯例
        'InterestCalcMethodRcs': [], // 单利、复利
        'BasisRcs': [],             // 计息基础
        'HolidaysOptions': [],      // 节假日选项
        'defaultHolidays': [],     // 默认节假日
        'rateMsgBoxData': {},
        'currencyOptions': [],
        'instrument': 'IRS',         // 交易种类
      },
      leg1: {},
      leg2: {},
      leg1Currency: '',             // leg1币种
      leg2Currency: '',             // leg2币种
      valuationData: {},            // 估值数据
      marketData: {},           // 市场数据
      activedTab: 'cash',
      btnLoading: false
    };
  },
  watch: {
    comForm: {
      deep: true,
      handler: debounce(function(newVal) {
        let data = newVal
        data.leg1 = this.leg1
        data.leg2 = this.leg2
        this.$bus.$emit('sendLeftData', this.setParams(this.comForm))
      }, 100)
    },
    leg1: {
      deep: true,
      handler: debounce(function(newVal) {
        this.comForm.leg1 = newVal
        this.$bus.$emit('sendLeftData', this.setParams(this.comForm))
      }, 100)
    },
    leg2: {
      deep: true,
      handler: debounce(function(newVal) {
        this.comForm.leg2 = newVal
        this.$bus.$emit('sendLeftData', this.setParams(this.comForm))
      }, 100)
    },
  },
  mounted() {
    this.init()
    this.$nextTick(() => {
      this.$bus.$on('sendActivedTab', (data) => {
        this.activedTab = data
      })
      this.$bus.$on('sendMarketData', (data) => {
        this.marketData = data
      })
    })
  },
  methods: {
    init() {
      this.loading = true
      Promise.all([this.querySysDate(), this.queryComboxData(), this.queryHolidays()]).then(res => {
        this.loading = false
        // 节假日数据
        if (res[2].success) {
          const data3 = res[2].data.result
          this.legItems['HolidaysOptions'] = data3
        }

        if (res[1].success) {
          const data1 = res[1].data.result
          // console.log(res[1]);
          // 标的资产数据处理
          this.underlyingData['CCS'] = data1.PAIRS
          this.underlyingData['IRS'] = data1.currencies
          this.legItems['currencyOptions'] = data1.currencies
          this.underlyingOptions = this.underlyingData[this.comForm.instrument]
          this.comForm.underlying = 'USD'
          this.setLegCurrency()
          this.setHolidays() // 设置节假日

          // 本金交换方式处理
          this.notionalExchangeOptions = data1.NominalExchangeRcs
          // this.notionalExchangeOptions[0].value
          this.comForm.nominalChangeType = ''

          // leg下拉框数据
          for(const key in this.legItems) {
            if (data1.hasOwnProperty(key)) this.legItems[key] = data1[key]
          }
          // 利率弹窗数据
          let msgBox = {}
          msgBox.cashDirection = data1.CashDirection              // 现金流向
          msgBox.rollConvention = data1.RollConventionRcs         // 计息惯例
          msgBox.segmentsDirection = data1.SegmentsDirectionRcs   // 计息残段
          msgBox.paymentAt = data1.PaymentAtRcs                   // 支付、定盘时点
          msgBox.calcTypeOptions = data1.SofrFixingCalcMethod     // 计算方式
          msgBox.shiftTypeOptions = data1.ShiftType               // 偏移方式
          msgBox.amortTypeOptions = data1.AmortType               // 摊还形式
          msgBox.amortFormRcs = data1.AmortFormRcs                // 摊还(递增递减)
          msgBox.compoundTypeOptions = data1.CompoundType         // 摊还频率
          this.legItems['rateMsgBoxData'] = msgBox
        }

        // 时间数据
        if (res[0].success) {
          this.sysTimes = Number(res[0].data.result.currentTime)    // 毫秒数
          this.sysDate = res[0].data.result.date
          this.comForm.priceDate = res[0].data.result.datetime.substring(0, 10)
          this.calcExpireDate() // 计算到期日
          this.getValueDate() // 获取起息日
        }
        
      }).catch(e => {
        this.loading = false
      })
    },
    calcExpireDate() {
      // 计算到期日，当前时间加3个月
      const expireDate = new Date(this.sysTimes + 3 * 30 * 24 * 60 * 60 * 1000) 
      this.comForm.maturityDate = expireDate.toISOString().split('T')[0] // 格式化为yyyy-MM-dd
    },
    // 查询系统日期
    querySysDate() {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await request({
            url: 'pms/getSystemDate.action',
            method: 'post'
          })
          if (res.success) {
            resolve(res)
          } else {
            reject(res)
          }
        } catch (error) {
         reject(error) 
        }
      })
    },
    // 获取起息日
    async getValueDate() {
      const param = {
        tradeDate: this.comForm.priceDate.replace(/-/g, ''),
        code:  this.comForm.underlying,
        type: this.comForm.instrument === 'IRS' ? 'CCY' : 'PAIR'
      }
      const res = await request({
        url: 'pms/getValueDate.action',
        method: 'post',
        data: param
      })
      if (res.success) {
        const date =  res.data.result.toString()
        this.comForm.valueDate = date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 8)
      }
    },
    queryComboxData() {
      return new Promise(async (resolve, reject) => {
        try {
          const param = {
            codifierGrpCodes: 'BasisRcs,FloatingIndexValue,CashDirection,PAIRS,currencies,NominalExchangeRcs,IndexFVRcs,CompoundType,FrequencyTypeRcs,InterestCalcMethodRcs,BasisRcs,RollConventionRcs,SegmentsDirectionRcs,PaymentAtRcs,SofrFixingCalcMethod,ShiftType,AmortType,AmortFormRcs'
          }
          const res = await request({
            // url: 'dcs/dcs/queryComboxData.action',
            url: 'pms/baseRcs/queryComboxData.action',
            method: 'post',
            data: param
          })
          if (res.success) {
            resolve(res)
          } else {
            reject(res)
          }
        } catch (error) {
          reject(error)
        }
      })
    },
    //查询节假日
    queryHolidays() {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await request({
            url: 'pms/getHolidays.action',
            // url: 'dcs/dcs/getHolidays.action',
            method: 'post'
          })
          if (res.success) {
            resolve(res)
          } else {
            reject(res.message)
          }
        } catch (error) {
          reject(error)
        }
      })
    },
    // 设置节假日
    setHolidays() {
      // let url = this.comForm.instrument === 'IRS' ? 'dcs/dcs/getHolidayByCurrency.action' : 'dcs/dcs/getHolidayIDByPairs.action'
      let url = this.comForm.instrument === 'IRS' ? 'pms/getHolidayByCurrency.action' : 'pms/getHolidayIDByPairs.action'
      const param = {
        code:  this.comForm.underlying
      }
      request({
        url: url,
        method: 'post',
        data: param
      }).then(res => {
        if (res.success) {
          this.legItems['defaultHolidays'] = res.data.result.split(',')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    pricingDateChange(value) {
      // Handle pricing date change
    },
    tradeKindsChange(value) {
      this.underlyingOptions = this.underlyingData[value]
      this.comForm.underlying = value === 'IRS' ? 'USD' : 'USDCNY'
      this.legItems.instrument = value
      this.comForm.nominalChangeType = value === 'IRS' ? '' : this.notionalExchangeOptions[0].value
      this.setLegCurrency()
      this.setHolidays()
    },
    underlyingChange(value) {
      this.setLegCurrency()
      this.setHolidays()
    },
    valueDateChange(value) {
      // Handle value date change
    },
    maturityDateChange(value) {
      // Handle maturity date change
    },
    notionalExchange(val) {

    },
    setLegCurrency() {
      if (this.comForm.instrument === 'IRS') {
        this.leg1Currency = this.comForm.underlying
        this.leg2Currency = this.comForm.underlying
      } else {
        this.leg1Currency = this.comForm.underlying.substring(0, 3)
        this.leg2Currency = this.comForm.underlying.substring(3, 6)
      }
    },
    inputBlur(event, field, decimalPlaces) {
      const value = parseFloat(event.target.value).toFixed(decimalPlaces);
      this.comForm[field] = value;
    },
    valuation() {
      this.$bus.$on('sendActivedTab', (data) => {
        this.activedTab = data
      })
      let params = {
        'queryParam.deal': this.setParams(this.comForm),
        'queryParam.priceDate': this.comForm.priceDate.replace(/-/g, ''),
        'queryParam.market': this.marketData
      }
      // console.log(this.activedTab, 'activedTab');
      this.btnLoading = true
      request({
        url: 'mds/simulationValuationAnalysis.action',
        method: 'post',
        data: params
      }).then(res => {
        this.btnLoading = false
        if (res.success) {
          this.valuationData = res.data
          this.$nextTick(() => {
            this.$refs['trialDialogStandard'].init({}, '估值', {})
          })
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.btnLoading = false
        this.$message.error(e.message)
      })
    },
    handleBack(key, item) {
      this[key] = item
    },
    payDirectionChange(key, val) {
      const value = val === 'P' ? 'R' : 'P'
      if (key === 'leg1') {
        this.$refs['leg2'].changePay(value)
      } else {
        this.$refs['leg1'].changePay(value)
      }
    },
    // 表单数据处理成接口需要的格式
    setParams(paramsData) {
      const data = JSON.parse(JSON.stringify(paramsData))
      let params = {
        profitCcy: data.underlying.length > 3 ? data.underlying.substr(0, 3) : data.underlying,
        underlying: data.underlying,
        instrument: data.instrument,
        valueDate: data.valueDate?.replace(/-/g, ''),
        maturityDate: data.maturityDate?.replace(/-/g, ''),
        nominalChangeType: data.nominalChangeType,
        priceDate: data.priceDate?.replace(/-/g, ''),
      }
      const leg1 = this.createLeg(1, data['leg1'])
      const leg2 = this.createLeg(2, data['leg2'])
      params.leg1 = leg1
      params.leg2 = leg2
      return params
    },
    createLeg(legId, leg) {
      let legParam = {
        legId: legId
      }
      for(const key in leg) {
        if (leg.hasOwnProperty(key)) {
          if (key === 'checkList') {
            legParam.adjusted = leg[key].includes('Adjusted') ? 'YES' : 'NO'
            legParam.isEom = leg[key].includes('EOMA') ? 'YES' : 'NO'
          } else if (key === 'resetLongPeriod' || key === 'longPeriod' || key === 'restartInterestCalc') {
            legParam[key] = leg[key] ? 'YES' : 'NO'
          } else if (key === 'firstPaymentDate' || key === 'amortFirstDate' || key === 'amortEndDate') {
            legParam[key] = leg[key] ? leg[key].replace(/-/g, '') : ''
          } else if (key === 'floatingIndex') {
            legParam[key] = leg[key].value
          } else {
            legParam[key] = leg[key]
          }
        }
      }
      return legParam
    }
  },
  beforeDestroy () {
    this.$bus.$off();
  },
}
</script>
<style lang="scss" scoped>
.swap-left {
  padding: 16px;
  background-color: var(--bg-color-2);
  height: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: auto;
  border-right: 1px solid #e4e7ed;
  .top-form {
    margin-bottom: 20px;
    .principal-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .el-select {
        width: 30%;
      }
      .el-input {
        width: 70%;
      }
    }
  }
}
.pd-r-5 {
  padding-right: 5px;
}
.pd-l-5 {
  padding-left: 5px;
}
.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>