<template>
    <div class="customResult">
        <el-tabs v-if="tabs.length > 0" v-model="activeName" @tab-click="handleClick">
            <el-tab-pane v-for="(item, index) in tabs" :key="item.value" :label="item.label" :name="item.value">
            </el-tab-pane>
        </el-tabs>
        <template>
            <div class="tableBox" v-if="tableConfig.length>0" :style="{ height: maxHeight + 'px' }">
                <CustomTable ref="table" :key="tableKey" v-loading="loading" :configs="tableConfig" :data="tableData" :border="true" :summary-render="summaryRender">
                    <template #dealId="{ row }">
                        <el-link type="primary" @click="onOpenModal(row)">{{row.dealId}}</el-link>
                    </template>
                    <template #folderStr="{ row }">
                        <el-link type="primary" @click="getFolderInfo(row)">{{row.folderStr}}</el-link>
                    </template>
                    <template #action="{ row }">
                        <div class="table-action">
                            <el-tooltip :content="$t('button.print')" placement="bottom">
                                <i class="el-icon-printer" @click="iconClick('1', row)"></i>
                            </el-tooltip>
                            <el-tooltip :content="$t('button.following')" placement="bottom">
                                <i class="el-icon-notebook-2" @click="iconClick('2', row)"></i>
                            </el-tooltip>
                            <el-tooltip :content="$t('button.life')" placement="bottom">
                                <i class="el-icon-alarm-clock" @click="iconClick('3', row)"></i>
                            </el-tooltip>
                        </div>
                    </template>
                </CustomTable>
            </div>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[30, 50, 70, 100, 150]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </template>
        <el-dialog
            :title="title"
            :visible.sync="dialogVisible"
            width="400px">
            <el-form ref="form" :model="form" label-width="100px">
                <el-row>
                    <el-col :span="20">
                        <el-form-item :label="this.$t('field.code')">
                            <el-input v-model="form.code" placeholder="" disabled></el-input>
                        </el-form-item>
                        <el-form-item :label="this.$t('field.shortName')">
                            <el-input v-model="form.name" placeholder="" disabled></el-input>
                        </el-form-item>
                        <el-form-item :label="this.$t('field.name')">
                            <el-input v-model="form.localName" placeholder="" disabled></el-input>
                        </el-form-item>
                        <el-form-item :label="this.$t('field.belongingLedger')">
                            <el-input v-model="form.bookIdName" placeholder="" disabled></el-input>
                        </el-form-item>
                        <el-form-item :label="this.$t('field.profitAndLossCcy')">
                            <el-select v-model="form.currencyId" placeholder="" disabled>
                                <el-option v-for="inner in option1" :label="inner.text" :value="inner.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="this.$t('field.accountAttributes')">
                            <el-select v-model="form.folderStatus" placeholder="" disabled>
                                <el-option v-for="inner in option2" :label="inner.text" :value="inner.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="this.$t('field.accountingClassification')">
                            <el-select v-model="form.accountingSection" placeholder="" disabled>
                                <el-option v-for="inner in option3" :label="inner.text" :value="inner.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="this.$t('field.homeOffshore')">
                            <el-select v-model="form.homeType" placeholder="" disabled>
                                <el-option v-for="inner in option4" :label="inner.text" :value="inner.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { CustomTable } from '@erayt/titanOne-component-vue';
