<template>
    <div class="topSearch">
        <div class="ts-list" v-for="(list, idx) in searchForm" :key="idx">
            <div class="leftBox">
                <i class="el-icon-plus" @click="addItem"></i>
                <i class="el-icon-delete" @click="delItem(idx)"></i>
                <span>{{product}}</span>
                <el-input ref="input" class="l-input" v-model="list.input" placeholder="" @focus="inputFocus(idx)">
                    <i slot="suffix" class="el-input__icon el-icon-search" @click="handleIconClick(idx)"></i>
                </el-input>
                <div ref="panel" class="panel" v-show="list.panelShow">
                    <div class="p-item" v-if="list.checkBox.length" v-for="(item, index) in list.checkBox">
                        <el-checkbox v-model="item.checkAll" @change="handleCheckAllChange($event, idx, index)"></el-checkbox>
                        <el-checkbox-group v-model="item.checked" @change="handleCheckedCitiesChange($event, idx, index)">
                            <el-checkbox v-if="filterArr.includes(inner.value)" v-for="inner in item.checkLists" :label="inner.value" :key="inner.item+idx">{{inner.label}}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </div>
            </div>
            <div class="rightBox">
                <el-form ref="form" :model="list.form" label-width="120px">
                    <el-row>
                        <el-col v-for="item in list.formLists" :span="11" :key="item.key+idx">
                            <el-form-item :label="item.label">
                                <el-input v-if="item.type === 'input'" :type="item.inputType" v-model="list.form[item.key]" :placeholder="item.placeholder||''" @blur="inputBlur($event, item, idx)"></el-input>
                                <el-select v-else-if="item.type === 'select'" v-model="list.form[item.key]" filterable :multiple="item.multiple" :collapse-tags="item.collapseTags" :placeholder="item.placeholder||''">
                                    <el-option v-for="inner in item.option" :label="inner.text" :value="inner.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import { queryComboxData, queryBondList, pubqueryList } from '../../../../api/dcsApi.js';
