<template>
    <div v-bind:class="{'ap-grid-column-search-table': true,
                        'ap-grid-column-change': isChange(rowData.changeArr),
                        'ap-grid-column-error': showRuleMsg,}">
        <el-input placeholder="请选择" :value="rowData[opts.prop]" :disabled="true">
            <el-button slot="append" icon="el-icon-search" @click="searchPickerClick"></el-button>
        </el-input>
        <el-dialog :title="opts.searchPickerTitle"
                   :visible.sync="dialogVisible"
                   :width="opts.searchPickerWidth"
                   :append-to-body="true">


            <div class="flex">
                <div class="search-pick-left">
                    <div>
                        <el-input placeholder="关键字过滤" v-model="filterText"></el-input>
                    </div>

                    <div v-loading="loadingTreeFlag" v-bind:style="{height: opts.searchPickerHeight}"
                         class="ap-grid-column-search-tree-ctn">
                        <el-tree
                                class="filter-tree"
                                ref="searchPickerRef"
                                :node-key="opts.searchPickerKey == null? 'fdId': opts.searchPickerKey.idKey"
                                :data="treeData"
                                :props="{children: 'children', label: opts.searchPickerKey.labelKey}"
                                :default-expand-all="opts.searchPickerExpandAll"
                                :check-on-click-node="true"
                                :highlight-current="true"
                                :expand-on-click-node="false"
                                :check-strictly="true"
                                :filter-node-method="filterNode"
                                @node-click="nodeClickEvent">
                        </el-tree>
                    </div>
                </div>


                <div class="flex-1 search-pick-right">
                    <div>
                        <el-input placeholder="关键字过滤" v-model="filterTextMain"></el-input>
                    </div>

                    <div v-loading="loadingTreeFlagMain" v-bind:style="{height: opts.searchPickerHeight}"
                         class="ap-grid-column-search-tree-ctn">
                        <el-tree
                                class="filter-tree"
                                ref="searchPickerMainRef"
                                :node-key="opts.searchPickerKeyMain == null? 'fdId': opts.searchPickerKeyMain.idKey"
                                :data="treeDataMain"
                                :props="{children: 'children', label: opts.searchPickerKeyMain.labelKey}"
                                :default-expand-all="true"
                                show-checkbox
                                :check-on-click-node="true"
                                :highlight-current="true"
                                :expand-on-click-node="false"
                                :check-strictly="true"
                                :filter-node-method="filterNodeMain"
                                @check="checkEventMain">
                        </el-tree>
                    </div>
                </div>
            </div>


            <span slot="footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="warning" @click="searchPickerClear">清 空</el-button>
                <el-button type="primary" @click="searchPickerConfirm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- rule校验 -->
        <div v-html="ruleMsg" v-show="showRuleMsg" class="ap-grid-column-error-msg"></div>
    </div>
</template>

