<template>
<div v-loading="loading">
  <calculatorTable v-if="tabs && tabs.length > 0" @cellCick="updateData" :tabs="tabs" :tableHeight="tableHeight" class="table-sty"></calculatorTable>
  <el-empty v-else description="暂无数据"></el-empty>
</div>
  
</template>
<script>
import request from '@/http/request.js'
export default {
  components: {
    calculatorTable: () => import('../components/calculatorTable')
  },
  props: {
    leftParams: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      tabs: [],
      tableHeight: 0,
      tabData: {},
      marketData: {}
    }
  },
  mounted() {
    // this.handleResize()
    // this.queryTabsData()
  },
  methods: {
    handleResize (num) {
      const h1 = document.documentElement.clientHeight
      // console.log(document.body.clientHeight);
      const height = h1 - 220
      this.tableHeight = (height / num) - 70
    },
    updateData(index, key, value, curveCode) {
      // console.log(index, key, value);
      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)
          }
        }
      }
    },
    // 查询表格数据
    async queryTabsData() {
      // console.log(this.leftParams, '111');
      this.tabData = {}
      const res = await request({
        url: 'mds/mds/findMarketInfoForAnalysis.action',
        method: 'post',
        data: {
          'queryParam.deal': this.leftParams
        },
      })
      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.loading = true
      this.marketData = {}
      this.tabs = []
      try {
        const res = await request({
          url: 'mds/findMarketPriceForValAnalysis.action',
          method: 'post',
          data: {
            'queryParam.data': params,
            'queryParam.priceDate': this.leftParams.priceDate,
          },
        })
        if (res.success) {
          let data = res.data.result
          this.handleData(params, data)
        } else {
          this.$message({
            message: res.message,
            type: 'error',
          })
        }
      } catch (error) {
        
      } finally {
        this.loading = false
      }
    },
    handleData(rawTab, rawData, tabKey = 'txt') {
      // 接口入参塞字段
      for(const key in rawData) {
        for(const i in rawTab) {
          if (rawTab[i].dataType === 'SPOT') delete rawTab[i]
          if (rawData.hasOwnProperty(key) && rawTab.hasOwnProperty(i) && key == i) {
            rawData[key].tabKey = tabKey
            rawData[key].code = rawTab[i].code
            rawData[key].dataType = rawTab[i].dataType
          }
        }
      }
      this.marketData = JSON.parse(JSON.stringify(rawData))
      this.$bus.$emit('sendMarketData', this.marketData)
      let temp = []
      for(const key1 in rawTab) {
        for (const key2 in rawData) {
          if (rawTab.hasOwnProperty(key1) && rawData.hasOwnProperty(key2) && key1 == key2) {
            let obj = rawTab[key1]
            let col = []
            if (rawTab[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 (rawTab[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 (rawTab[key1] == 'FXVOL') {                // 波动率表
              col = rawData[key2].columns
            }
            obj.columns = col
            obj.tableData = rawData[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)
        })
        // const map = new Map()
        // obj.tab = obj.tab.filter(item => !map.has(item.code) && map.set(item.code, 1))    // 去重
        obj.defaultValue = obj.tab[0][tabKey]
        copyTabs.push(obj)
      })
      this.tabs = JSON.parse(JSON.stringify(copyTabs))
      this.$nextTick(() => {
        this.handleResize(this.tabs.length)
      })
      console.log('tabs ===============', this.tabs);
    },
    async saveData() {
      if (Object.keys(this.marketData).length === 0) return
      this.loading = true
      let params = {
        'queryParam.priceDate': this.leftParams.priceDate,
        'queryParam.market': this.marketData
      }
      const res = await request({
        url: 'mds/saveMarketPriceForValAnalysis.action',
        method: 'post',
        data: params
      })
      if (res.success) {
        this.$message({
          message: '保存成功',
          type: 'success',
        });
        this.handleData(this.tabData, res.data.result)
      } else {
        this.$message({
          message: '保存失败',
          type: 'error',
        });
      }
      this.loading = false
      this.$bus.$emit('sendMarketData', this.marketData)
    },
    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}`
    },
  }
}
</script>
<style lang="scss" scoped>
.table-sty {
  margin-top: 10px;
}
</style>