export default {
  name: 'topSearch',
  data() {
    return {
        filterArr: [],
        product: this.$t('field.product'),
        obj: {
                formLists: [],
                form: {},
                input: '',
                checked: [],
                type: '',
                panelShow: false,
                checkBox: [
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '1',
                        checkLists: [
                            {
                                label: this.$t('field.foreignExchangeSpot'),
                                value: 'FXSPOT'
                            },
                            {
                                label: this.$t('field.foreignExchangeForward'),
                                value: 'FXFWD'
                            },
                            {
                                label: this.$t('field.NDF'),
                                value: 'NDF'
                            },
                            {
                                label: this.$t('field.foreignExchangeSwap'),
                                value: 'FXSWAP'
                            },
                            {
                                label: this.$t('field.preciousMetalsSpot'),
                                value: 'PMSPOT'
                            },
                            {
                                label: this.$t('field.longTermPreciousMetals'),
                                value: 'PMFWD'
                            },
                            {
                                label: this.$t('field.preciousMetalSwap'),
                                value: 'PMSWAP'
                            }
                        ]
                    },
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '2',
                        checkLists: [
                            {
                                label: this.$t('field.foreignExchangeCommonOptions'),
                                value: 'FXOPTION_VANILA'
                            },
                            {
                                label: this.$t('field.foreignExchangeBarrierOptions'),
                                value: 'FXOPTION_BARRIER'
                            },
                            {
                                label: this.$t('field.foreignExchangeDigitalOptions'),
                                value: 'FXOPTION_DIGITAL'
                            },
                            {
                                label: this.$t('field.forexTouchOptions'),
                                value: 'FXOPTION_TOUCH'
                            },
                            {
                                label: this.$t('field.forexAsianOptions'),
                                value: 'FXOPTION_ASIAN'
                            },
                            {
                                label: this.$t('field.preciousMetalCommonOptions'),
                                value: 'PMOPTION_VANILA'
                            },
                            {
                                label: this.$t('field.preciousMetalBarrierOptions'),
                                value: 'PMOPTION_BARRIER'
                            },
                            {
                                label: this.$t('field.preciousMetalDigitalOptions'),
                                value: 'PMOPTION_DIGITAL'
                            },
                            {
                                label: this.$t('field.preciousMetalTouchOptions'),
                                value: 'PMOPTION_TOUCH'
                            },
                            {
                                label: this.$t('field.preciousMetalAsianOptions'),
                                value: 'PMOPTION_ASIAN'
                            },
                            {
                                label: this.$t('menu.straddleOptionsCombo'),
                                value: 'Straddle'
                            },
                            {
                                label: this.$t('menu.strangleOptionsCombo'),
                                value: 'Strangle'
                            },
                            {
                                label: this.$t('menu.butterflyOptionsCombo'),
                                value: 'Butterfly'
                            },
                            {
                                label: this.$t('menu.bullCallSpreadCombo'),
                                value: 'CallSpread'
                            },
                            {
                                label: this.$t('menu.bearPutSpreadCombo'),
                                value: 'PutSpread'
                            },
                            {
                                label: this.$t('menu.seagullOptionsCombo'),
                                value: 'Seagull'
                            },
                            {
                                label: this.$t('menu.riskReversalCombo'),
                                value: 'RiskReversal'
                            },
                            {
                                label: this.$t('menu.participatingForwardCombo'),
                                value: 'ParticipatoryForward'
                            }
                        ]
                    },
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '3',
                        checkLists: [
                            {
                                label: this.$t('field.outrightRepo'),
                                value: 'REPOOUT'
                            },
                            {
                                label: this.$t('field.collateralisedRepo'),
                                value: 'REPO'
                            },
                            {
                                label: this.$t('field.bondLending'),
                                value: 'SECLB'
                            }
                        ]
                    },
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '4',
                        checkLists: [
                            {
                                label: this.$t('field.cashCouponTrading'),
                                value: 'BOND'
                            },
                            {
                                label: this.$t('field.bondForward'),
                                value: 'BONDFWD'
                            }
                        ]
                    },
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '5',
                        checkLists: [
                            {
                                label: this.$t('field.unilateralCashFlow'),
                                value: 'SIMPLECF'
                            },
                            {
                                label: this.$t('field.depositReserve'),
                                value: 'BRR'
                            },
                            {
                                label: this.$t('field.interbankBorrowing'),
                                value: 'IAM'
                            },
                            {
                                label: this.$t('field.preciousMetalLending'),
                                value: 'PMLD'
                            },
                            {
                                label: this.$t('field.multiTermLending'),
                                value: 'LOANDEPO'
                            },
                            {
                                label: this.$t('field.fundAllocation'),
                                value: 'POSALL'
                            },
                            {
                                label: this.$t('field.goldLeasing'),
                                value: 'LEASE'
                            },
                            {
                                label: this.$t('field.creditDefaultSwap'),
                                value: 'CDS'
                            },
                            {
                                label: this.$t('field.forwardRateAgreement'),
                                value: 'FRA'
                            }
                        ]
                    },
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '6',
                        checkLists: [
                            {
                                label: this.$t('menu.irsDeal'),
                                value: 'IRS'
                            },
                            {
                                label: this.$t('menu.interestRateCapFloor'),
                                value: 'CAPFLOOR'
                            },
                            {
                                label: this.$t('menu.interestRateSwaption'),
                                value: 'SWAPTION'
                            }
                        ]
                    },
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '7',
                        checkLists: [
                            {
                                label: this.$t('menu.bondFund'),
                                value: 'BFUND'
                            },
                            {
                                label: this.$t('menu.moneyFund'),
                                value: 'MFUND'
                            }
                        ]
                    },
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '8',
                        checkLists: [
                            {
                                label: this.$t('menu.treasuryBondf'),
                                value: 'BONDF'
                            },
                            {
                                label: this.$t('menu.standardBondf'),
                                value: 'SBONDF'
                            }
                        ]
                    },
                    {
                        checkAll: false,
                        checked: [],
                        checkType: '9',
                        checkLists: [
                            {
                                label: this.$t('menu.ccsDeal'),
                                value: 'CCS'
                            }
                        ]
                    }
                ]
            },
        searchForm: [],
        activeIndex: null,
        formLists: [
            {
                label: this.$t('field.currencyPair'),
                type: 'select',
                key: 'underlying',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.transactionExchangeRate'),
                type: 'input',
                inputType: 'number',
                key: 'spotRate',
                placeholder: this.$t('field.pleaseInput'),
                isFixed: 6
            },
            {
                label: this.$t('field.tradingDirection'),
                type: 'select',
                key: 'buySell',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            }
        ],
        formLists2: [
            {
                label: this.$t('field.currencyPair'),
                type: 'select',
                key: 'underlying',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.strikePrice'),
                type: 'input',
                inputType: 'number',
                key: 'strike',
                placeholder: this.$t('field.pleaseInput'),
                isFixed: 6
            },
            {
                label: this.$t('field.tradingDirection'),
                type: 'select',
                key: 'buySell',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.deliveryMethods'),
                type: 'select',
                key: 'settlementMode',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            }
        ],
        formLists3: [
            {
                label: this.$t('menu.currency'),
                type: 'select',
                key: 'ccy',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.tradingDirection'),
                type: 'select',
                key: 'buySell',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            }
        ],
        formLists4: [
            {
                label: this.$t('field.tradingDirection'),
                type: 'select',
                key: 'buySell',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.bondCode'),
                type: 'select',
                key: 'bond',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.custodianInstitution'),
                type: 'select',
                key: 'bondsTrustee',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            }
        ],
        formLists6: [
            {
                label: this.$t('menu.currency'),
                type: 'select',
                key: 'ccy',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            }
        ],
        formLists8: [
            {
                label: this.$t('menu.contract'),
                type: 'select',
                key: 'contract',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.tradingDirection'),
                type: 'select',
                key: 'buySell',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            }
        ],
        formLists9: [
            {
                label: this.$t('field.currencyPair'),
                type: 'select',
                key: 'underlying',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            }
        ],
        formLists10: [
            {
                label: this.$t('field.currencyPair'),
                type: 'select',
                key: 'underlying',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.strikePrice'),
                type: 'input',
                inputType: 'number',
                key: 'strike',
                placeholder: this.$t('field.pleaseInput'),
                isFixed: 6
            },
            {
                label: this.$t('field.tradingDirection'),
                type: 'select',
                key: 'buySell',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.deliveryMethods'),
                type: 'select',
                key: 'settlementMode',
                multiple: true,
                collapseTags: true,
                placeholder: '',
                option: []
            },
            {
                label: this.$t('field.combinationNumber'),
                type: 'input',
                key: 'contractId',
                placeholder: this.$t('field.pleaseInput')
            }
        ]
    };
  },
  mounted() {
    this.init()
  },
  created() {
    document.addEventListener('click', this.handleClickOutside);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside);
  },
  methods: {
    async init () {
        await this.getOption()
        await this.queryList()
        this.reset()
    },
    async queryList () {
        let param = {
        "queryParam.moduleName": "pubProduct",
        "queryParam.keyWord":   undefined
        }
        let formData = new FormData();
        formData.append('reqJson', JSON.stringify(param));
        const res = await pubqueryList(formData)
        if ( res.data?.result?.datals) {
            this.filterArr = res.data.result.datals.map((item)=>{return item.code})
            // this.filterArr = ['FXSPOT','REPOOUT','BONDFWD']
            // console.log('this.filterArr',this.filterArr)
            this.obj.checkBox.forEach(item=>{
                item.checkLists = item.checkLists.filter(c=>this.filterArr.includes(c.value))
            })
        }
    },
    async getOption () {
        let formData = new FormData();
        formData.append('reqJson', '{"codifierGrpCodes": "static_pairs,OptionSettlementMode,static_currencies,static_trusteeList,static_contract,BuySellRcs"}');
        const res = await queryComboxData(formData)
        const result = res.data.result
        this.formLists[0].option = this.formLists2[0].option = this.formLists10[0].option = this.formLists9[0].option = result.pairs
        this.formLists2[3].option = this.formLists10[3].option = result.OptionSettlementMode
        this.formLists3[0].option = this.formLists6[0].option = result.currencies
        this.formLists4[2].option = result.trusteeList
        this.formLists8[0].option = result.contract
        this.formLists[2].option = this.formLists2[2].option = this.formLists10[2].option = this.formLists3[1].option = this.formLists4[0].option = this.formLists8[1].option = result.BuySellRcs
        // 债券检索
        let formData2 = new FormData();
        formData2.append('reqJson', '{"q":"","queryParam.pageLimit":"100"}');
        const res2 = await queryBondList(formData2)
        this.formLists4[1].option = res2.data.result.map(item=>{
            return {
                text: item.localName,
                value: item.code
            }
        })
    },
    includesArray (arr1, arr2) {
        return arr1.some(element => arr2.includes(element.value))
    },
    inputFocus (index) {
        this.activeIndex = index
        let list = this.searchForm[index].checkBox
        for(let i = list.length - 1; i > 0; i--) {
            if (!this.includesArray(list[i].checkLists, this.filterArr)) {
                this.searchForm[index].checkBox.splice(i,1)
            }
        } 
        this.$set(this.searchForm[index], 'panelShow', true)
    },
    handleIconClick (index) {
        this.activeIndex = index
        this.$set(this.searchForm[index], 'panelShow', true)
    },
    handleCheckAllChange (val, idx, index) {
        this.searchForm[idx].checkBox.forEach(item => {
            item.checkAll = false
            item.checked = []
        })
        this.searchForm[idx].checkBox[index].checkAll = val ? true : false
        this.searchForm[idx].checkBox[index].checked = val ? this.searchForm[idx].checkBox[index].checkLists.map(c=>c.value) : []
    },
    handleCheckedCitiesChange (val, idx, index) {
        this.searchForm[idx].checkBox.forEach(item => {
            item.checkAll = false
            item.checked = []
        })
        this.searchForm[idx].checkBox[index].checked = val
    },
    // 点击弹层以外关闭弹层
    handleClickOutside(e, flag=false) {
        if (flag) {
            this.formatJson()
        } else if (this.searchForm[this.activeIndex]?.panelShow && ((e.target.offsetParent.className.indexOf('l-input') === -1 || e.target.form) && e.target.className != 'el-checkbox__original' && e.target.className != 'el-checkbox__label' && e.target.className != 'el-checkbox__inner' && e.target.offsetParent.className != 'panel')) {
            this.formatJson()
        }
    },
    formatJson () {
        if (this.activeIndex !== null) {
            this.searchForm[this.activeIndex].panelShow = false
            let obj = this.searchForm[this.activeIndex].checkBox.filter(c=>c.checked.length > 0)[0]
            this.searchForm[this.activeIndex].type = obj?.checkType
            if (this.searchForm.filter(c=>c.type===obj?.checkType).length > 1) {
                this.searchForm[this.activeIndex].type = ''
                this.$alert(this.$t('field.thisCategoryAlreadyExists'), this.$t('field.warn'), {
                    confirmButtonText: this.$t('field.confirm')
                });
            } else {
                this.searchForm[this.activeIndex].input = obj?.checkLists.filter(e=>obj.checked.includes(e.value)).map(c=>c.label)
                this.searchForm[this.activeIndex].checked = obj?.checkLists.filter(e=>obj.checked.includes(e.value)).map(c=>c.value)
                this.searchForm[this.activeIndex].checkedBox = obj?.checkLists.filter(e=>obj.checked.includes(e.value))
            }
            switch (this.searchForm[this.activeIndex].type) {
                case '1':
                    this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists)))
                    break;
                case '2':
                    let arr = ["Straddle", "Strangle", "Butterfly", "CallSpread", "PutSpread", "Seagull", "RiskReversal", "ParticipatoryForward"]
                    if (arr.some(value => this.searchForm[this.activeIndex].checked.includes(value))) {
                        this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists10)))
                    } else {
                        this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists2)))
                    }
                    break;
                case '3':
                    this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists3)))
                    break;
                case '4':
                    this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists4)))
                    break;
                case '5':
                    this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists3)))
                    break;
                case '6':
                    this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists6)))
                    break;
                case '7':
                    this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists6)))
                    break;
                case '8':
                    this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists8)))
                    break;
                case '9':
                    this.$set(this.searchForm[this.activeIndex], 'formLists', JSON.parse(JSON.stringify(this.formLists9)))
                    break;
                default:
                    break;
            }
            let json = {}
            this.searchForm[this.activeIndex].formLists.forEach(item=>{
                if (item.type === 'select' && item.multiple) {
                    json[item.key] = []
                } else {
                    json[item.key] = ''
                }
            })
            this.$set(this.searchForm[this.activeIndex], 'form', json)
        }
    },
    addItem () {
        let status = true
        for(let i = 0; i < this.searchForm.length; i++) {
            if(!this.searchForm[i].input) {
                status = false
                break
            }
        }
        if (status) {
            this.searchForm.push(JSON.parse(JSON.stringify(this.obj)))
        }
    },
    delItem (index) {
        if (this.searchForm.length > 1) {
            this.searchForm.splice(index, 1)
        } else {
            this.searchForm.splice(index, 1)
            this.searchForm.push(JSON.parse(JSON.stringify(this.obj)))
        }
    },
    topSubmit () {
        return this.searchForm
    },
    reset () {
        this.searchForm = [JSON.parse(JSON.stringify(this.obj))]
    },
    inputBlur (e, item, index) {
        if (item.isFixed && e.target.value) {
            let num = 0
            if (item.key === 'spotRate' && e.target.value > 100000) {
                num = 100000
            } else if (item.key === 'spotRate' && e.target.value < -100000) {
                num = -100000
            } else if (item.key === 'strike' && e.target.value > 1000000000000000) {
                num = 1000000000000000
            } else if (item.key === 'strike' && e.target.value < -1000000000000000) {
                num = -1000000000000000
            } else {
                num = e.target.value
            }
            this.searchForm[index].form[item.key] = parseFloat(num).toFixed(item.isFixed)
        }
    }
  }
};
</script>

