<template>
  <div class="swap-right">
    <div style="margin-bottom: 10px">
      <el-button v-if="currentTab !== 'cash'" type="primary" size="medium" @click="save" :loading="btnLoading">保存</el-button>
      <el-button type="primary" size="medium" @click="refresh" :loading="btnLoading">刷新</el-button>
    </div>
    <el-tabs v-model="currentTab" type="card" @tab-click="tabClick">
      <el-tab-pane label="现金流表" name="cash">
        <calculatorTable v-loading="" v-if="cashTab.length > 0" :tabs="cashTab" :tableHeight="tableHeight" class="cash-table" />
        <el-empty v-else description="暂无数据"></el-empty>
        
      </el-tab-pane>
      <el-tab-pane label="市场数据" name="marketData" lazy>
        <marketTable :leftParams="leftParams" ref="marketTable" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import request from '@/http/request.js'
import {formatMoney} from '@/utils'
export default {
  components: {
    marketTable: () => import('./marketTable.vue'),
    calculatorTable: () => import('../components/calculatorTable')
  },
  data() {
    return {
      columns: [
        {label: '现金流类型', key: 'cashflowType', align: 'center'},
        {label: '支付日期', key: 'paymentDate', align: 'center'},
        {label: '计息开始', key: 'periodStartDateAdj',align: 'center'},
        {label: '计息结束', key: 'periodEndDateAdj',align: 'center'},
        {label: '名义本金', key: 'nominal',align: 'right'},
        {label: '金额', key: 'amount',align: 'right'},
      ],
      currentTab: 'cash',
      leftFormData: {},
      leftParams: {},
      btnLoading: false,
      tableHeight: 0,
      loading: false,
      cashTab: []
    }
  },
  mounted() {
    this.init().then(res => {
      // console.log(this.leftFormData, 'res');
      // this.refresh()
    })
  },
  methods: {
    init() {
      return new Promise((resolve, reject) => {
        this.$bus.$on('sendLeftData', data => {
          this.leftFormData = JSON.parse(JSON.stringify(data))
          this.leftParams = JSON.parse(JSON.stringify(data))
          resolve(data)
        })
      })
    },
    refresh() {
      this.leftParams = JSON.parse(JSON.stringify(this.leftFormData))
      // console.log(this.leftParams, 'this.leftParams');
      if (this.currentTab === 'cash') {
        this.refreshCash()
      } else if (this.currentTab === 'marketData') {
        this.$refs.marketTable?.queryTabsData()
      }
    },
    save() {
      if (this.currentTab === 'marketData') {
        this.$refs.marketTable?.saveData()
      }
    },
    refreshCash() {
      for(const i in this.leftParams) {
        if (this.leftParams.hasOwnProperty(i)) {
          if (i === 'leg1' || i === 'leg2') {
            if (this.leftParams[i]['indexation'] === 'FIXED') {
              if (!this.leftParams[i]['fixedRate']) return this.$message.error(`${i}利率不能为空!`)
            } else {
              if (!this.leftParams[i]['floatingIndex']) return this.$message.error(`${i}浮动利率指标不能为空!`)
              if (!this.leftParams[i]['floatingRatio']) return this.$message.error(`${i}浮动利率比率不能为空!`)
              if (!this.leftParams[i]['floatingSpread']) return this.$message.error(`${i}浮动利率点差不能为空!`)
            }
            if (!this.leftParams[i]['notional']) return this.$message.error(`${i}本金不能为空!`)
            if (!this.leftParams[i]['compoundFrequency']) return this.$message.error(`${i}计息频率不能为空!`)
            if (!this.leftParams[i]['couponFrequency']) return this.$message.error(`${i}付息频率不能为空!`)
            if (this.leftParams[i]['amortType'] !== 'NONE') {
              if (!this.leftParams[i]['amortValue']) return this.$message.error(`${i}摊还金额或比例不能为空!`)
              if (!this.leftParams[i]['amortFrequency']) return this.$message.error(`${i}摊还频率不能为空!`)
            }
          }
        }
      }
      let params = {
        'queryParam.deal': this.leftParams,
      }
      this.btnLoading = true
      this.loading = true
      this.cashTab = []
      request({
        url: 'pms/calCashflows.action',
        method: 'post',
        data: params
      }).then(res => {
        this.btnLoading = false
        this.loading = false
        if (res.success) {
          let data = res.data
          for(const key in data) {
            if (data.hasOwnProperty(key)) {
              if (key === 'cashFlow1' || key === 'cashFlow2') {
                data[key].forEach(item => {
                  item.paymentDate = this.formateDate(item.paymentDate)
                  item.periodStartDateAdj = item.periodStartDateAdj.toString().length < 8 ? item.paymentDate : this.formateDate(item.periodStartDateAdj)
                  item.periodEndDateAdj = item.periodEndDateAdj.toString().length < 8 ? item.paymentDate : this.formateDate(item.periodEndDateAdj)
                  item.nominal = formatMoney(item.nominal, 2)
                  item.amount = formatMoney(item.amount, 2)
                })
                let obj = {
                  defaultValue: key,
                  dataType: key,
                  tabKey: 'code',
                  tab: [{
                    text: key,
                    code: key,
                    dataType: key,
                    tableData: data[key],
                    columns: this.columns
                  }],
                }
                this.cashTab.push(obj)
              }
            }
          }
          this.$nextTick(() => {
            this.handleResize(this.cashTab.length)
          })
          // console.log(this.cashTab, 'cashTab');
        } else {
          this.$message({
            message: res.message,
            type: 'error',
          })
        }
      }).catch(err => {
        this.btnLoading = false
        this.loading = false
        console.log(err);
      })
    },
    tabClick(val) {
      this.$bus.$emit('sendActivedTab', val.name)
    },
    handleResize (num) {
      const h1 = document.documentElement.clientHeight
      // console.log(document.body.clientHeight);
      const height = h1 - 220
      this.tableHeight = (height / num) - 70
    },
    formateDate(date) {
      const date1 = date.toString()
      if (date1.length < 8) return date1
      const year = date1.substr(0, 4)
      const month = date1.substr(4, 2)   
      const day = date1.substr(6, 2)
      return `${year}-${month}-${day}`
    },
  },
  beforeDestroy() {
    this.$bus.$off();
  },
}
</script>
<style lang="scss" scoped>
.swap-right {
  height: 100%;
  padding: 16px;
  background-color: var(--bg-color-2);
}
.el-form-item {
  margin-bottom: 1px;
  width: 100%;
  ::v-deep .el-form-item__content {
    text-align: right;
  }
}
.table-sty {
  margin: 10px 0 10px 0;
}
.cash-table {
  margin-top: 10px;
}
::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>