<template>
    <div>
        <el-dialog
            :title="$t('field.valuationResults')"
            :visible="dialogVisible"
            width="900px"
            class="trialDialog"
            append-to-body
            :close-on-click-modal="false"
            :before-close="handleClose">
            <div class="box" v-loading="loading">
                <div class="b-top">
                    <p>
                        <span>{{$t('field.valuationDate')}}</span>
                        <el-date-picker
                            v-model="vlDate"
                            type="date"
                            value-format="yyyyMMdd"
                            :disabled="disabled"
                            @change="dateChange"
                            :placeholder="$t('field.chooseDate')">
                        </el-date-picker>
                    </p>
                    <p v-if="globalId">
                        <span>{{$t('field.dealsId')}}</span>
                        <b>{{globalId}}</b>
                        <el-tooltip class="item" v-if="errorCode && errorCode !== '0'" effect="dark" :content="errorCode" placement="top">
                            <em>错误代码: 009</em>
                        </el-tooltip>
                    </p>
                </div>
                <el-tabs v-model="activeName">
                    <el-tab-pane :label="$t('field.valuationResults')" name="first" style="height: 400px">
                        <div class="tab-box">
                            <ul>
                                <li v-for="(item) in vlResult" :key="item.text">
                                    <span>{{item.text}}</span>
                                    <span>{{item.value}}</span>
                                </li>
                            </ul>
                        </div>
                        <div class="tab-box">
                            <p><em></em><b>{{$t('field.marketData')}}</b></p>
                            <ul>
                                <li v-for="(item) in vlMarket" :key="item.text">
                                    <span >{{item.text}}</span>
                                    <el-link v-if="item.link" type="primary">{{item.value}}</el-link>
                                    <span v-else :title="item.value" class="text-sty">{{item.value}}</span>
                                </li>
                            </ul>
                        </div>
                        <div class="tab-box">
                            <p>
                                <em></em>
                                <b style="cursor: pointer;" @click="moreShow=!moreShow">{{$t('field.more')}}
                                    <i v-if="moreShow" class="el-icon-arrow-up"></i>
                                    <i v-else class="el-icon-arrow-down"></i>
                                </b>
                            </p>
                            <ul class="more" v-show="moreShow">
                                <template v-if="vlMore.length > 2">
                                    <li class="noBorder" v-for="(item) in vlMore" :key="item.text">
                                        <span>{{item.text}}</span>
                                        <span>{{item.value}}</span>
                                    </li>
                                </template>
                                <template v-else>
                                    <li v-for="(item, index) in vlMore" :key="index">
                                        <p>{{Object.keys(item)[0]}}</p>
                                        <ul>
                                            <li v-for="(inner, ) in item[Object.keys(item)[0]]" :key="inner.text">
                                                <span>{{inner.text}}</span>
                                                <span>{{inner.value}}</span>
                                            </li>
                                        </ul>
                                    </li>
                                </template>
                            </ul>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane v-if="cashTabs.length > 0" label="现金流" name="second">
                        <el-tabs v-model="card" type="card">
                            <el-tab-pane v-for="(item) in cashTabs" :label="item.code" :name="item.code" :key="item.code" style="height: 400px">
                                <el-checkbox-group v-model="item.checked" class="check-box" @change="val => checkChange(val, item.code)">
                                  <el-checkbox v-for="item in checkList" :label="item.value" :key="item.value">{{item.text}}</el-checkbox>
                                </el-checkbox-group>
                                <el-table :data="item.tableData" stripe border style="width: 100%" :header-cell-style="{'text-align': 'center'}">
                                  <el-table-column width="1" />
                                  <div v-for="(col, idx) in item.columns" :key="idx">
                                    <el-table-column :label="col.label" :prop="col.key" :width="100"  :align="col.align || 'center'"
                                      :sortable="col.key === 'cashflowType' || col.key === 'paymentDate'">
                                      <template slot-scope="scope">
                                        <template v-if="col.isLink && scope.row.hasChildren">
                                          <el-link :underline="false" type="primary" @click="click1(scope.row)">{{scope.row[col.key]}}</el-link>
                                        </template>
                                        <template v-else>
                                          <span>{{scope.row[col.key]}}</span>
                                        </template>
                                      </template>
                                    </el-table-column>
                                  </div>
                                </el-table>
                                <!-- <keep-alive>
                                    <el-table
                                        :data="item.tableData"
                                        stripe
                                        border
                                        style="width: 100%">
                                        <el-table-column
                                            prop="cashflowType"
                                            headerAlign="center"
                                            label="现金流类型"
                                            min-width="140"
                                            align="left">
                                        </el-table-column>
                                        <el-table-column
                                            prop="periodStartDateAdj"
                                            headerAlign="center"
                                            label="开始日期"
                                            align="center">
                                            <template slot-scope="scope">
                                                <span>{{ scope.row.periodStartDateAdj.toString().substr(0, 4) + '-' + scope.row.periodStartDateAdj.toString().substr(4, 2) + '-' + scope.row.periodStartDateAdj.toString().substr(6, 2) }}</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="periodEndDateAdj"
                                            headerAlign="center"
                                            label="结束日期"
                                            align="center">
                                            <template slot-scope="scope">
                                                <span>{{ scope.row.periodEndDateAdj.toString().substr(0, 4) + '-' + scope.row.periodEndDateAdj.toString().substr(4, 2) + '-' + scope.row.periodEndDateAdj.toString().substr(6, 2) }}</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="amount"
                                            headerAlign="center"
                                            label="金额"
                                            align="right">
                                            <template slot-scope="scope">
                                                <span>{{ formatNum(scope.row.amount, 2) }}</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="coupon"
                                            headerAlign="center"
                                            label="利率"
                                            align="right">
                                            <template slot-scope="scope">
                                                <el-link v-if="scope.row.children && scope.row.children.length > 0" type="primary" @click="openDialog(scope.row)">{{ scope.row.coupon ? (scope.row.coupon*1).toFixed(8) : '' }}</el-link>
                                                <span v-else>{{ scope.row.coupon ? (scope.row.coupon*1).toFixed(8) : '' }}</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="dfAmount"
                                            headerAlign="center"
                                            label="贴现金额"
                                            align="right">
                                            <template slot-scope="scope">
                                                <span>{{ formatNum(scope.row.dfAmount, 2) }}</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="paymentDateDf"
                                            headerAlign="center"
                                            label="贴现"
                                            align="center">
                                            <template slot-scope="scope">
                                                <span>{{ (scope.row.paymentDateDf*1).toFixed(8) }}</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="paymentDate"
                                            headerAlign="center"
                                            label="支付日期"
                                            align="center">
                                            <template slot-scope="scope">
                                                <span>{{ scope.row.paymentDate.toString().substr(0, 4) + '-' + scope.row.paymentDate.toString().substr(4, 2) + '-' + scope.row.paymentDate.toString().substr(6, 2) }}</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="date"
                                            headerAlign="center"
                                            label="天数"
                                            align="center">
                                        </el-table-column>
                                    </el-table>
                                </keep-alive> -->
                            </el-tab-pane>
                        </el-tabs>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <span slot="footer">
                <el-button size="small" @click="handleClose">关闭</el-button>
            </span>
        </el-dialog>
        <!-- <CashFlowDialog ref="cashFlowDialog"></CashFlowDialog> -->
        <cashFlowMsgBox ref="cashFlowMsgBox" v-if="isShow" :isShow="isShow" :columns="dialogCols" :desList="dialogDes" :tableData="dialogTable" @handleClose="closeDialog"></cashFlowMsgBox>
    </div>