<script>
    import {handleDefaultParams} from 'ap-util/util/ObjectUtil'
    import {convertToTreeData} from 'ap-util/util/DataUtil'
    import ApTableColBase from './ApTableColBase'

    export default {
        name: "ApTableSearchPicker",
        extends: ApTableColBase,
        data() {
            return {
                opts: {},
                dialogVisible: false,
                loadingTreeFlag: false,
                isFirstLoad: true,
                filterText: '',
                treeData: [],
                loadingTreeFlagMain: false,
                filterTextMain: '',
                treeDataMain: [],
            }
        },
        watch: {
            filterText(val) {
                this.$refs.searchPickerRef.filter(val);
            },
            filterTextMain(val) {
                this.$refs.searchPickerMainRef.filter(val);
            }
        },
        created() {
            // 初始化组件前修改默认参数
            this.opts = handleDefaultParams(this.colOptions, {
                searchPickerTitle: '查找',
                searchPickerWidth: '800px',
                searchPickerHeight: '400px',
                searchPickerKey: {idKey: "fdId", parentKey: "fdParentId", labelKey: "fdName"},
                searchPickerMethod: 'post',
                searchPickerLoadTime: "init", // init、edit、click
                searchPickerExpandAll: true,
                searchPickerKeyMain: {idKey: "fdId", parentKey: "fdParentId", labelKey: "fdName"},
                searchPickerMethodMain: 'post',
                searchPickerSelectMultipleMain: false,
                searchPickerBeforeClick() {
                    return true;
                },
                searchPickerConfirm() {
                    return true
                },
                searchPickerClear() {
                    return true
                },
            });
        },
        mounted: function () {
            this.$nextTick(function () {
                this.loadTreeDataInit();
            })
        },
        methods: {
            // 查询点击
            searchPickerClick() {
                if (!this.opts.searchPickerBeforeClick(this.rowData)) {
                    return;
                }
                this.dialogVisible = true;
                if (this.opts.searchPickerLoadTime == "click") {
                    this.loadTreeDataNow();
                }
            },
            // 树：初始化时加载
            loadTreeDataInit() {
                if (this.opts.searchPickerLoadTime == "init") {
                    if (this.colData == null || this.colData[this.opts.prop] == null) {
                        return;
                    }
                    this.loadingTreeFlag = true;
                    this.setTreeData(this.colData[this.opts.prop]);
                    this.loadingTreeFlag = false;
                } else if (this.opts.searchPickerLoadTime == "edit") {
                    if (this.isFirstLoad) {
                        this.loadTreeDataNow();
                        this.isFirstLoad = false;
                    }
                }
            },
            // 树：加载数据
            loadTreeDataNow() {
                let params = {};
                let searchPickerParams = this.opts.searchPickerParams;
                if (typeof searchPickerParams === 'function') {
                    params = searchPickerParams(this.rowData, this.opts);
                } else if (searchPickerParams != null) {
                    params = searchPickerParams;
                }
                this.loadingTreeFlag = true;
                this.$request({
                    url: this.opts.searchPickerUrl,
                    method: this.opts.searchPickerMethod,
                    data: params
                }).then(response => {
                    this.setTreeData(response.data);
                }).finally(() => {
                    this.loadingTreeFlag = false;
                })
            },
            // 设定tree数据
            setTreeData(data) {
                this.treeData = convertToTreeData(data, {
                    idKey: this.opts.searchPickerKey.idKey,
                    parentKey: this.opts.searchPickerKey.parentKey,
                    childrenKey: "children",
                });
            },
            // 树：过滤节点
            filterNode(value, data) {
                if (!value) return true;
                return data[this.opts.searchPickerKey.labelKey].indexOf(value) !== -1;
            },
            // 树：过滤节点
            filterNodeMain(value, data) {
                if (!value) return true;
                return data[this.opts.searchPickerKeyMain.labelKey].indexOf(value) !== -1;
            },
            // 选择事件
            nodeClickEvent(data, node, comp) {
                let params = {};
                // 自定义请求参数
                let searchPickerParamsMain = this.opts.searchPickerParamsMain;
                if (typeof searchPickerParamsMain === 'function') {
                    params = searchPickerParamsMain(this.rowData, this.opts, data);
                } else if (searchPickerParamsMain != null) {
                    params = searchPickerParamsMain;
                } else {
                    params = data;
                }
                this.loadingTreeFlagMain = true;
                this.$request({
                    url: this.opts.searchPickerUrlMain,
                    method: this.opts.searchPickerMethodMain,
                    data: params
                }).then(response => {
                    this.treeDataMain = convertToTreeData(response.data, {
                        idKey: this.opts.searchPickerKey.idKey,
                        parentKey: this.opts.searchPickerKey.parentKey,
                        childrenKey: "children",
                    });
                }).finally(() => {
                    this.loadingTreeFlagMain = false;
                })
            },
            // 树：勾选事件
            checkEventMain(data, node, comp) {
                if (this.opts.searchPickerSelectMultipleMain) {
                    return;
                }
                // 单选处理
                let checkKeys = this.$refs.searchPickerMainRef.getCheckedKeys(false);
                for (let i = 0; i < checkKeys.length; i++) {
                    this.$refs.searchPickerMainRef.setChecked(checkKeys[i], false, false)
                }
                this.$refs.searchPickerMainRef.setChecked(data, true, false)
            },
            // 回调：清单
            searchPickerClear() {
                let isOk = this.opts.searchPickerClear(this.rowData);
                if (isOk) {
                    // 手动触发修改事件
                    this.changeEvent(this.rowData)
                    this.dialogVisible = false;
                }
            },
            // 回调：确认
            searchPickerConfirm() {
                let checkedNodes = this.$refs.searchPickerMainRef.getCheckedNodes(false, false)
                let isOk = this.opts.searchPickerConfirm(this.rowData, checkedNodes);
                if (isOk) {
                    // 手动触发修改事件
                    this.changeEvent(this.rowData)
                    this.dialogVisible = false;
                }
            },
        }
    }
</script>

<style scoped>
    .ap-grid-column-search-tree-ctn {
        overflow: auto;
    }

    .search-pick-left {
        width: 40%;
        border-right: 1px solid #E2E7EF;
        padding-right: 10px;
    }

    .search-pick-right {
        padding-left: 10px;
    }

    .ap-grid-column-search-table /deep/ .el-input__inner {
        padding: 0px 2px;
        border-radius: 4px 0px 0px 4px;
    }

    .ap-grid-column-error /deep/ .el-input__inner {
        border: 1px solid red;
    }

</style>