<style lang="scss" scoped>
.topSearch{
    padding: 20px;
    .ts-list{
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        position: relative;
        .leftBox{
            width: 300px;
            margin: 0;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .el-input{
                width: 200px;
            }
            &>i{
                cursor: pointer;
            }
        }
        .rightBox{
            margin-left: 50px;
            flex: 1;
            .el-select{
                width: 100%;
            }
        }
        .panel{
            position: absolute;
            left: 100px;
            top: 30px;
            z-index: 3;
            width: 500px;
            height: 400px;
            overflow: hidden;
            overflow-y: auto;
            background-color: var(--table-cell-striped-bg);
            border: 1px solid var(--scrollBar);
            .p-item{
                display: flex;
                align-items: center;
                border-bottom: 1px solid var(--scrollBar);
                &:last-child{
                    border: none;
                }
                &>.el-checkbox{
                    padding: 0 10px;
                }
                .el-checkbox-group{
                    flex: 1;
                    padding: 10px;
                    border-left: 1px solid var(--scrollBar);
                    .el-checkbox{
                        width: 30%;
                        margin-right: 3%;
                        margin-top: 10px;
                        &:nth-of-type(1),&:nth-of-type(2),&:nth-of-type(3) {
                            margin-top: 0;
                        }
                    }
                }
            }
        }
    }
}
</style>