<template>
    <div class="transaction">
        <h4>{{title}}</h4>
        <el-form class="t-form" ref="form" :model="form" label-width="100px">
            <el-row>
                <el-col :span="20">
                    <el-form-item v-for="(item, index) in form" :label="item.label" :key="item.key">
                        <el-select v-model="item.value1" placeholder="" @change="selectChange($event, index)">
                            <el-option v-for="inner in option" :label="inner.text" :value="inner.value"></el-option>
                        </el-select>
                        <el-select v-if="item.type === 'select'" :key="item.selectKey" v-model="item.value2" :multiple="item.multiple" :collapse-tags="item.collapseTags" filterable :placeholder="item.placeholder">
                            <el-option v-for="inner in item.option" :label="inner.text" :value="inner.value"></el-option>
                        </el-select>
                        <el-input v-else-if="item.type === 'input'" v-model="item.value2" :placeholder="item.placeholder" @change="inputChange(index)"></el-input>
                        <el-input v-else-if="item.type === 'custom'" v-model="item.value2" :placeholder="item.placeholder" @focus="inputFocus">
                            <i slot="suffix" class="el-input__icon el-icon-search" @click="handleIconClick"></i>
                        </el-input>
                        <span v-if="item.btn" @click="nowUser">{{item.btn}}</span>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-dialog
            :visible.sync="dialogVisible"
            width="600px"
            :before-close="handleClose">
            <span slot="title">
                <el-select v-model="dialogValue" filterable placeholder="" @change="dialogSelectChange">
                    <el-option v-for="inner in dialogOption" :label="inner.text" :value="inner.value"></el-option>
                </el-select>
            </span>
            <div class="d-box" :key="form[1]?.selectKey">
                <template v-if="dialogValue==='1'">
                    <!-- <el-input v-model="treeSearch" :placeholder="pleaseInput"/>
                    <transition>
                        <el-tree
                            ref="tree"
                            :data="treeData"
                            :props="defaultProps"
                            node-key="id"
                            show-checkbox
                            check-strictly
                            :filter-node-method="filterNode"
                            :render-content="renderContent"
                            @check-change="handleCheckChange">
                        </el-tree>
                    </transition> -->
                    <div class="folder">
                        <el-select v-model="treeValue" :multiple="form[1]?.multiple" :collapse-tags="form[1]?.collapseTags" filterable :placeholder="pleaseSelect">
                             <el-option v-for="inner in treeData" :label="inner.text" :value="inner.value"></el-option>
                         </el-select> 
                     </div>
                </template>
                <template v-else>
                    <div class="folder">
                       <el-select v-model="folderValue" :multiple="form[1]?.multiple" :collapse-tags="form[1]?.collapseTags" filterable :placeholder="pleaseSelect">
                            <el-option v-for="inner in folderOption" :label="inner.text" :value="inner.value"></el-option>
                        </el-select> 
                    </div>
                </template>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="btn" @click="dialogVisible=false">{{this.$t('field.cancel')}}</el-button>
                <el-button class="btn" type="primary" @click="dialogSubmit">{{this.$t('field.confirm')}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { queryComboxData, queryCptyPage, queryFolderQueryAuthList } from '../../../../api/dcsApi.js';
export default {
  name: 'transaction',
  data() {
    return {
        title: this.$t('field.transaction'),
        form: [],
        defaultForm: [
            {
                label: this.$t('menu.counterparty'),
                type: 'select',
                key: 'cpty',
                value1: 'EQ',
                value2: [],
                placeholder: '',
                option: [],
                multiple: false,
                collapseTags: false,
                selectKey: 1
            },
            {
                label: this.$t('field.folderGroup'),
                type: 'custom',
                key: 'folder',
                value1: 'EQ',
                value2: '',
                id: '',
                placeholder: '',
                multiple: false,
                collapseTags: false,
                selectKey: 1
            },
            {
                label: this.$t('field.operatingUsers'),
                type: 'input',
                key: 'takerId',
                value1: 'EQ',
                value2: '',
                placeholder: '',
                btn: this.$t('field.currentUser')
            },
            {
                label: this.$t('field.salesman'),
                type: 'input',
                key: 'ext4',
                value1: 'EQ',
                value2: '',
                placeholder: this.$t('field.pleaseInput')
            },
            {
                label: this.$t('field.transactionStatus'),
                type: 'select',
                key: 'dealStatus',
                value1: 'EQ',
                value2: [],
                placeholder: '',
                option: [],
                multiple: false,
                collapseTags: false,
                selectKey: 1
            },
            {
                label: this.$t('field.natureOfTransaction'),
                type: 'select',
                key: 'dealFlag',
                value1: 'EQ',
                value2: [],
                placeholder: '',
                option: [],
                multiple: false,
                collapseTags: false,
                selectKey: 1
            },
            {
                label: this.$t('field.transactionPurpose'),
                type: 'input',
                key: 'ext20',
                value1: 'EQ',
                value2: '',
                placeholder: ''
            },
            {
                label: this.$t('field.sourceOfTransaction'),
                type: 'input',
                key: 'sourceName',
                value1: 'EQ',
                value2: '',
                placeholder: ''
            }
        ],
        option: [
            {
                text: '=',
                value: 'EQ'
            },
            {
                text: '!=',
                value: 'NQ'
            },
            {
                text: this.$t('field.contain'),
                value: 'IN'
            },
            {
                text: this.$t('field.notContain'),
                value: 'NOT IN'
            }
        ],
        dialogVisible: false,
        dialogValue: '1',
        dialogOption: [
            {
                text: this.$t('field.accountSearch'),
                value: '1'
            },
            {
                text: this.$t('field.accountGroupSearch'),
                value: '2'
            }
        ],
        treeSearch: '',
        defaultProps: {
          label: 'id',
          children: 'children'
        },
        treeValue: '',
        treeData: [],
        folderValue: [],
        folderOption: [],
        pleaseInput: this.$t('field.pleaseInput'),
        pleaseSelect: this.$t('field.pleaseSelect')
    };
  },
  watch: {
    treeSearch (val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.init()
  },
  mounted() {
  },
  methods: {
    async init () {
        await this.getOption()
        this.reset()
    },
    async getOption () {
        // 通用
        let formData = new FormData();
        formData.append('reqJson', '{"codifierGrpCodes": "DealFlagRcs,dealStatusList,folderTreeAuthWithGrp"}');
        const res = await queryComboxData(formData)
        this.defaultForm[4].option = res.data.result.dealStatusList
        this.defaultForm[5].option = res.data.result.DealFlagRcs
        // this.treeData = res.data.result.folderTreeAuthWithGrp.filter(c=>c.id.indexOf('E@@') !== -1) // 账户
        this.folderOption = res.data.result.folderTreeAuthWithGrp.filter(c=>c.id.indexOf('E@@') == -1) // 账户组

        // 交易对手
        let json = {
            "q":"",
            "queryParam.loginId": Eui.Share.get("loginId"),
            "queryParam.bankId": Eui.Share.get("bankId")
        }
        let formData2 = new FormData();
        formData2.append('reqJson', JSON.stringify(json));
        const res2 = await queryCptyPage(formData2)
        this.defaultForm[0].option = res2.data.result.datals.map(item=>{
            return {
                text: item.localName,
                value: item.code
            }
        })

        // 账户/账户组
        let json2 = {
            "q":"",
            "loginId": Eui.Share.get("loginId"),
            "bankId": Eui.Share.get("bankId")
        }
        let formData3 = new FormData();
        formData3.append('reqJson', JSON.stringify(json2));
        const res3 = await queryFolderQueryAuthList(formData3)
        this.treeData = res3.data.result.map(item=>{
            return {
                text: item.localName,
                value: 'F@@' + item.code
            }
        })
    },
    inputFocus () {
        this.dialogVisible = true
        // this.dialogValue = '1'
    },
    handleIconClick () {
        this.dialogVisible = true
    },
    filterNode (value, data) { // 筛选树
      if (!value) return true
      if (data.id) {
        return data.id.indexOf(value) !== -1
      } else {
        return false
      }
    },
    renderContent(h, { node, data, store }) {
        return (
          <span class="custom-tree-node">
            <span>{data.id.substr(3)}</span>
            <span>{data.text}</span>
          </span>);
    },
    dialogSelectChange () {
        this.treeValue = []
        this.folderValue = []
    },
    handleCheckChange(data, checked, node) {
        if (checked) {
            // 当节点被选中时，取消其他所有节点的选中状态，除了当前节点自身。
            this.$refs.tree.setCheckedKeys([]); // 清空所有选中项，但不包括当前节点）
            this.$refs.tree.setChecked(data, true, true); // 设置当前节点为选中状态，第三个参数 true 表示不触发回调函数
        }
    },
    dialogSubmit () {
        if (this.dialogValue === '1') {
            // this.form[1].value2 = this.$refs.tree.getCheckedNodes()[0]?.text || ''
            // this.form[1].id = this.$refs.tree.getCheckedNodes()[0]?.id || ''
            // this.$refs.tree.setCheckedKeys([])
            // for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
            //     // 遍历 el-tree 的每个节点，将节点的 expanded 属性设为 true 或 false
            //     this.$refs.tree.store._getAllNodes()[i].expanded = false
            // }

            let arr = []
            this.treeData.forEach(item => {
                if (this.form[1].multiple) {
                    this.treeValue.forEach(e=>{
                        if(e === item.value) {
                            arr.push(item.text) 
                        }
                    })
                } else {
                    if (this.treeValue === item.value) {
                        arr.push(item.text)
                    }
                }
            });
            this.form[1].value2 = arr
            this.form[1].id = this.treeValue
        } else {
            let arr = []
            this.folderOption.forEach(item => {
                if (this.form[1].multiple) {
                    this.folderValue.forEach(e=>{
                        if(e === item.value) {
                            arr.push(item.text) 
                        }
                    })
                } else {
                    if (this.folderValue === item.value) {
                        arr.push(item.text)
                    }
                }
            });
            this.form[1].value2 = arr
            this.form[1].id = this.folderValue
        }
        this.dialogVisible = false
        // if (this.form[1].id.length > 0) {
        //     this.dialogVisible = false
        // }
    },
    // 切换左侧相等、包含，清空右侧筛选条件
    selectChange (e, index) {
        this.form[index].selectKey++
        if (e === 'EQ' || e === 'NQ') {
            this.$set(this.form[index], 'value2', '')
            this.form[index].multiple = false
            this.form[index].collapseTags = false
        } else {
            this.$set(this.form[index], 'value2', [])
            this.form[index].multiple = true
            this.form[index].collapseTags = true
        }
    },
    // 当前用户
    nowUser () {
        this.form[2].value2 = Eui.Share.get('loginId')
        this.form[2].isUser = true
    },
    inputChange (index) {
        if (index === 2) {
            this.form[2].isUser = false 
        }
    },
    submit () {
        return this.form
    },
    reset () {
        this.form = JSON.parse(JSON.stringify(this.defaultForm))
    }
        
  }
};
</script>

<style lang="scss" scoped>
    .transaction{
        width: 100%;
        h4{
            padding: 6px 20px;
            margin: 0;
            background-color: var(--select-item-hover-bg);
        }
        .t-form{
            padding: 20px;
            .el-form-item__content{
                .el-select{
                    &:first-child{
                        width: 20%;
                        margin-right: 10px;
                    }
                }
                div{
                    &:nth-of-type(2){
                        flex: 1;
                    }
                }
                span{
                    position: absolute;
                    color: var(--blue-80);
                    right: -70px;
                    cursor: pointer;
                }
            }
        }
    }
</style>
<style lang="scss">
    .transaction{
        width: 100%;
        .t-form{
            .el-form-item__content{
                display: flex;
                justify-content: space-between;
            }
        }
        .el-dialog__header{
            height: 50px;
        }
        .el-dialog .el-dialog__body{
            .el-tree{
                max-height: 400px;
                margin-top: 20px;
                overflow: hidden;
                overflow-y: auto;
            }
            .folder{
                .el-select{
                    width: 100%;
                }
            }
        }
        .custom-tree-node {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 14px;
            padding-right: 8px;
            span:last-child {
                color: var(--blue-80);
            }
        }
    }
</style>