<template>
    <div class="optionCalculator-table" :class="iconShow?'p-l-36':''">
        <div class="btns">
            <el-button type="primary" @click="saveBtn">{{$t('field.save')}}</el-button>
            <el-button type="primary" @click="findMarketInfoForAnalysis">{{$t('field.refresh')}}</el-button>
        </div>
        <el-row v-loading="loading">
            <el-col :span="12">
                <div class="table-box">
                    <!-- <div class="clearfix">
                      <el-radio-group v-model="card1">
                        <el-radio-button v-for="item in tab1" :label="item.code">{{item.code}}</el-radio-button>
                      </el-radio-group>
                      <span>远期曲线</span>
                      <span></span>
                    </div> -->
                    <!-- <span class="title">远期曲线</span> -->
                    <el-tabs v-model="card1" type="card">
                        <el-tab-pane v-for="(item, idx) in tab1" :label="item.code" :name="item.code" :key="item.code">
                            <keep-alive>
                                <el-table
                                    :data="item.tableData"
                                    stripe
                                    border
                                    :height="maxHeight"
                                    :max-height="maxHeight"
                                    @row-dblclick="dblclick"
                                    @row-click="rowClick"
                                    :row-class-name="rowFixed"
                                    style="width: 100%">
                                    <el-table-column
                                        prop="tenor"
                                        min-width="40%"
                                        headerAlign="center"
                                        :label="$t('menu.tenor')"
                                        align="center">
                                    </el-table-column>
                                    <el-table-column
                                        prop="deliveryDate"
                                        min-width="40%"
                                        headerAlign="center"
                                        :label="$t('field.maturityDate')"
                                        align="center">
                                        <template slot-scope="scope">
                                            <span>{{ scope.row.deliveryDate.toString().substr(0,4) }}-{{ scope.row.deliveryDate.toString().substr(4,2) }}-{{ scope.row.deliveryDate.toString().substr(6,2) }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        headerAlign="center"
                                        :label="$t('field.raiseThePremium')"
                                        align="right">
                                        <template slot-scope="scope">
                                            <template v-if="scope.row.tenor === 'Spot'">
                                                <span>{{ scope.row.swapStr }}</span>
                                            </template>
                                            <template v-else>
                                                <el-input v-if="row === scope.row.id" type="number" v-model="scope.row.swapStrInput" @blur="inputBlur('tab1', idx, scope)"></el-input>
                                                <span v-else>{{ scope.row.swapStr }}</span>
                                            </template>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        headerAlign="center"
                                        :label="$t('field.forwardPrice')"
                                        align="right">
                                        <template slot-scope="scope">
                                            <template v-if="scope.row.tenor === 'Spot'">
                                                <el-input v-if="row === scope.row.id" type="number" v-model="scope.row.fwdRateStrInput" @blur="inputBlur('tab1', idx, scope)"></el-input>
                                                <span v-else>{{ scope.row.fwdRateStr }}</span>
                                            </template>
                                            <template v-else>
                                                <span>{{ scope.row.fwdRateStr }}</span>
                                            </template>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </keep-alive>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </el-col>
            <el-col :span="12">
                <div class="table-box">
                    <!-- <div class="clearfix">
                        <el-radio-group v-model="card2">
                            <el-radio-button v-for="item in tab2" :label="item.code">{{item.code}}</el-radio-button>
                        </el-radio-group>
                        <span>利率曲线</span>
                        <span></span>
                    </div> -->
                    <!-- <span class="title">利率曲线</span> -->
                    <el-tabs v-model="card2" type="card">
                        <el-tab-pane v-for="(item, idx) in tab2" :label="item.code" :name="item.code" :key="item.code">
                            <keep-alive>
                                <el-table
                                    :data="item.tableData"
                                    stripe
                                    border
                                    :height="maxHeight"
                                    :max-height="maxHeight"
                                    @row-dblclick="dblclick2"
                                    @row-click="rowClick2"
                                    style="width: 100%">
                                    <el-table-column
                                        prop="tenor"
                                        min-width="40%"
                                        headerAlign="center"
                                        :label="$t('menu.tenor')"
                                        align="center">
                                    </el-table-column>
                                    <el-table-column
                                        prop="endDate"
                                        min-width="40%"
                                        headerAlign="center"
                                        :label="$t('field.maturityDate')"
                                        align="center">
                                        <template slot-scope="scope">
                                            <span>{{ scope.row.endDate.toString().substr(0,4) }}-{{ scope.row.endDate.toString().substr(4,2) }}-{{ scope.row.endDate.toString().substr(6,2) }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        headerAlign="center"
                                        :label="$t('field.interestRate')"
                                        align="right">
                                        <template slot-scope="scope">
                                            <el-input v-if="row2 === scope.row.id && scope.row.valueType !== 'FXSWAP'" type="number" v-model="scope.row.rateStrInput" @blur="inputBlur('tab2', idx, scope)"></el-input>
                                            <span v-else>{{ scope.row.rateStr }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        headerAlign="center"
                                        :label="$t('field.discountRate')"
                                        align="right">
                                        <template slot-scope="scope">
                                            <span>{{ scope.row.dfStr }}</span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </keep-alive>
                        </el-tab-pane>
                      </el-tabs>
                </div>
            </el-col>
            <el-col :span="24">
                <div class="table-box table-box2">
                    <!-- <div class="clearfix">
                        <el-radio-group v-model="card3">
                            <el-radio-button v-for="item in tab3" :label="item.code">{{item.code}}</el-radio-button>
                        </el-radio-group>
                        <span>波动率曲面</span>
                        <span></span>
                    </div> -->
                    <!-- <span class="title">波动率曲面</span> -->
                    <el-tabs v-model="card3" type="card">
                        <el-tab-pane v-for="(item, idx) in tab3" :label="item.code" :name="item.code" :key="item.code">
                            <keep-alive>
                                <el-table
                                    :data="item.tableData"
                                    stripe
                                    border
                                    :height="maxHeight"
                                    :max-height="maxHeight"
                                    @row-dblclick="dblclick3"
                                    @row-click="rowClick3"
                                    style="width: 100%">
                                    <el-table-column
                                        v-for="(inner,index) in item.tableColumns"
                                        :prop="inner.field"
                                        :min-width="index < 2 ? '40%' : 'auto'"
                                        headerAlign="center"
                                        :label="inner.name"
                                        :align="index < 2 ? 'center' : 'right'">
                                        <template slot-scope="scope">
                                            <template v-if="index < 2">
                                                <span v-if="index === 0">{{ scope.row[inner.field] }}</span>
                                                <span v-else>{{ scope.row[inner.field].toString().substr(0,4) }}-{{ scope.row[inner.field].toString().substr(4,2) }}-{{ scope.row[inner.field].toString().substr(6,2) }}</span>
                                            </template>
                                            <template v-else>
                                                <el-input v-if="row3 === scope.row.id" type="number" v-model="scope.row.val[inner.field].VolStr" @blur="inputBlur('tab3', idx, scope)"></el-input>
                                                <span v-else>{{ scope.row.val[inner.field].VolStr }} / <b>{{ scope.row.val[inner.field].StrikeStr }}</b></span>
                                            </template>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </keep-alive>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { findMarketInfoForAnalysis, findMarketPriceForValAnalysis, saveMarketPriceForValAnalysis } from '../../../../api/pmsApi.js';
export default {
  name: 'table',
  props: {
    iconShow: {
        type: Boolean,
        default: false
    }
  },
  data() {
    return {
        tab: {},
        tab1: [],
        tab2: [],
        tab3: [],
        maxHeight: null,
        tableData: [],
        row:'',
        tmpRow:{},
        card1: '',
        tableData2: [],
        row2:'',
        tmpRow2:{},
        card2: '',
        tableData3: [],
        row3:'',
        tmpRow3:{},
        card3: '',
        form: {},
        loading: false,
        queryParamDeal: {}
    };
  },
  mounted() {
    this.init()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy () {
    this.$bus.$off('sendForm');
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    init () {
        this.getForm()
        this.handleResize()
    },
    getForm () {
        new Promise((resolve, reject) =>{
            this.$bus.$on('sendForm',(data) => {
                this.form = data
                resolve(this.form)
            })
        }).then((data) =>{
            this.findMarketInfoForAnalysis()
        }).catch((err) =>{
            // console.log(err)
        })
    },
    // 获取市场数据
    async findMarketInfoForAnalysis () {
        this.loading = true
        console.log('form-----', this.form)
        this.queryParamDeal = {
            "queryParam.deal": {
                instrument: 'FXOPTION',
                priceDate: this.form.date.split('-').join(''),
                optionCategory: this.form.select3,
                ccy1: '',
                ccy2: '',
                underlyingType: 'FX',
                underlying: this.form.select,
                profitCcy: this.form.select22,
                exerciseType: this.form.select5,
                maturityDate: this.form.date3.split('-').join(''),
                deliveryDate: this.form.date4.split('-').join(''),
                premiumDate: this.form.date2.split('-').join(''),
                cutOffTime: this.form.time.split(':').join('') + '00',
                premiumCcy: this.form.select22,
                premiumAmount: this.form.value19,
                ccy: this.form.select8,
                nominal: this.form.value3,
                strike: this.form.value2,
                buySell: this.form.select4,
                callPut: this.form.select6,
                triggerStatus: 'INIT',
                trigger: this.form.value15,
                trigger2: this.form.value16,
                returnRate1: this.form.value17,
                returnRate2: this.form.value18,
                obsType: this.form.select19,
                isUseMid: 'MID',
                paymentAt: this.form.select17,
                paymentAt2: this.form.select18,
                quantoFactor: '',
                quantoCcy: this.form.select9,
                quantoPair: this.form.select10,
                model: this.form.select21
            }
        }
        // let formData = new FormData();
        // formData.append('reqJson', JSON.stringify(this.queryParamDeal))
        const res = await findMarketInfoForAnalysis(this.queryParamDeal)
        if (res.success) {
            this.tab = res.data.result
            this.tab1 = []
            this.tab2 = []
            this.tab3 = []
            for (let key in this.tab) {
                if (this.tab.hasOwnProperty(key)) {
                    this.tab[key].field = key
                    if (this.tab[key].dataType === 'FWD') {
                        this.tab1.push(this.tab[key])
                    }
                    if (this.tab[key].dataType === 'CURVE') {
                        this.tab2.push(this.tab[key])
                    }
                    if (this.tab[key].dataType === 'FXVOL') {
                        this.tab3.push(this.tab[key])
                    }
                }
            }
            // console.log('this.tab,this.tab1,this.tab2,this.tab3-------',this.tab,this.tab1,this.tab2,this.tab3)
            this.card1 = this.tab1.length > 0 ? this.tab1[0].code : ''
            this.card2 = this.tab2.length > 0 ? this.tab2[0].code : ''
            this.card3 = this.tab3.length > 0 ? this.tab3[0].code : ''
            this.findMarketPriceForValAnalysis()
        } else {
            this.$message({
                message: res.message,
                type: 'error'
            })
        }
    },
    // 获取市场价格
    async findMarketPriceForValAnalysis () {
        this.loading = true
        let json = {
            "queryParam.priceDate": this.form.date.split('-').join(''),
            "queryParam.data": this.tab
        }
        // let formData = new FormData();
        // formData.append('reqJson', JSON.stringify(json))
        const res = await findMarketPriceForValAnalysis(json)
        this.loading = false
        if (res.success) {
            let data = res.data.result
            this.formatTable(data)
        } else {
            this.$message({
                message: res.message,
                type: 'error'
            })
        }
    },
    // 保存按钮
    async saveBtn () {
        this.loading = true
        let json = {
            "queryParam.priceDate": this.form.date.split('-').join(''),
            "queryParam.market": this.formatData()
        }
        // let formData = new FormData();
        // formData.append('reqJson', JSON.stringify(json))
        const res = await saveMarketPriceForValAnalysis(json)
        this.loading = false
        if (res.success) {
            let data = res.data.result
            this.formatTable(data)
        } else {
            this.$message({
                message: res.message,
                type: 'error'
            })
        }
    },
    // 接口返回table添加至各tab
    formatTable (data) {
        this.tab1.forEach(item => {
            item.tableData = data[item.field].datals.map((e,index)=>{
                return {
                    id: index,
                    ...e,
                    swapStrInput: e.swapStr.replace(/,/g, ''),
                    fwdRateStrInput: e.fwdRateStr.replace(/,/g, '')
                }
            })
        })
        this.tab2.forEach(item => {
            item.tableData = data[item.field].datals.map((e,index)=>{
                return {
                    id: index,
                    ...e,
                    rateStrInput: e.rateStr.replace(/,/g, '')
                }
            })
        })
        this.tab3.forEach(item => {
            item.tableColumns = data[item.field].columns
            item.tableData = data[item.field].datals.map((e,index)=>{
                return {
                    id: index,
                    ...e
                }
            })
        })
        this.sendTab()
    },
    // 发送给左侧search栏
    sendTab () {
        let obj = {
            "queryParam.priceDate": this.form.date.split('-').join(''),
            "queryParam.market": this.formatData()
        }
        this.$bus.$emit('sendTab',  obj)
    },
    // 处理table成保存接口所需数据格式
    formatData () {
        let obj = {}
        let obj1 = {}
        this.tab1.forEach(item=>{
            obj1[item.field]= {}
            obj1[item.field].datals = item.tableData
            obj1[item.field].code = item.code
            obj1[item.field].dataType = item.dataType
        })
        let obj2 = {}
        this.tab2.forEach(item=>{
            obj2[item.field]= {}
            obj2[item.field].datals = item.tableData
            obj2[item.field].code = item.code
            obj2[item.field].dataType = item.dataType
        })
        let obj3 = {}
        this.tab3.forEach(item=>{
            obj3[item.field]= {}
            obj3[item.field].datals = item.tableData
            obj3[item.field].code = item.code
            obj3[item.field].dataType = item.dataType
        })
        obj = Object.assign({}, obj1, obj2, obj3)
        return obj
    },
    // 获取table最大高度
    handleResize () {
        const box = Array.from(document.getElementsByClassName('optionCalculator-table')) || []
        const boxH = box.find(ele => ele.clientHeight > 0)?.clientHeight || 0
        this.maxHeight = (boxH / 2) - 60 - 13
    },
    dblclick (row, column, event) {
        this.row = row.id
        this.tmpRow = row
    },
    dblclick2 (row, column, event) {
        this.row2 = row.id
        this.tmpRow2 = row
    },
    dblclick3 (row, column, event) {
        this.row3 = row.id
        this.tmpRow3 = row
    },
    rowClick (row, column, event) {
        this.row = row.id === this.row ? this.row  : '' 
        this.row2 = ''
        this.row3 = ''
    },
    rowClick2 (row, column, event) {
        this.row = ''
        this.row2 = row.id === this.row2 ? this.row2  : '' 
        this.row3 = ''
    },
    rowClick3 (row, column, event) {
        this.row = ''
        this.row2 = ''
        this.row3 = row.id === this.row3 ? this.row3  : '' 
    },
    inputBlur (e, index, scope) {
        if (e === 'tab1') {
            if (scope.row.tenor === 'Spot') {
                this.tab1[index].tableData[scope.$index].fwdRateStr = (scope.row.fwdRateStrInput*1).toLocaleString('en-US', {
                    minimumFractionDigits: scope.row.precision.Fwd,
                    maximumFractionDigits: scope.row.precision.Fwd
                }) // 转换千分位
                this.tab1[index].tableData[scope.$index].fwdRateStrInput = (scope.row.fwdRateStrInput*1).toFixed(scope.row.precision.Fwd)
            } else {
                this.tab1[index].tableData[scope.$index].swapStr = (scope.row.swapStrInput*1).toLocaleString('en-US', {
                    minimumFractionDigits: scope.row.precision.Swap,
                    maximumFractionDigits: scope.row.precision.Swap
                })
                this.tab1[index].tableData[scope.$index].swapStrInput = (scope.row.swapStrInput*1).toFixed(scope.row.precision.Swap)
            }
        } else if (e === 'tab2') {
            this.tab2[index].tableData[scope.$index].rateStr = (scope.row.rateStrInput*1).toLocaleString('en-US', {
                minimumFractionDigits: scope.row.precision.Rate,
                maximumFractionDigits: scope.row.precision.Rate
            })
            this.tab2[index].tableData[scope.$index].rateStrInput = (scope.row.rateStrInput*1).toFixed(scope.row.precision.Rate)
        } else if (e === 'tab3') {
            this.tab3[index].tableData[scope.$index].val[scope.column.property].VolStr = (scope.row.val[scope.column.property].VolStr*1).toFixed(4)
        }
    },
    rowFixed({ row, rowIndex, columnIndex }) {
        if (row.tenor === 'Spot') {
            return 'fixedRow'
        }
    }
  }
};
</script>

<style lang="scss">
    .optionCalculator-table{
        .table-box{
            .el-card__body, .el-card__header{
                padding: 0;
            }
            .clearfix{
                width: 100%;
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 30px;
                line-height: 30px;
                position: relative;
                &::after{
                    display: none;
                }
                .el-radio-group{
                    /* position: absolute; */
                    /* left: 0; */
                    .el-radio-button__inner{
                        padding: 5px 10px;
                    }
                }
                .el-button{
                    /* position: absolute; */
                    /* right: 0; */
                    padding: 5px 10px;
                }
            }
            .el-table{
                border-bottom: 1px solid var(--scrollBar);
                .fixedRow{
                    position: sticky;
                    top: 0;
                    width: 100%;
                    z-index: 9;
                    .cell{
                        background-color: var(--scrollBar);
                    }
                }
            }
            .el-table, .el-table__header, .el-table__body {
                width: 100%!important;
            }
            .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);
                        }
                    }
                }
                
            }
            /* number输入框上下箭头隐藏 */
            input::-webkit-outer-spin-button,
            input::-webkit-inner-spin-button {
                -webkit-appearance: none;
            }
            input[type="number"]{
                -moz-appearance: textfield;
            }
        }
    }
</style>
<style lang="scss" scoped>
    .optionCalculator-table{
        background-color: var(--bg-color-2);
        padding: 0 10px;
        height: 100%;
        .btns{
            width: 100%;
            padding: 10px 10px;
            .el-button{
                padding: 5px 10px;
                cursor: pointer;
            }
        }
        &.p-l-36{
            padding-left: 36px;
        }
        .el-row{
            height: calc(100% - 46px);
        }
        .table-box{
            padding: 0 10px;
            height: 100%;
            position: relative;
            &.table-box2{
                padding-top: 20px;
            }
            p{
                margin: 0;
                width: 100%;
                height: 30px;
                line-height: 30px;
                text-align: center;
            }
            .title{
                position: absolute;
                left: 50%;
                transform: translateX(-50%);
            }
        }
    }
</style>