<template>
    <div>
        <div class="table-list">
        <section class="buttonBox">
          <el-row>
          <el-col :span='4' :offset="19">
            <el-input v-model="keyword" placeholder="请输入部门名称" clearable/>
          </el-col>
          </el-row>
        </section>
        <section class="contentBox">
            <el-table
              :data="filteredDepartments"
              style="width: 100%"
              :default-expand-all="true"
              @select-all="selectAllFilteredDepartmentHandler"
              row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            >
              <el-table-column type="selection" prop="selected"  width="70">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.selected" @change="departRowCheckChanged(scope.row)"/> 
                </template>
              </el-table-column>
              <el-table-column prop="name" label="部门名称" width="300" :fixed="true"/>
              <el-table-column label="部门成员通讯录权限" >
                <template slot-scope="scope">
                  {{
                        scope.row["permissionType"] == "JustOnDepart"
                          ? `可见所在${$SuperviseStr.depart}成员`
                          : ""
                      }}
                      {{ scope.row["permissionType"] == "JustSelf" ? "可见自己" : "" }}
                      {{
                        scope.row["permissionType"] == "OnDepartAndSub"
                          ? `可见所在${$SuperviseStr.depart}及下级${$SuperviseStr.depart}成员`
                          : ""
                      }}
                      {{
                        scope.row["permissionType"] == "Special"
                          ? `可见指定${$SuperviseStr.depart}` +
                            "(" +
                            scope.row.allowedDepartsStr +
                            ")"
                          : ""
                      }}
                      {{ scope.row["permissionType"] == "Whole" ? "可见全部成员" : "" }}
                </template>
              </el-table-column>
            </el-table>
          </section>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="applySelectedDepartment">确 定</el-button>
            <el-button @click="closeSelectDepartment">取 消</el-button>
        </div>
    </div>
