<template>
    <el-dialog
        :title="treeSet.isSelectPerson ? '选择人员' : '选择部门'"
        width="660px"
        :visible.sync="treeSet.dialogVisible">
        <div class="transfer-area">
            <div class="select-area t-a-select">
                <p class="title">选择</p>
                <div class="tree-div">
                    <div class="input-container">
                        <el-input v-model="searchText" placeholder="请输入内容"></el-input>
                    </div>
                    <div class="select-div"  style="width: 100%;">
                        <el-select v-model="brandSelection" placeholder="请选择品牌" @change="selectBrand" style="width: 100%;margin-top:20px;">
                            <el-option
                                v-for="(item, index) in brands"
                                :key="item.id"
                                :label="item.label"
                                :value="index">
                                {{item.label}}
                            </el-option>
                        </el-select>
                    </div>
                    <el-tree
                        class="search-menu"
                        node-key="id"
                        ref="tree"
                        :check-strictly="true"
                        :default-expanded-keys="defaultOpen"
                        :data="menuData"
                        show-checkbox
                        :highlight-current="true"
                        :expand-on-click-node="false"
                        icon-class="open-child"
                        :props="myProps"
                        :filter-node-method="filterNode"
                        @check-change="getCurrentNode"
                        @node-expand="nodeOpen"
                        @node-collapse="nodeClose"
                        @node-click="handleNodeClick">
                        <span class="custom-tree-node" :class="data.disableOpen ? 'disable-open' : ''" slot-scope="{ node, data }">
                            <span>{{ data.label }}</span>
                            <span class="open-btn" v-if="data.childrens">
                                <el-button @click="nodeOpen(data, node)" :disabled="data.disableOpen" type="text" size="small">下级</el-button>
                            </span>
                        </span>
                    </el-tree>
                </div>
            </div>
            <div class="selected-area t-a-select">
                <p class="title">
                    已选
                    <a class="J_del-all" @click="delSelected('empty')">全部清除</a>
                </p>
                <div class="tree-div">
                    <ul class="selected-list">
                        <template v-if="selectedList.length > 0">
                            <li v-for="li in selectedList" class="list group-li" :class="li.groupId ? 'group-li' : 'person-li'" :key="li.id+li.label">
                                <div class="label">
                                    <i class="iconfont" :class="li.groupId ? 'icon-tongshi-zuzhijiagou' : 'icon-chengyuan'"></i>{{li.label}}
                                </div>
                                <div class="close-btn" @click="delSelected(li)">
                                    <i class="el-icon-close"></i>
                                </div>
                            </li>
                        </template>
                    </ul>
                </div>
            </div>
        </div>
        <div class="btn-box t-rt p-b-10">
            <el-button @click="treeSet.dialogVisible = false;">取消</el-button>
            <el-button type="primary" @click="submitSelected">确定</el-button>
        </div>
     </el-dialog>