</template>

<script>
import { pmsFindPmsResultDetail } from '@/api/pmsApi.js'
// import CashFlowDialog from './cashFlowDialog.vue'
// import * as colsList from './colsList.js'
import {setData} from './colsList.js'
import {formatMoney, formateDate} from '@/utils' 
export default {
    name: 'trialDiallogStandard',
    components: {
        // CashFlowDialog,
        cashFlowMsgBox: () => import('./cashFlowMsgBox.vue')
    },
    props: {
        disabled: {
            type: Boolean,
            default: () => false
        },
        isQueryAction: {            // 是否查询操作
            type: Boolean,
            default: () => true
        },
        rawData: {
            type: Object,
            default: () => {}
        },
        sysDate: {
            type: Number,
            default: () => 0
        }
    },
    data() {
        return {
            dialogVisible: false,
            vlDate: null,
            globalId: '',
            errorCode: '',
            activeName: 'first',
            vlResult: [],
            vlMarket: [],
            vlMore: [],
            moreShow: false,
            formData: null,
            form: {},
            options: null,
            dialogResultType: '',
            card: '',
            cashTabs: [],
            loading: false,
            checkList: [
                { text: '显示本金', value: 'ben' },
                { text: '显示已支付现金流', value: 'cash' }
            ],
            isShow: false,
            dialogDes: [],
            dialogCols: [],
            dialogTable: []
        }
    },
    mounted() {
    },
    methods: {
        init (json, type, data) {
            this.formData = json
            this.form = data.form ? JSON.parse(JSON.stringify(data.form)) : {}
            this.options = data.options || []
            this.vlResult = data.table || []
            this.vlMarket = data.dialogTable || []
            this.dialogResultType = type
            this.dialogVisible = true
            this.activeName = 'first'
            this.moreShow = false
            if (!this.isQueryAction) {
              this.handleData(this.rawData)
            } else {
              this.pmsFindPmsResultDetail(this.formData)
            }
        },
        handleData(rawData) {
        //   console.log(rawData);
          const data = JSON.parse(JSON.stringify(rawData))
          this.cashTabs = []
          this.vlDate = data.vlDate.toString() || this.vlDate
          this.globalId = data.globalId
          this.errorCode = data.errorCode
          this.vlResult = data.vlResult || []
          this.vlMarket = data.vlMarket || []
          this.vlMore = data.vlMore ? (Object.prototype.toString.call(data.vlMore) === '[object Object]' ? this.objToArray(data.vlMore) : data.vlMore) : []
          // 现金流tab处理
          let arr = []
          for (const key in data) {
            if (key !== 'vlParam' && key !== 'vlResult' && key !== 'vlMarket' && key !== 'vlMore' && key !== 'vlDate' && key !== 'globalId' && key !== 'errorCode') {
              let json = {
                code: key,
                checked: ['ben', 'cash'],
                columns: this.setColumn(data[key][0].indexation, data[key][0].freq, data[key][0].isSofr),
                cashData: this.formateData(data[key]),
                tableData: data[key],
                
              }
              arr.push(json)
            }
          }
          this.cashTabs = arr.sort((a, b) => a.code.localeCompare(b.code))
          this.card = this.cashTabs.length > 0 ? this.cashTabs[0].code : ''
        //   console.log(this.cashTabs, '11111111111');
        },
        handleClose () {
            this.dialogVisible = false
        },
        async dateChange (date) {
            this.formData.vlDate = date.split('-').join('')
            this.pmsFindPmsResultDetail(this.formData)
        },
        // 逐笔估值结果
        async pmsFindPmsResultDetail (formData) {
            this.loading = true
            // const params = new URLSearchParams()
            // params.append('queryParam.globalId', formData.globalId)
            // params.append('queryParam.vlDate', formData.vlDate)
            const params = {
              'queryParam.globalId': formData.globalId,
              'queryParam.vlDate': formData.vlDate
            }
            const res = await pmsFindPmsResultDetail(params)
            if (res.success) {
              let data = res.data.result
              this.handleData(data)  
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
            this.loading = false
        },
        objToArray(obj) {
            var arr = []
            for (var key in obj) {
                let json = {}
                json[key] = obj[key]
                arr.push(json);
            }
            return arr
        },
        openDialog (row) {
            this.$refs.cashFlowDialog.init(row)
        },
        formatNum (e, digit) {
            return (e*1).toLocaleString('en-US', {
                minimumFractionDigits: digit,
                maximumFractionDigits: digit
            }) // 转换千分位
        },
        checkChange (val, code) {
          this.cashTabs.forEach(item => {
            if (item.code === code) {
              if (val.length > 1) {
                item.tableData = item.cashData
              } else {
                if (!val.includes('ben')) item.tableData = item.cashData.filter(x => x.cashflowType === 'PRINCIPAL')
                if (!val.includes('cash')) item.tableData = item.cashData.filter(x => Number(x.paymentDate.replace(/-/g, '')) <= this.sysDate)
              }
            }
          })
        },
        click1(row) {
            this.dialogCols = row.columns || []
            if (Object.keys(row.labelData).length > 0) {
              for (const key in row.labelData) {
                row.labelInfo.forEach(item => {
                  if (item.field === key) item.value = row.labelData[key]
                })
              }
            }
            this.dialogDes = JSON.parse(JSON.stringify(row.labelInfo))
            this.dialogTable = row.children || []
            this.isShow = true
        },
        closeDialog() {
          this.isShow = false
        },
        setColumn(indexation, freq, isSofr) {
          if (indexation === 'FIXED') {                   // 固息
            if (freq) {
              return setData(0).rawTable
            } else {
                return setData(1).rawTable
            }
          } else {                                       // 浮息
            if (freq && !isSofr) {
              return setData(2).rawTable
            } else if (!freq && !isSofr) {
              return setData(3).rawTable
            } else if (freq && isSofr) {
              return setData(4).rawTable
            } else {
              return setData(5).rawTable
            }
          }
        },
        formateData(list) {
          list.forEach(item => {
            item.coupon = item.coupon ? formatMoney(item.coupon, 8) : ''
            item.paymentDateDf = item.paymentDateDf ? formatMoney(item.paymentDateDf, 8) : ''
            item.fixingRate = item.fixingRate ? formatMoney(item.fixingRate, 8) : ''
            item.amount =item.amount ? formatMoney(item.amount, 2) : ''
            item.dfAmount = item.dfAmount ? formatMoney(item.dfAmount, 2) : ''
            item.startDateDf = item.startDateDf ? formatMoney(item.startDateDf, 8) : ''
            item.endDateDf = item.endDateDf ? formatMoney(item.endDateDf, 8) : ''
            item.nominal = item.nominal ? formatMoney(item.nominal, 2) : ''
            item.startDate = item.startDate ? formateDate(item.startDate) : ''
            item.endDate = item.endDate ? formateDate(item.endDate) : ''
            item.paymentDate = item.paymentDate ? formateDate(item.paymentDate) : ''
            item.periodStartDate = item.periodStartDate ? formateDate(item.periodStartDate) : ''
            item.periodEndDate = item.periodEndDate ? formateDate(item.periodEndDate) : ''
            item.fixingDate = item.fixingDate ? formateDate(item.fixingDate) : ''
          })
          return list
        }
    }
};
</script>

<style lang="scss" scoped>
    .trialDialog{
        .box{
            .b-top {
                padding: 0 40px;
                display: flex;
                align-items: center;
                margin-bottom: 10px;
                p{
                    width: 50%;
                    margin: 0;
                    color: var(--color-70);
                    &>span{
                        display: inline-block;
                        width: 110px;
                        text-align: right;
                        margin-right: 8px;
                    }
                    b{
                        font-weight: normal;
                        color: #000;
                    }
                    .el-date-editor{
                        width: 200px;
                    }
                    em {
                        padding: 2px 6px;
                        font-style: normal;
                        color: var(--red-60);
                        border: 1px solid var(--red-60);
                        border-radius: 4px;
                        margin-left: 8px;
                    }
                }
            }
            .text-sty {
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
            }
            .el-tabs{
                ::v-deep .el-tabs__content{
                    max-height: 500px;
                    overflow: hidden;
                    overflow-y: auto;
                    .tab-box{
                        border: 1px solid var(--scrollBar);
                        border-radius: 4px;
                        margin-bottom: 10px;
                        p{
                            padding: 0 30px;
                            position: relative;
                            height: auto;
                            color:var(--table-text-color);
                            em{
                                display: inline-block;
                                position: absolute;
                                top: 0;
                                bottom: 0;
                                left: 20px;
                                width: 4px;
                                background-color: var(--blue-70);
                                border-radius: 4px;
                                margin-right: 8px;
                            }
                        }
                        ul{
                            display: flex;
                            flex-wrap: wrap;
                            padding: 0 40px;
                            color:var(--table-text-color);
                            li{
                                width: 50%;
                                list-style: none;
                                margin-bottom: 10px;
                                display: flex;
                                align-items: center;
                                &.more{
                                    width: 100%;
                                }
                                &>span{
                                    display: inline-block;
                                    &:nth-of-type(1) {
                                        width: 110px;
                                        text-align: right;
                                        margin-right: 8px;
                                        color: var(--color-70);
                                    }
                                    &:nth-of-type(2) {
                                        width: 200px;
                                        height: 30px;
                                        line-height: 30px;
                                        padding: 0 10px;
                                        border: 1px solid var(--scrollBarHover);
                                        background-color: var(--scrollBar);
                                        border-radius: 4px;
                                    }
                                }
                                .el-input, .el-select{
                                    width: 200px;
                                }
                                a{
                                    margin: 6px 10px;
                                }
                            }
                            &.more{
                                padding: 0 20px;
                                justify-content: space-between;
                                &>li{
                                    width: 49%;
                                    display: block;
                                    border: 1px solid var(--scrollBar);
                                    border-radius: 4px;
                                    &.noBorder{
                                        border: none;
                                    }
                                    p{
                                        padding: 0 20px;
                                        font-weight: 600;
                                        color: var(--blue-70); 
                                    }
                                    ul {
                                        padding: 0 10px;
                                        li{
                                            width: 100%;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            ::v-deep .el-tabs.el-tabs--card{
                .el-tabs__header{
                    border-bottom: none;
                    margin-bottom: 10px;
                    .el-tabs__nav{
                        border: none;
                    }
                    .el-tabs__nav-wrap .el-tabs__item{
                        padding: 0 10px;
                        height: 26px;
                        line-height: 26px;
                        border: 1px solid var(--scrollBar);
                        border-right: 0;
                        &:last-child{
                            border-right: 1px solid var(--scrollBar);
                        }
                        &.is-active{
                            color: var(--blue-50);
                        }
                    }
                } 
            }
            .el-table{
                border-bottom: 1px solid var(--scrollBar);
            }
            ::v-deep .el-table, ::v-deep .el-table__header, ::v-deep .el-table__body {
                width: 100%!important;
            }
            .check-box {
              position: absolute;
              right: 10;
              margin-top: -40px;
            //   z-index: 999;
            //  float: right;
            //  margin-bottom: 8px;
            }
        }
        ::v-deep .el-dialog__footer{
            border-top: 1px solid var(--scrollBar);
        }
    }
</style>