<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="searchTreeClick"></el-button>
        </el-input>
        <el-dialog :title="opts.searchTreeTitle"
                   :visible.sync="dialogVisible"
                   :width="opts.searchTreeWidth"
                   :append-to-body="true">
            <div>
                <el-input placeholder="关键字过滤" v-model="filterText"></el-input>
            </div>
            <div v-loading="loadingTreeFlag" v-bind:style="{height: opts.searchTreeHeight}"
                 class="ap-grid-column-search-tree-ctn">
                <el-tree
                        class="filter-tree"
                        ref="searchTreeRef"
                        :node-key="opts.searchTreeKey == null? 'fdId': opts.searchTreeKey.idKey"
                        :default-checked-keys="defaultCheckedKeys"
                        :data="treeData"
                        :props="{children: 'children', label: opts.searchTreeKey.labelKey}"
                        :default-expand-all="opts.searchTreeExpandAll"
                        show-checkbox
                        :check-on-click-node="true"
                        :highlight-current="true"
                        :expand-on-click-node="false"
                        :check-strictly="opts.searchTreeCheckStrictly"
                        :filter-node-method="filterNode"
                        @check="checkEvent">
                </el-tree>
            </div>

            <span slot="footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="warning" @click="searchTreeClear">清 空</el-button>
                <el-button type="primary" @click="searchTreeConfirm">确 定</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: "ApTableSearchTree",
        extends: ApTableColBase,
        data() {
            return {
                opts: {},
                dialogVisible: false,
                loadingTreeFlag: false,
                isFirstLoad: true,
                filterText: '',
                treeData: [],
                defaultCheckedKeys:[]
            }
        },
        watch: {
            filterText(val) {
                this.$refs.searchTreeRef.filter(val);
            }
        },
        created() {
            // 初始化组件前修改默认参数
            this.opts = handleDefaultParams(this.colOptions, {
                searchTreeTitle: '查找',
                searchTreeWidth: '400px',
                searchTreeHeight: '400px',
                searchTreeKey: {idKey: "fdId", parentKey: "fdParentId", labelKey: "fdName"},
                searchTreeMethod: 'post',
                searchTreeCheckStrictly: true,
                searchTreeLoadTime: "init", // init、edit、click
                searchTreeSelectMultiple: false,
                searchTreeExpandAll: true,
                searchTreeDefaultCheckedKeys: [],
                searchTreeBeforeClick() {
                    return true;
                },
                searchTreeConfirm() {
                    return true;
                },
                searchTreeClear() {
                    return true;
                },
            });
        },
        mounted: function () {
            this.$nextTick(function () {
                this.loadTreeDataInit();
            })
        },
        methods: {
            searchTreeClick() {
                if (!this.opts.searchTreeBeforeClick(this.rowData)) {
                    return;
                }
                this.dialogVisible = true;
                if (this.opts.searchTreeLoadTime == "click") {
                    this.loadTreeDataNow();
                }
            },
            // 树：初始化时加载
            loadTreeDataInit() {
                if (this.opts.searchTreeLoadTime == "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.searchTreeLoadTime == "edit") {
                    if (this.isFirstLoad) {
                        this.loadTreeDataNow();
                        this.isFirstLoad = false;
                    }
                }
            },
            // 树：加载数据
            loadTreeDataNow() {
                let params = {};
                let searchTreeParams = this.opts.searchTreeParams;
                if (typeof searchTreeParams === 'function') {
                    params = searchTreeParams(null, this.opts);
                } else if (searchTreeParams != null) {
                    params = searchTreeParams;
                }
                this.loadingTreeFlag = true;
                this.$request({
                    url:  this.opts.searchTreeUrl,
                    method:  this.opts.searchTreeMethod,
                    data: params
                }).then(response => {
                    this.setTreeData(response.data);
                }).finally(() => {
                    this.loadingTreeFlag = false;
                })
            },
            getDefaultCheckedKeys(rowData){
                let res = [];
                let defaultCheckedKeys = this.opts.searchTreeDefaultCheckedKeys;
                if (typeof defaultCheckedKeys === 'function') {
                    res = defaultCheckedKeys(rowData);
                } else if (defaultCheckedKeys != null) {
                    res = defaultCheckedKeys;
                }
                return res;
            },
            // 设定tree数据
            setTreeData(data) {
                this.treeData = convertToTreeData(data, {
                    idKey: this.opts.searchTreeKey.idKey,
                    parentKey: this.opts.searchTreeKey.parentKey,
                    childrenKey: "children",
                });
                this.defaultCheckedKeys = this.getDefaultCheckedKeys(this.rowData);
            },
            // 树：过滤节点
            filterNode(value, data) {
                if (!value) return true;
                return data[this.opts.searchTreeKey.labelKey].indexOf(value) !== -1;
            },
            // 树：勾选事件
            checkEvent(data, node, comp) {
                if (this.opts.searchTreeSelectMultiple) {
                    return;
                }
                // 单选处理
                let checkKeys = this.$refs.searchTreeRef.getCheckedKeys(false);
                for (let i = 0; i < checkKeys.length; i++) {
                    this.$refs.searchTreeRef.setChecked(checkKeys[i], false, false)
                }
                this.$refs.searchTreeRef.setChecked(data, true, false)
            },
            // 回调：清单
            searchTreeClear() {
                let isOk = this.opts.searchTreeClear(this.rowData);
                if (isOk) {
                    // 手动触发修改事件
                    this.changeEvent(this.rowData)
                    this.dialogVisible = false;
                }
            },
            // 回调：确认
            searchTreeConfirm() {
                let checkedNodes = this.$refs.searchTreeRef.getCheckedNodes(false, false)
                let isOk = this.opts.searchTreeConfirm(this.rowData, checkedNodes);
                if (isOk) {
                    // 手动触发修改事件
                    this.changeEvent(this.rowData)
                    this.dialogVisible = false;
                }
            },
        }
    }
</script>

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

    .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>