</template>
<script>
    import { formatTreeData, deepCopy } from '@/utils/index';
    import { getRequest, postRequest, postJsonRequest } from '@/api/api';
    export default {
        name: "vue-select-employee",
        props: {
            treeSet: {
                type: Object,
                default() {
                    return {
                        isSelectPerson: true,
                        dialogVisible: false,
                        isSingle: false // 是否单选
                    }
                }
            },
            selectType: {
                type: String,
                default: "all" // all 所有都可选, person 只选人， store 只选门店, group 只选分组, group-store 选门店/分组
            },
            forbidenList: {
                type: Array,
                default() {
                    return [];
                }
            },
            visibleNodes: {
                type: [Array, String], // 设置仅可见的节点，如果不传则默认展示所有
                default() {
                    return "";
                }
            },
            defaultList: { // 回显数据
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                searchText: "",
                myProps: {
                    children: 'childrens',
                    label: 'label',
                    disabled: "disabled"
                },
                menuData: [],
                menusObj: {},
                defaultOpen: [],
                selectedList: [],
                brandSelection: 0,
                brands: [],
                hasOpened: false,
                firstRender: true
            };
        },
        methods: {
            /**
             * 获取分组架构
             */
            getGroupData() {
                let _this = this;
                let params = {
                    isStoreGroup: 1
                };
                getRequest("/haoban-manage-web/dept/deptList", params)
                .then(res => {
                    console.log(res, "storegroup");
                    let treeData = [];
                    if (res.data.errorCode == 1) {
                        treeData = res.data.result || [];
                    }
                    _this.formatGroupData(treeData);
                })
                .catch(e => {
                    console.log(e, "error");
                });
            },
            formatGroupData(data) {
                let copyData = data;
                let _this = this;
                let selType = _this.selectType;
                let fbdList = this.forbidenList;
                this.menusObj = {};
                data.forEach(group => {
                    group.label = group.name || "";
                    group.id = group.groupId || "";
                    group.disableOpen = false;
                    let isForbiden = !!(fbdList.indexOf(group.id) > -1)
                    group.disabled = (group.hasPression != 1 || selType == "person" || selType == "store" || isForbiden);
                    let arr = [];
                    copyData.forEach(cG => {
                        cG.disableOpen = false;
                        cG.disabled = (cG.hasPression != 1 || selType == "person" || selType == "store" || isForbiden);
                        if (cG.parentId == group.groupId) {
                            arr.push(cG);
                        }
                    });
                    if (arr.length > 0) {
                        group.childrens = arr 
                    } else if (group.level != 0 && _this.selectType != "group"){
                        group.childrens = [{label: ""}];
                        group.isLast = true;
                    }
                    if (group.level == 0) {
                        group.disabled = ((group.childrens && group.childrens.length > 0) || (group.hasPression != 1 || selType == "person" || selType == "store" || isForbiden));
                        group.hasLoad = true;
                        _this.brands.push(group);
                        if (group.childrens) _this.defaultOpen.push(group.id);
                    }
                    _this.menusObj[group.id] = group;
                });
                _this.menuData = [_this.brands[0]];
                if (selType != "group") {
                    this.getStoreList(_this.menuData[0])
                }
            },
            /**
             * 树形菜单选择
             */
            handleNodeClick(obj, node) {
                this.$emit("handleTreeSelection", obj, node, 'node');
            },
            /**
             * 获取当前复选框状态改变的节点，如果被选中，将禁用展开
             */
            getCurrentNode(data, ifChecked, son) {
                data.disableOpen = ifChecked;
                this.selectedList = this.$refs.tree.getCheckedNodes();
                if (this.treeSet.isSingle && this.selectedList.length > 1) {
                    let index = this.selectedList.indexOf(data);
                    this.selectedList.splice(1 - index, 1);
                    this.$refs.tree.setCheckedNodes(this.selectedList);
                }
            },
            /**
             * 节点展开时，禁用复选框
             */
            nodeOpen(data, self) {
                data.disabled = true;
                if (!data.hasLoad && this.selectType != "group") {
                    this.getStoreList(data);
                    data.hasLoad = true; // 标记为已经请求过子分组数据，下次展开不再请求
                }
            },
            getStoreList(parent) {
                let ths = this;
                let params = {
                    storeGroupId: parent.groupId,
                    showChild: 0,
                    pageNumber: 1,
                    pageSize: 1000000000,
                    showType: 2
                };
                getRequest("/haoban-manage-web/store/findSimplePage", params)
                .then(res => {
                    let storeList = [];
                    if (res.data.errorCode == 1) {
                        storeList = res.data.result.list == null ? [] : res.data.result.list;
                        ths.formatStoreList(storeList, parent);
                        if (ths.$refs.tree) {
                            ths.renderDefault();
                        }
                    }
                })
                .catch(e => {
                    console.log(e, "error");
                });
            },
            formatStoreList(list, parent) {
                let type = this.selectType;
                list.forEach(li => {
                    li.id = li.storeId;
                    li.label = li.storeName;
                    li.hasLoad = true;
                    li.disabled = !!(type == "person");
                    if (li.clerks.length && (type == "all" || type == "person")) {
                        li.clerks.forEach(clerks => {
                            clerks.label = clerks.name;
                            clerks.id = clerks.employeeClerkId;
                        });
                        li.childrens = li.clerks;
                    }
                });
                if (parent.isLast) {
                    parent.childrens = list;
                } else {
                    let arr = !!parent.childrens ? parent.childrens : [];
                    arr = arr.concat(list);
                    parent.childrens = JSON.parse(JSON.stringify(arr));
                }
                if (parent.childrens.length > 0 && this.firstRender) {
                    this.firstRender = false;
                    this.defaultOpen.push(parent.id);
                }
                // this.renderDefault();
            },
            /**
             * 节点关闭时，取消复选框的禁用
             */
            nodeClose(data, node, self) {
                let selType = this.selectType;
                if (data.storeId) {
                    data.disabled = (selType == "person");
                } else {
                    let fbdList = this.forbidenList;
                    let isForbiden = fbdList.indexOf(data.id) > -1;
                    data.disabled = (data.hasPression != 1 || isForbiden || selType == "store" || selType == "person");
                }
            },
            /**
             * 关键词搜索
             */
            filterNode(value, data) {
                if (!value) return true;
                return (data.label.indexOf(value) !== -1 || (data.phoneNumber || "").indexOf(value) !== -1);
            },
            /**
             * 删除已选项
             */
            delSelected(obj) {
                if (obj == 'empty') {
                    this.$refs.tree.setCheckedKeys(this.selectedList, false);
                    this.selectedList = this.$refs.tree.getCheckedNodes();
                } else {
                    let index = this.selectedList.indexOf(obj);
                    this.selectedList.splice(index, 1);
                    this.$refs.tree.setCheckedNodes(this.selectedList);
                }
            },
            /**
             * 外抛已选的数据
             */
            submitSelected() {
                this.$emit("handleSelectedList", this.selectedList);
                this.treeSet.dialogVisible = false;
            },
            /**
             * 选择品牌
             */
            selectBrand(val) {
                this.menuData = [this.brands[val]];
                this.brands[val].hasLoad = true;
                this.firstRender = true;
                if (this.selectType != "group") {
                    this.getStoreList(this.menuData[0]);
                }
                this.renderDefault();
            },
            /**
             * 渲染回显数据
             */
            renderDefault() {
                this.$nextTick(() => {
                    let list = this.defaultList;
                    this.selectedList = list;
                    console.log(this.selectedList);
                    this.$refs.tree.setCheckedNodes(list);
                    list.forEach(li => {
                        if (li.employeeClerkId) {
                            this.defaultOpen = [li.storeId];
                        } else if (!li.storeId && !li.employeeClerkId) {
                            console.log(this.menusObj[li.id]);
                            this.defaultOpen.push(this.menusObj[li.id].parentId);
                        }
                    });
                });
            }
        },
        beforeMount() {
            this.getGroupData();
        },
        mounted() {
            console.log(this.$refs.tree, "this.$refs.tree");
                        // this.renderDefault();
        },
        watch: {
            searchText(newK, old) {
                this.$refs.tree.filter(newK);
            },
            defaultList: {
        　　　　handler(newValue, oldValue) {
        　　　　　　console.log(newValue)
                    if (!!this.$refs.tree) {
                        this.renderDefault();
                    }
        　　　　},
        　　　　deep: true
        　　},
            treeSet: {
                handler(newValue, oldValue) {
                    if (newValue.dialogVisible && !this.hasOpened) {
                        this.hasOpened = true;
                        this.renderDefault();
                    }
                },
                deep: true
            }
        }
    };