import { dcsQueryPage, queryFieldByProduct, queryComboxData, getFolderInfo } from '../../../api/dcsApi.js';
export default {
  name: 'customResult',
  components: {
    CustomTable
  },
  data() {
    return {
        searchParams: {},
        tabs: [],
        activeName: '',
        tableData: [],
        tableConfig: [],
        publicConfig: [
            {
                label: this.$t('field.transactionSerialNumber'),
                name: 'dealId',
                slot: true,
                headerAlign: 'center',
                align: 'left',
                width: 120,
                fixed: 'left'
            },
            {
                label: this.$t('field.product'),
                name: 'productStr',
                headerAlign: 'center',
                align: 'left',
                fixed: true
            },
            {
                label: this.$t('field.control'),
                name: 'action',
                slot: true,
                width: 100,
                headerAlign: 'center',
                align: 'center',
                fixed: true
            },
            {
                label: this.$t('field.folder'),
                name: 'folderStr',
                slot: true,
                headerAlign: 'center'
            },
            {
                label: this.$t('field.accountType'),
                name: 'folderStatusStr',
                headerAlign: 'center',
                align: 'center',
            },
            {
                label: this.$t('menu.counterparty'),
                name: 'cptyStr',
                headerAlign: 'center',
                align: 'left',
                width: 220
            },
            {
                label: this.$t('field.operatingUsers'),
                name: 'takerId',
                headerAlign: 'center'
            },
            {
                label: this.$t('field.transactionDate'),
                name: 'tradeDateStr',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.startingDate'),
                name: 'valueDateStr',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.expirationDate'),
                name: 'maturityDateStr',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.enterDate'),
                name: 'captureTimeStr',
                headerAlign: 'center',
                align: 'center',
                width: 140
            },
            {
                label: this.$t('field.transactionStatus'),
                name: 'dealStatusStr',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.natureOfTransaction'),
                name: 'dealFlagStr',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.sourceOfTransaction'),
                name: 'sourceName',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.transactionPurpose'),
                name: 'ext20',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.lastModifiedDate'),
                name: 'lastModifyDateStr',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.subjectCategories'),
                name: 'underlyingTypeStr',
                headerAlign: 'center',
                align: 'left'
            },
            {
                label: this.$t('menu.underlying'),
                name: 'underlying',
                headerAlign: 'center',
                align: 'left',
                width: 100
            },
            {
                label: this.$t('field.tradingDirection'),
                name: 'buySellStr',
                headerAlign: 'center',
                align: 'center'
            },
            {
                label: this.$t('field.externalSerialNumber'),
                name: 'globalId',
                headerAlign: 'center',
                align: 'left',
                width: 120
            },
            {
                label: this.$t('field.fatherTransactionSerialNumber'),
                name: 'parentId',
                headerAlign: 'center',
                align: 'left',
                width: 120
            }
        ],
        loading: false,
        currentPage: 1,
        pageSize: 50,
        total: null,
        json: {},
        tableKey: 1,
        title: this.$t('field.accountDetails'),
        dialogVisible: false,
        form: {
            code: '',
            name: '',
            localName: '',
            bookIdName: '',
            currencyId: '',
            folderStatus: '',
            accountingSection: '',
            homeType: '',
        },
        option1: [],
        option2: [],
        option3: [],
        option4: [],
        maxHeight: null
    };
  },
  mounted() {
    this.init()
    this.getOption()
    window.addEventListener('resize', this.handleResize)
  },
  activated () {
    this.init()
    window.addEventListener('resize', this.handleResize)
  },
  deactivated () {
    window.removeEventListener('resize', this.handleResize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    async getOption () {
        let formData = new FormData();
        formData.append('codifierGrpCodes', 'static_currencies,FolderStatus,AccountingSection,HomeType');
        const res = await queryComboxData(formData)
        const result = res.data.result
        this.option1 = result.currencies
        this.option2 = result.FolderStatus
        this.option3 = result.AccountingSection
        this.option4 = result.HomeType
    },
    // 根据产品key转换condition
    conditionChange (key) {
        let condition = []
        if (key === 'FXSPOT' || key === 'FXFWD' || key === 'NDF' || key === 'FXSWAP' || key === 'PMSPOT' || key === 'PMFWD' || key === 'PMSWAP') {
            condition = ['foreignExchangeCondition'] // 外汇即期，远期，NDF, 掉期，贵金属即期，远期，掉期
        } else if (key === 'FXOPTION_VANILA' || key === 'FXOPTION_BARRIER' || key === 'FXOPTION_DIGITAL' || key === 'FXOPTION_TOUCH' || key === 'FXOPTION_ASIAN' || key === 'PMOPTION_VANILA' || key === 'PMOPTION_BARRIER' || key === 'PMOPTION_DIGITAL' || key === 'PMOPTION_TOUCH' || key === 'PMOPTION_ASIAN') {
            condition = ['fxoptionCondition'] // 期权
        } else if (key === 'REPOOUT' || key === 'REPO') {
            condition = ['repoCondition'] // 买断式，质押式
        } else if (key === 'SECLB') {
            condition = ['bondlendingCondition'] // 债券借贷
        } else if (key === 'BOND' || key === 'BONDFWD') {
            condition = ['bondCondition'] // 现券买卖，债券远期
        } else if (key === 'SIMPLECF' || key === 'BRR') {
            condition = ['cashflowCondition'] // 单边现金流，存款准备金
        } else if (key === 'IAM' || key === 'PMLD' || key === 'LOANDEPO' || key === 'LEASE' || key === 'CDS' || key === 'FRA') {
            condition = ['loandepositCondition'] // 同业拆借，贵金属拆借，多期拆借，黄金租赁，信用违约互换，远期利率协议
        } else if (key === 'POSALL') {
            condition = ['posallocationCondition'] // 资金调拨
        } else if (key === 'IRS' || key === 'CCS') {
            condition = ['instrumentlegCondition'] // 利率掉期、货币掉期
        } else if (key === 'CAPFLOOR') {
            condition = ['capfloorCondition'] // 利率上下限
        } else if (key === 'SWAPTION') {
            condition = ['swaptionCondition'] // 利率互换期权
        } else if (key === 'BFUND' || key === 'MFUND') {
            condition = ['fundCondition'] // 债券基金，货币基金
        } else if (key === 'BONDF' || key === 'SBONDF') {
            condition = ['futureCondition'] // 国债期货，标准债券远期
        } else if (key === 'Straddle' || key === 'Strangle' || key === 'Butterfly' || key === 'CallSpread' || key === 'PutSpread' || key === 'Seagull' || key === 'RiskReversal' || key === 'ParticipatoryForward') {
            condition = ['fxoptionCondition', 'contractCondition'] //组合相关--其他、组合号
        }
        return condition
    },
    initJson () {
        this.json = {
            "queryParam.moduleName": "dcsCustomTradeQuery",
            "queryParam.pageStart": this.currentPage,
            "queryParam.pageLimit": this.pageSize,
            "queryParam.loginId": Eui.Share.get("loginId"),
            "queryParam.bankId": Eui.Share.get("bankId")
        }
        let moreConditionRule = JSON.parse(JSON.stringify(this.searchParams.moreConditionRule))
        let moreConditionRule2
        if (this.activeName) {
            this.json["queryParam.products"] = [this.activeName] // 产品
            moreConditionRule2 = this.searchParams.moreConditionRule2[this.conditionChange(this.activeName)[0]] || []
            moreConditionRule2.forEach(item=>{
                if (item) {
                    moreConditionRule.push(item)
                }
            })
        }
        if (moreConditionRule.length > 0) {
            moreConditionRule.forEach(item=>{
                if (item.isNow) {
                    const date = new Date()
                    const yyyy = date.getFullYear()
                    const mm = String(date.getMonth() + 1).padStart(2, '0') // 月份需要加1，并且补零
                    const dd = String(date.getDate()).padStart(2, '0') // 日需要补零
                    const convertedDate = `${yyyy}${mm}${dd}`
                    const convertedDate2 = `${yyyy}-${mm}-${dd}`
                    if (item.Field === 'tradeDate' || item.Field === 'maturityDate') {
                        item.Value = [convertedDate, convertedDate]
                    } else if (item.Field === 'captureTime') {
                        item.Value = [convertedDate2 + ' 00:00:00', convertedDate2 + ' 23:59:59']
                    }
                }
                if (item.isUser) {
                    item.Value = item.Operator === 'EQ' || item.Operator === 'NQ' ? Eui.Share.get('loginId') : [Eui.Share.get('loginId')]
                }
            })
            this.json["queryParam.moreCondition"] = JSON.stringify({ // 交易信息
                "Condition":"AND",
                "Rules": moreConditionRule
            })
        }
        this.conditionChange(this.activeName).forEach(item=>{
            if (this.searchParams[item] && this.searchParams[item].length > 0) {
                this.json['queryParam.' + item] = JSON.stringify({
                    "Condition":"AND",
                    "Rules":this.searchParams[item]
                })
            }
        })
    },
    // 获取table最大高度
    handleResize () {
        const customResult = Array.from(document.getElementsByClassName('customResult')) || []
        const customResultH = customResult.find(ele => ele.clientHeight > 0)?.clientHeight || 0
        const tabs = Array.from(document.getElementsByClassName('el-tabs')) || []
        const tabsH = tabs.find(ele => ele.clientHeight > 0)?.clientHeight || 0
        const pagination = Array.from(document.getElementsByClassName('el-pagination')) || []
        const paginationH = pagination.find(ele => ele.clientHeight > 0)?.clientHeight || 0
        if (this.searchParams.products.length > 0) {
            this.maxHeight = customResultH - tabsH - paginationH - 10
        } else {
            this.maxHeight = customResultH - paginationH - 10
        }
    },
    async init () {
        this.loading = true
        this.searchParams = JSON.parse(localStorage.getItem('params'))
        if (this.searchParams.products.length > 0) {
            this.tabs = this.searchParams.products
            this.activeName = this.tabs[0].value
            await this.queryFieldByProduct()
        } else {
            this.tabs = []
            this.activeName = ''
            this.tableConfig = [...this.publicConfig]
        }
        this.handleResize()
        this.initJson()
        this.queryPage(this.json)
    },
    async queryPage (params) {
        let formData = new FormData();
        formData.append('reqJson', JSON.stringify(params));
        const res = await queryPage(formData)
        this.tableData = res.data.result.datals
        this.total = res.data.result.total
        this.loading = false
    },
    // tab切换
    async handleClick () {
        this.currentPage = 1
        this.pageSize = 50
        this.loading = true
        this.initJson()
        await this.queryFieldByProduct()
        this.queryPage(this.json)
    },
    // 获取产品表头
    async queryFieldByProduct () {
        let data = {
            areaType: 'QueryArea',
            product: this.activeName
        }
        let formData = new FormData();
        formData.append('reqJson', JSON.stringify(data));
        const res = await queryFieldByProduct(formData)
        let arr = []
        res.data.result.forEach(item => {
            let obj = {
                label: item.fieldLocalName,
                name: item.fieldCode,
                headerAlign: 'center'
            }
            if (item.fieldDataType === '1' || item.fieldDataType === '3') {
                obj.align = 'center'
            } else if (item.fieldDataType === '4') {
                obj.align = 'right'
                obj.width = 120,
                obj.showSummary =  true
            }
            arr.push(obj)
        });
        this.tableConfig = [...this.publicConfig, ...arr]
        this.tableKey = Math.floor(Math.random() * Math.pow(10, 16))
    },
    handleSizeChange (e) {
        this.pageSize = e
        this.currentPage = 1
        this.loading = true
        this.initJson()
        this.queryPage(this.json)
    },
    handleCurrentChange (e) {
        this.currentPage = e
        this.loading = true
        this.initJson()
        this.queryPage(this.json)
    },
    // 账户详情
    async getFolderInfo (row) {
        const data = {
            code: row.folder
        }
        let formData = new FormData();
        formData.append('reqJson', JSON.stringify(data));
        const res = await getFolderInfo(formData)
        this.form = {
            code: res.data.result.code,
            name: res.data.result.name,
            localName: res.data.result.localName,
            bookIdName: res.data.result.bookIdName,
            currencyId: res.data.result.currencyId + '',
            folderStatus: res.data.result.folderStatus,
            accountingSection: res.data.result.accountingSection,
            homeType: res.data.result.homeType
        }
        this.dialogVisible = true
    },
    // 操作按钮
    iconClick (index, row) {
        if (index === '1') {
            const dealId = row.dealId
            const product = row.product
            const instrument = row.product
            const data = {
                id: 1, // id必填 后续通过此id可修改弹窗信息
                text: '打印', // 标题
                href: '/dcs/dcs/dcsDailyTradeQuery/tradePrint', // 路由 对应路由表里配置的路由
                loadMode: 'iframe',
                width: 750, //宽 必须是数字类型
                height: 516 - 45,
                customclass: 'user-modifyPwd', //自定义类名
                maximize: true, //最大化功能
                minimize: true, //最小化功能
                draggable: true, //拖拽功能
                modal: true, //蒙层
                appendToBody: true, //是否添加进body
                closeonclickModal: false, //点击蒙层是否关闭弹窗
                extraParams: {
                // 额外参数
                // loginId: Eui.share.get('loginId')，// 获取登陆loginId
                dealId,
                product,
                instrument
                }
            };
            Eui.openVueWin(data);
        } else if (index === '2') {
            const dealId = row.dealId
            const product = row.product
            const instrument = row.product
            const data = {
                id: 1, // id必填 后续通过此id可修改弹窗信息
                text: '跟踪', // 标题
                href: '/dcs/dcs/dcsDailyTradeQuery/tradeQueryTrace', // 路由 对应路由表里配置的路由
                loadMode: 'iframe',
                width: 750, //宽 必须是数字类型
                height: 516 - 45,
                customclass: 'user-modifyPwd', //自定义类名
                maximize: true, //最大化功能
                minimize: true, //最小化功能
                draggable: true, //拖拽功能
                modal: true, //蒙层
                appendToBody: true, //是否添加进body
                closeonclickModal: false, //点击蒙层是否关闭弹窗
                extraParams: {
                // 额外参数
                // loginId: Eui.share.get('loginId')，// 获取登陆loginId
                dealId,
                product
                }
            };
            Eui.openVueWin(data);
        } else if (index === '3') {
            const dealId = row.dealId
            const product = row.product
            const instrument = row.product
            let id = this.$menuMap.get('/dcs/dcs/dcsLifeCycle/index')
            this.$router.push(`/iframe/${id}?dealId=${dealId}&product=${product}&instrument=${instrument}&title=生命周期`)
        }
    },
    onOpenModal(row) {
      const data = {
        id: 1, // id必填 后续通过此id可修改弹窗信息
        text: row.productStr, // 标题
        href: '/dcs/dcs/dcsInput/index', // 路由 对应路由表里配置的路由
        loadMode: 'iframe', // 加载方式 iframe
        width: 750, //宽 必须是数字类型
        height: 516 - 45,
        customclass: 'user-modifyPwd', //自定义类名
        maximize: true, //最大化功能
        minimize: true, //最小化功能
        draggable: true, //拖拽功能
        modal: true, //蒙层
        appendToBody: true, //是否添加进body
        closeonclickModal: false, //点击蒙层是否关闭弹窗
        extraParams: {
          // 额外参数
          // loginId: Eui.share.get('loginId')，// 获取登陆loginId
          dealId: row.dealId,
          product: row.product
        }
      };
      Eui.openVueWin(data);
    },
    // 汇总
    summaryRender (h, scopeData) {
        if (this.tableData.length > 0) {
           const {column} = scopeData
            let arr = []
            let tofix = null
            let sum = null
            this.tableData.forEach(item=>{
                tofix = tofix ? tofix : item[column.property].split('.')[1].length
                arr.push((item[column.property].replace(/,/g, '')) * 1)
                sum += (item[column.property].replace(/,/g, '')) * 1
            })
            let max = Math.max(...arr)
            let min = Math.min(...arr)
            let avg = sum/arr.length
            let sumStr = sum.toLocaleString('en-US', {
                        minimumFractionDigits: tofix,
                        maximumFractionDigits: tofix
                    })
            let maxStr = max.toLocaleString('en-US', {
                        minimumFractionDigits: tofix,
                        maximumFractionDigits: tofix
                    })
            let minStr = min.toLocaleString('en-US', {
                        minimumFractionDigits: tofix,
                        maximumFractionDigits: tofix
                    })
            let avgStr = avg.toLocaleString('en-US', {
                        minimumFractionDigits: tofix,
                        maximumFractionDigits: tofix
                    })
            let str = `${column.label}: Sum=${sumStr} Max=${maxStr} Avg=${avgStr} Min=${minStr}`
            return <div style={{ padding: '8px 12px',position: 'fixed', bottom: '58px', left: '0', 'font-size': '13px'}}>{str}</div> 
        }
    }
  }
};
</script>

<style lang="scss">
    .customResult{
        height: 100%;
        background-color: var(--table-cell-striped-bg);
        color: var(--color-90);
        font-size: 12px;
        .el-tabs__item{
            font-size: 12px;
        }
        .el-form-item, .el-select{
            width: 100%;
        }
        .el-form-item{
            margin-bottom: 10px;
        }
        .el-input, .el-input__inner, .el-input__suffix span i{
            height: 20px!important;
            line-height: 20px!important;
        }
        .el-table__fixed-header-wrapper{
            z-index: 99;
        }
        .tableBox {
            /* .el-table .el-table__body-wrapper{
                max-height: 600px;
                overflow: hidden;
                overflow-y: auto;
                overflow-x: auto;
            } */
            .table-action{
                height: 100%;
                display: flex;
                justify-content: space-around;
                align-items: center;
                color: var(--blue-50);
                font-size: 14px;
                i{
                    cursor: pointer;
                }
            }
        }
        .el-pagination{
            text-align: right;
            position: fixed;
            bottom: 52px;
            right: 36px;
            box-shadow: none;
            .el-pager li{
                height: 20px;
                line-height: 20px;
                margin-top: 5px;
            }
        }
        .el-tabs .el-tabs__header .el-tabs__nav-wrap{
            padding: 0 16px;
        }
    }
</style>