</template>
<script>
import {getEmployeeIddepartAdminsApi,StaffDepartmentListApi } from "@/api/staffApi.js"
var hasLocalLoadedDepartments = false;
var localDepartmentsForSelectList = [];
var localDepartmentsFlatForSelectList = [];
export default {
    props: {
        loadingDepartment: {
            type: Boolean,
            default: false
        },
        selectedDepartIds: {
            type: Array,
            default: []
        }
    },
    emits: ["apply-selected-department-handler", "cancel-selected-department-handler"],
    data() {
        return {
            keyword: "",
            /**
             * 实际用到的数据
             */
            departments: [],
            filteredDepartments: [],
            selectedDepartments: {}
        }
    },
    watch: {
        selectedDepartIds(nValue, oValue) { 
            console.log("监听到变化:", nValue, oValue, arguments, this.selectedDepartIds, localDepartmentsForSelectList);
            this.switchDepartmentsSelected(localDepartmentsForSelectList, nValue,oValue);
        },
        keyword(nValue, oValue) {
            console.log("执行刷新操作keyword===",nValue);
            this.searchFilterDepartment(nValue);
        },
        filteredDepartments(n, o) {
            //console.log("数据发生变更", n, o);

        },
        loadingDepartment(nValue, oValue) {
            console.log("loadingDepartment的执行动作", nValue, oValue, this.selectedDepartIds);
        }
    },
    mounted() {
        var self = this;
        console.log("mounted 加载部门信息....",hasLocalLoadedDepartments,localDepartmentsForSelectList, self.selectedDepartIds);

        if (!hasLocalLoadedDepartments) {
            //表格列表
            let obj = { domainId: self.$route.query.domainId }; //获取url域domainId
            StaffDepartmentListApi(obj).then((response) => {
                if (response.data) {
                    var dps = response.data;
                    var rt = [];
                    for (var i = 0; i < dps.length; i++) {
                        var rtItem = self.buildBindDepatments(dps[i], self.selectedDepartIds);
                        rt.push(rtItem);
                    }
                    self.sortTableData(rt);
                    localDepartmentsForSelectList = rt;
                    self.searchFilterDepartment("");
                }

                hasLocalLoadedDepartments = true;
            });
        } else {
            this.switchDepartmentsSelected(localDepartmentsForSelectList, self.selectedDepartIds,null,true);
            self.searchFilterDepartment("");
        }
    },
    methods: {
        switchDepartmentsSelected(departments, stedDeptIds, unstedDepartIds, isFromPopupLoaded) {
            var self = this;
            if (!stedDeptIds) {
                stedDeptIds = [];
            }

            if (!unstedDepartIds) {
                unstedDepartIds = [];
            }

            var unSelectedIds = [];
            if (!isFromPopupLoaded) {
                unSelectedIds = unstedDepartIds.filter(ii => stedDeptIds.filter(uii => uii == ii).length == 0);
            }

            console.log("待切换的状态", stedDeptIds, stedDeptIds.length, unSelectedIds,isFromPopupLoaded);
            var executeSwitchChecked = function (dtps, dptIds, selectedFlag) {
                for (var i = 0; i < dptIds.length; i++) {
                    var stid = dptIds[i];
                    /*
                    var filteredDpts = dtps.filter(ii => ii.id == dptIds[i]);
                    for (var ic = 0; ic < filteredDpts.length; ic++) {
                        filteredDpts[ic].selected = selectedFlag;
                    }
                        */
                    var item = dtps[stid];
                    if (item) {
                        item.selected = selectedFlag;
                    }

                    if (item.selected) {
                        self.selectedDepartments[item.id] = item;
                    }

                    console.log("遍历的数据vvv为:", dtps, item, dptIds, selectedFlag);
                }
            }

            executeSwitchChecked(localDepartmentsFlatForSelectList, stedDeptIds, true);
            if (!isFromPopupLoaded) {
                console.log("选中的数据为v2...:", self.selectedDepartments, stedDeptIds, stedDeptIds.length);
                if (self.selectedDepartments && stedDeptIds.length == 0) {
                    for (var id in this.selectedDepartments) {
                        var item = this.selectedDepartments[id];
                        item.selected = false;
                        delete self.selectedDepartments[id];

                        console.log("取消选中的数据为:", item, self.selectedDepartments);
                    }
                }
                executeSwitchChecked(localDepartmentsFlatForSelectList, unSelectedIds, false);
            } else {
                console.log("即将进入循环...");
                for (var key in localDepartmentsFlatForSelectList) {
                    var item = localDepartmentsFlatForSelectList[key];
                    if (item.selected) {
                        console.log("目前已经选中的数据为xx：", item);
                        item.selected = stedDeptIds.filter(ii => ii == item.id).length > 0;
                    }
                }
            }
        },
        selectAllFilteredDepartmentHandler(tparam) {
            var self = this;
            var selectedAll = tparam.length > 0;
            localDepartmentsForSelectList.forEach((item, index) => {
                item.selected = selectedAll;
                self.departRowCheckChanged(item);
                console.log("触发到==selectAllFilteredDepartmentHandler 的功能", item);
                // 处理 item 对象
            });
        },
        searchFilterDepartment(keyword) {
            let searchValue = keyword;
            if (searchValue) {
                let treeData = localDepartmentsForSelectList
                treeData = this.handleTreeData(treeData, searchValue)
                this.filteredDepartments = treeData  //匹配返回过滤查询到的父子树数据
            } else {
                console.log("展示数据之前的searchFilterDepartment值为", localDepartmentsFlatForSelectList);
                this.filteredDepartments = localDepartmentsForSelectList;
            }
        },
        handleTreeData(treeData, searchValue) {
            // debugger
            if (!treeData || treeData.length == 0) return [];
            const array = [];
            for (let i = 0; i < treeData.length; i++) {
                let match = false;
                for (let pro in treeData[i]) {
                    if (typeof (treeData[i][pro]) == 'string') {
                        match |= treeData[i][pro].includes(searchValue);
                        if (match) break;
                    }
                }
                if (this.handleTreeData(treeData[i].children, searchValue).length > 0 || match) {
                    array.push({ ...treeData[i], children: this.handleTreeData(treeData[i].children, searchValue) })
                }
            }
            return array;
        },
        departRowCheckChanged(row) {
            var self = this;
            if (row?.children) {
                for (var i = 0; i < row.children.length; i++) {
                    var item = row.children[i];
                    item.name = item.name;
                    item.selected = row.selected;
                    if (item.selected) {
                        self.selectedDepartments[item.id] = item;
                    } else {
                        delete self.selectedDepartments[item.id];
                    }

                    self.departRowCheckChanged(item);
                }
            }

            if (row.selected) {
                self.selectedDepartments[row.id] = row;
            } else {
                delete self.selectedDepartments[row.id];
            }
        },
        applySelectedDepartment() {
            var self = this;

            var selectedDeparts = [];
            for (var id in self.selectedDepartments) {
                var item = self.selectedDepartments[id];
                selectedDeparts.push({
                    id: item.id,
                    name: item.name
                });
            }

            self.departments = selectedDeparts;

            console.log("选中的数据vvvv", self.departments);

            this.$emit("apply-selected-department-handler", self.departments);
        },
        closeSelectDepartment() {
            this.$emit("cancel-selected-department-handler");
        },
        buildBindDepatments(deptOne, selectedDptIds) {
            var self = this;
            var dto = {
                id: deptOne.id,
                name: deptOne.name,
                permissionType: deptOne.permissionType,
                selected: selectedDptIds.filter(ii => ii == deptOne.id).length > 0,
                children: []
            }

            if (dto.selected) {
                self.selectedDepartments[dto.id] = dto;
            } else {
                delete self.selectedDepartments[dto.id];
            }
            if (deptOne?.children) {
                for (var i = 0; i < deptOne.children.length; i++) {
                    var child = self.buildBindDepatments(deptOne.children[i], selectedDptIds);

                    dto.children.push(child);
                }
            }

            localDepartmentsFlatForSelectList[dto.id] = dto;

            return dto;
        },
        sortTableData(arr) {
            //递归排序
            if (arr.length) {
                arr.forEach((item) => {
                    item.displayOrderNumber = item.displayOrder;
                    let allowedDepartsStr = [];
                    if (item.allowedDeparts && item.allowedDeparts.length) {
                        item.allowedDeparts.forEach((its) => {
                            allowedDepartsStr.push(its.name);
                        });
                        item.allowedDepartsStr = allowedDepartsStr.join(",");
                    }
                    if (item.children.length) {
                        this.sortTableData(item.children);
                    }
                });
            }
        },
    }
}
</script>