</script>
<style lang="scss">
.p-b-10 {
    padding-bottom: 10px;
}
.transfer-area {
    display: flex;
    margin-bottom: 40px;
    .t-a-select {
        width:300px;
        height:415px;
        background:rgba(255,255,255,1);
        border:1px solid rgba(220,223,230,1);
        border-radius:4px;
        overflow: hidden;
        &:first-child {
            margin-right: 20px;
        }
        >.title {
            width:100%;
            height:42px;
            line-height: 42px;
            background:rgba(245,247,250,1);
            border-bottom:1px solid rgba(220,223,230,1);
            border-radius:4px;
            text-indent: 15px;
            color: #303133;
            font-size: 16px;
            .J_del-all {
                font-size: 14px;
                color: #409EFF;
                float: right;
                cursor: pointer;
                margin-right: 15px;
            }
        }
        .tree-div {
            width: 100%;
            height: 373px;
            overflow: auto;
            padding: 15px;
            box-sizing: border-box;
            .search-menu {
                margin-top: 20px;
                color: #606266;
                font-size: 14px;
                min-width: 100%;
                display:inline-block !important;
                .el-tree-node {
                    .el-tree-node__content {
                        height: 36px;
                        position: relative;
                        .open-child {
                            position: absolute;
                            right: 0;
                            top: 0;
                            width: 36px;
                            height: 36px;
                            padding: 0;
                            box-sizing: border-box;
                        }
                        .custom-tree-node {
                            flex: 1;
                            height: 100%;
                            line-height: 36px;
                            .open-btn {
                                width: 50px;
                                height: 14px;
                                color: #409EFF;
                                float: right;
                                text-align: right;
                                border-left: 1px solid #DCDFE6;
                                margin-top: 11px;
                                line-height: 14px;
                            }
                            &.disable-open {
                                z-index: 999;
                            }
                        }
                        &:hover {
                            background: none;
                        }
                    }
                }
            }
            .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
                background: none;
            }
        }
        .selected-list {
            .list {
                padding: 12px 0;
                display: flex;
                .label {
                    flex: 1;
                    .iconfont {
                        color: #409EFF;
                        margin-right: 5px;
                    }
                }
                .close-btn {
                    width: 16px;
                    height: 16px;
                    line-height: 18px;
                    text-align: center;
                    cursor: pointer;
                    border-radius: 100%;
                    font-size: 8px;
                    vertical-align: middle;
                    &:hover {
                        color: #fff;
                        background: #909399;
                    }
                }
            }
        }
    }
}
</style>

