<template>
  <div class="fx-right">
    <div class="right-top">
      <el-button type="primary" size="medium" @click="save">保存</el-button>
      <el-button type="primary" size="medium" @click="refresh">刷新</el-button>
    </div>
    <div v-loading="loading">
      <div class="right-content" v-if="tabs.length > 0" >
        <calculatorTable @cellCick="updateData" :tabs="tabs" :tableHeight="tableHeight" class="table-sty"></calculatorTable>
      </div>
      <el-empty v-else description="暂无数据"></el-empty>
    </div>
    
  </div>
</template>
<script>
import request from '@/http/request.js'
export default {
  components: {
    calculatorTable: () => import('../components/calculatorTable')
  },
  data() {
    return {
      loading: false,
      leftFormData: {},
      tableHeight: 0,
      tabs: [   // 数据结构
      // { defaultValue: 'usdcad', dataType: 'FWD',
      //   tab: [
      //     {text: 'fwd', code: 'usdcad', dataType: 'FWD',tableData: [], columns: []},
      //   ],
      // },
      ],
      marketData: {},
      tabData: {},
      btnLoading: false
    };
  },
  mounted() {
    this.handleResize()
    // this.init();
    this.getLeftFormData().then(res => {
      this.queryTabsData(res)
    })
  },

  methods: {
    init() {
      this.$bus.$on('sendLeftData', (data) => {
        this.leftFormData = JSON.parse(JSON.stringify(data))
        this.queryTabsData(this.leftFormData)
      })
    },
    getLeftFormData() {
      return new Promise((resolve, reject) =>{
        this.$bus.$on('sendLeftData',(data) => {
          this.leftFormData = JSON.parse(JSON.stringify(data))
          resolve(this.leftFormData)
        })
      })
    },
    updateData(index, key, value, curveCode) {
      // console.log(index, key, value, curveCode);
      for(const i in this.marketData) {
        if (this.marketData.hasOwnProperty(i)) {
          if (this.marketData[i].datals[0].curveCode === curveCode) {
            this.$set(this.marketData[i].datals[index], key, value)
          }
        }
      }
    },
    // 查询表格tab
    async queryTabsData(params) {
      this.tabData = {}
      let obj = {
        instrument:params.tradeType,
        priceDate:params.priceDay.replace(/-/g, ''),
        underlying:params.currencyPair,
        profitCcy:params.currencyPair.substr(0, 3),
        valueDate:params.valueDate.replace(/-/g, ''),
        deliveryDate:params.expireDate.replace(/-/g, ''),
        ccy: params.principal,
        nominal: params.money,
        buySell: params.tradeDirection,
        isUseMid: 'MID'
      }
      const res = await request({
        url: 'mds/mds/findMarketInfoForAnalysis.action',
        method: 'post',
        data: {
          'queryParam.deal': obj
        },
      })
      if (res.success) {
        let data = res.data.result
        this.tabData = data
        this.queryTableData(data)
      } else {
        this.$message({
          message: res.message,
          type: 'error',
        })
      }
    },
    // 查询表格数据
    async queryTableData(params) {
      this.marketData = {}
      this.tabs = []
      try {
        this.loading = true
        const res = await request({
          url: 'mds/findMarketPriceForValAnalysis.action',
          method: 'post',
          data: {
            'queryParam.data': params,
            'queryParam.priceDate': this.leftFormData.priceDay.replace(/-/g, ''),
          },
        })
        if (res.success) {
          let data = res.data.result
          this.handleTabsAndTableData(params, data)
        } else {
          this.$message({
            message: res.message,
            type: 'error',
          })
        }
      } catch (error) {
        
      } finally {
        this.loading = false
      }
    },
    async save() {
      if (Object.keys(this.marketData).length === 0) return
      let params = {
        'queryParam.priceDate': this.leftFormData.priceDay.replace(/-/g, ''),
        'queryParam.market': this.marketData
      }
      this.btnLoading = true
      this.loading = true
      const res = await request({
        url: 'mds/saveMarketPriceForValAnalysis.action',
        method: 'post',
        data: params
      })
      this.btnLoading = false
      this.loading = false
      if (res.success) {
        this.$message({
          message: '保存成功',
          type: 'success',
        });
        this.handleTabsAndTableData(this.tabData, res.data.result)
      } else {
        this.$message({
          message: '保存失败',
          type: 'error',
        });
      }
      this.$bus.$emit('sendRightData', this.marketData)
    },
    async refresh() {
      this.btnLoading = true
      try {
        await this.queryTabsData(this.leftFormData)
      } catch (error) {
        console.log(error)
      } finally {
        this.btnLoading = false
      }
    },
    handleTabsAndTableData(rowTab, rowData, tabKey = 'code') {
      delete rowTab['SPOT']
      delete rowData['SPOT']
      // 接口入参塞字段
      for(const key in rowData) {
        for(const i in rowTab) {
          if (rowTab[i].dataType === 'SPOT') delete rowTab[i]
          if (rowData.hasOwnProperty(key) && rowTab.hasOwnProperty(i) && key == i) {
            rowData[key].tabKey = tabKey
            rowData[key].code = rowTab[i].code
            rowData[key].dataType = rowTab[i].dataType
          }
        }
      }
      this.marketData = JSON.parse(JSON.stringify(rowData))
      this.$bus.$emit('sendRightData', this.marketData)
      let temp = []
      this.tabs = []
      for(const key1 in rowTab) {
        for (const key2 in rowData) {
          if (rowTab.hasOwnProperty(key1) && rowData.hasOwnProperty(key2) && key1 == key2) {
            let obj = rowTab[key1]
            let col = []
            if (rowTab[key1].dataType == 'FWD') {                // 远期价格表
              col = [
                {label: '期限', key: 'tenor', align: 'center'},
                {label: '到期日', key: 'deliveryDate', align: 'center'},
                {label: '远期价格', key: 'fwdRateStr', align: 'right'},
                {label: '升贴水', key: 'swapStr', align: 'right', isEdit: true},
              ]
            } else if (rowTab[key1].dataType == 'CURVE') {      // 收益曲线表
              col = [
                {label: '期限', key: 'tenor', align: 'center'},
                {label: '到期日', key: 'endDate', align: 'center'},
                {label: '利率(%)', key: 'rateStr', align: 'right', isEdit: true},
                {label: '贴现率', key: 'dfStr', align: 'right'},
              ]
            } else if (rowTab[key1] == 'FXVOL') {                // 波动率表
              col = rowData[key2].columns
            }
            obj.columns = col
            obj.tableData = rowData[key2].datals.map(item => {
              if (item.deliveryDate) item.deliveryDate = this.formateDate(item.deliveryDate)
              if (item.endDate) item.endDate = this.formateDate(item.endDate)
              return item
            })
            temp.push(obj)
        }
      }
    }
    let arr = [... new Set(temp.map(item => item.dataType))]
    let copyTabs = []
    arr.forEach(i => {
      let obj = {
        defaultValue: '',
        dataType: i,
        tabKey: tabKey,        
        tab: [],
      }
      temp.forEach(item => {
        if (item.dataType === i) obj.tab.push(item)
      })
      obj.defaultValue = obj.tab[0][tabKey]
      copyTabs.push(obj)
    })
    this.tabs = JSON.parse(JSON.stringify(copyTabs))
    // console.log('tabs ===============', this.tabs);
    },
    formateDate(date) {
      const date1 = date.toString()
      const year = date1.substr(0, 4)
      const month = date1.substr(4, 2)   
      const day = date1.substr(6, 2)
      return `${year}-${month}-${day}`
    },
    // 获取table最大高度
    handleResize () {
      const box = Array.from(document.getElementsByClassName('fx-right')) || []
      const boxH = box.find(ele => ele.clientHeight > 0)?.clientHeight || 0
      this.tableHeight = boxH - 130
    },
  },
  beforeDestroy () {
    this.$bus.$off('sendLeftData');
  },
}
</script>
<style lang="scss" scoped>
.fx-right {
  padding: 20px;
  background-color: var(--bg-color-2);
  height: 100%;
  overflow-x: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  .right-top {
    margin-bottom: 10px;
  }
  .table-sty {
    display: flex;
    justify-content: space-between;
    align-items: center;
    // flex-wrap: wrap;
    height: 100%;
    .row-box {
      flex: 1;
      width: calc(100% - 20px) / 2;
      padding:0 5px 5px 0;
    }
  }
}
// ::v-deep.el-tabs.el-tabs--card{
//                 .el-tabs__header{
//                     border-bottom: none;
//                     margin-bottom: 5px;
//                     .el-tabs__nav{
//                         border: none;
//                     }
//                     .el-tabs__nav-wrap .el-tabs__item{
//                         padding: 0 10px;
//                         height: 26px;
//                         line-height: 26px;
//                         margin-right: 4px;
//                         border: 1px solid var(--scrollBar);
//                         &.is-active{
//                             color: var(--blue-50);
//                             border-color: var(--blue-50);
//                         }
//                     }
//                 }
                
//             }
</style>