<template>
    <div class="m-menuManagement">
        <EmptyPage v-if="isShowEmpty" />
        <CSTreeDragLayout
            ref="CSTREEDRAGLAYOUT"
            @treeClick="treeClick"
            @addClickDirectory="addClickDirectory"
            @menuClick="menuClick"
            :mode="menuConfig.mode"
            :config="csTreeDragLayoutConfig"
            v-if="isShowMain && changeShow"
        >
            <template #form="slotProps">
                <MenuForm
                    ref="MenuForm"
                    :config="menuFormConfig"
                    :activeName="csTreeDragLayoutConfig.activeName"
                    :current="slotProps.slotProps"
                    @submitForm="submitForm"
                >
                    <template #[item.slotName]="menuFormProps" v-for="(item, index) in menuConfig.formConfig.slots.list">
                        <slot :name="item.slotName" :slotProps="menuFormProps.slotProps"></slot>
                    </template>
                </MenuForm>
            </template>
        </CSTreeDragLayout>
    </div>
</template>

<script>
import CSTreeDragLayout from "../../../BusinessCommon/Components/CSTreeDragLayout.vue";
import CSTopSystemNav from "../../../BusinessCommon/Components/CSTopSystemNav.vue";
import EmptyPage from "../../../BusinessCommon/Components/EmptyPage.vue";
import CoreAPI from "../../../Common/JS/CoreAPI.js";
import MenuForm from "../../../MenuFrame/Menu/Components/MenuForm.vue";

export default {
    //systemCode:系统编码
    //mode :运行模式，dev 设计时  runTime  运行时
    props: {
        menuConfig: {
            default() {
                return {
                    formConfig: {
                        slots: {
                            list: [{ slotName: "", formKey: "", formInitValue: null }]
                        }
                    },
                    systemCode: "",
                    mode: "dev"
                };
            }
        }
    },
    components: {
        EmptyPage,
        CSTreeDragLayout,
        MenuForm
    },
    data() {
        return {
            isShowEmpty: false,
            isShowMain: false,
            changeShow: true,
            csTreeDragLayoutConfig: {
                activeName: "",
                dropdown: [
                    {
                        type: "addDirectory",
                        label: "cs.menuFrame.menu.addMenu"
                    },
                    {
                        type: "deleteDirectory",
                        label: "cs.menuFrame.menu.delMenu"
                    }
                ],
                iconList: ["el-icon-files"],
                treeData: [],
                getMenuTreeData: this.getMenuTreeData,
                dragDirectory: this.dragMenuFrameMenu,
                loadNode: this.loadNode,
                props: {
                    children: "children",
                    label: "label",
                    isLeaf: "isLeaf"
                },
                showSearch: true,
                showTopAdd: true,
                topTitle: "cs.menuFrame.menu.menuConfig"
            },
            menuFormConfig: {
                isEdit: true,
                parentId: ""
            }
        };
    },
    methods: {
        /*----------  tab标签页相关  ----------*/
        changeShowEmpty(type) {
            this.isShowEmpty = type;
            this.isShowMain = !type;
        },
        handleClick(active) {
            this.csTreeDragLayoutConfig.activeName = active.active;
            //active.e 为假代表请求完系统以后默认执行第一次，把第一个系统返回
            if (!active.e) {
                this.changeShowEmpty(active.active == null);
            }
            this.changeShow = false;
            //手动切换系统时
            this.$nextTick(() => {
                this.changeShow = true;
            });
        },

        /*----------  let组件相关  ----------*/
        treeClick(data) {
            this.menuFormConfig.isEdit = true;
            if (data.loadType == 10) {
                this.$emit("customFunc", data);
            }
            CloudServiceCommon.Log.debug(data);
        },
        //处理接口返回的参数 拼装成当前需要的参数名等
        setResData(data) {
            if (Array.isArray(data)) {
                data.forEach(item => {
                    let obj = { directoryType: 1, directoryOrder: null, isLeaf: !item.isChildren };
                    ({ id: obj.directoryId, name: obj.directoryName, parentId: obj.parentDirectoryId, children: obj.children } = item);
                    item = Object.assign(item, obj);
                    if (item.children && item.children.length > 0) {
                        this.setResData(item.children);
                    }
                });
            } else {
                let obj = { directoryType: 1, directoryOrder: null, isLeaf: !data.isChildren };
                ({ id: obj.directoryId, name: obj.directoryName, parentId: obj.parentDirectoryId, children: obj.children } = data);
                data = Object.assign(data, obj);
            }
        },
        //获取菜单树
        getMenuTreeData(filterText) {
            let _this = this;
            let postData = {
                sortModels: [{ fieldName: "order", sortType: 0 }],
                filterModel: {
                    filterGroupModel: [
                        {
                            filterFields: [
                                {
                                    operationType: 10,
                                    fieldType: 10,
                                    fieldName: "name",
                                    fieldValue: filterText ? filterText.trim() : ""
                                }
                            ],
                            logicType: 0
                        }
                    ]
                },
                lazyLoad: false,
                systemId: _this.csTreeDragLayoutConfig.activeName
            };
            // 菜单框架不显示用户自定义菜单过滤
            if (_this.menuConfig.mode != "runTime") {
                postData.filterModel.filterGroupModel[0].filterFields.push({
                    operationType: 20,
                    fieldType: 30,
                    fieldName: "is_default",
                    fieldValue: 1
                });
            }
            return new Promise(resolve => {
                CoreAPI.getMenuFrameMenuTree(postData)
                    .then(res => {
                        _this.setResData(res);
                        resolve(res);
                    })
                    .catch(err => {
                        resolve([]);
                        if (err.code) {
                            this.$message.error(
                                this.$t(`cs.common.errorCode.${err.code}`).indexOf(err.code) == -1
                                    ? this.$t(`cs.common.errorCode.${err.code}`)
                                    : err.msg
                            );
                        }
                        CloudServiceCommon.Log.debug(err);
                    });
            });
        },
        //树拖拽
        dragMenuFrameMenu(postData) {
            return new Promise(resolve => {
                CoreAPI.dragMenuFrameMenu(postData)
                    .then(res => {
                        resolve(res);
                    })
                    .catch(err => {
                        resolve([]);
                        if (err.code) {
                            this.$message.error(
                                this.$t(`cs.common.errorCode.${err.code}`).indexOf(err.code) == -1
                                    ? this.$t(`cs.common.errorCode.${err.code}`)
                                    : err.msg
                            );
                        }
                        CloudServiceCommon.Log.debug(err);
                    });
            });
        },
        //懒加载
        loadNode(node) {
            const _this = this;
            return new Promise(resolve => {
                let postData = {
                    sortModels: [{ fieldName: "order", sortType: 0 }],
                    filterModel: {
                        filterGroupModel: [
                            {
                                filterFields: [
                                    {
                                        operationType: node.data.directoryId ? 20 : 100,
                                        fieldType: 10,
                                        fieldName: "parent_id",
                                        fieldValue: node.data.directoryId
                                    }
                                ],
                                logicType: 0
                            }
                        ]
                    },
                    lazyLoad: true,
                    systemId: _this.csTreeDragLayoutConfig.activeName
                };
                // 菜单框架不显示用户自定义菜单过滤
                if (_this.menuConfig.mode != "runTime") {
                    postData.filterModel.filterGroupModel[0].filterFields.push({
                        operationType: 20,
                        fieldType: 30,
                        fieldName: "is_default",
                        fieldValue: 1
                    });
                }
                CoreAPI.getMenuFrameMenuTree(postData)
                    .then(res => {
                        if (node.level == 1 && (!res || res.length == 0)) {
                            resolve([]);
                        }
                        _this.setResData(res);
                        _this.menuFormConfig.isEdit = true;
                        resolve(res);
                    })
                    .catch(err => {
                        resolve([]);
                        if (err.code) {
                            this.$message.error(
                                this.$t(`cs.common.errorCode.${err.code}`).indexOf(err.code) == -1
                                    ? this.$t(`cs.common.errorCode.${err.code}`)
                                    : err.msg
                            );
                        }
                        CloudServiceCommon.Log.debug(err);
                    });
            });
        },
        // 外面添加目录加号点击
        addClickDirectory() {
            // 初始化form表单并打开
            this.menuFormConfig.parentId = "";
            this.menuFormConfig.isEdit = false;
            this.$refs.CSTREEDRAGLAYOUT.resetRightStatus();
            this.$refs.CSTREEDRAGLAYOUT.leftTreeConfig.current = {}; //开启创建模式
            this.$nextTick(() => {
                this.$refs.CSTREEDRAGLAYOUT.rightFormConfig.showRight = true;
                this.$refs.CSTREEDRAGLAYOUT.rightFormConfig.isShowEmptyPage = false;
            });
            // 触发下父的方法
            this.$emit("customFunc");
        },
        //删除菜单
        deleteMenuFn(data) {
            let message = data.isChildren
                ? this.$t("cs.common.message.childOperationCategoryConfirmation", {
                      operate: `${this.$t("cs.common.button.delete")}`,
                      category: `${this.$t("cs.common.text.menu")}`,
                      data: `【${data.directoryName}】`
                  })
                : this.$t("cs.common.message.operationCategoryConfirmation", {
                      operate: `${this.$t("cs.common.button.delete")}`,
                      category: `${this.$t("cs.common.text.menu")}`,
                      data: `【${data.directoryName}】`
                  });
            this.$confirm(message, this.$t("cs.common.text.tips"), {
                confirmButtonText: this.$t("cs.common.button.ok"),
                cancelButtonText: this.$t("cs.common.button.cancel"),
                closeOnClickModal: false,
                closeOnPressEscape: false,
                type: "warning"
            })
                .then(() => {
                    let postData = {
                        systemId: this.csTreeDragLayoutConfig.activeName,
                        selectAll: false, //是否全选
                        selectKeys: [data.directoryId], //列表选中的key集合
                        deselectKeys: [], //列表取消选中的key集合
                        deleteField: "id", //删除的标识，表示根据哪个字段删除
                        filterModel: null //详见通用过滤模型说明
                    };
                    CoreAPI.batchDeleteMenuFrameMenu(postData).then(
                        res => {
                            if (res) {
                                this.$refs.CSTREEDRAGLAYOUT.delTree(data);
                            }
                        },
                        err => {
                            if (err.code) {
                                this.$message.error(
                                    this.$t(`cs.common.errorCode.${err.code}`).indexOf(err.code) == -1
                                        ? this.$t(`cs.common.errorCode.${err.code}`)
                                        : err.msg
                                );
                            }
                        }
                    );
                })
                .catch(err => {
                    CloudServiceCommon.Log.debug(err);
                });
        },
        menuClick(item) {
            switch (item.type) {
                case "addDirectory":
                    this.addClickDirectory();
                    this.menuFormConfig.parentId = item.data.directoryId;
                    this.menuFormConfig.isEdit = false;
                    break;
                case "deleteDirectory":
                    this.deleteMenuFn(item.data);
                    break;
                default:
                    break;
            }
        },
        submitForm(res) {
            this.setResData(res);
            this.$refs.CSTREEDRAGLAYOUT.RefreshTree(res);
        },
        //根据编码获取系统表信息
        getAuthorizeSystemByCode() {
            CoreAPI.getAuthorizeSystemByCode(this.menuConfig.systemCode).then(res => {
                if (res && res.id) {
                    this.handleClick({ active: res.id }, false);
                }
            });
        }
    },
    created() {
        this.menuFormConfig = { ...this.menuFormConfig, ...this.menuConfig };
        if (this.menuConfig.systemCode) {
            this.getAuthorizeSystemByCode();
        } else {
            setTimeout(() => {
                this.handleClick({ active: this.$route.params?.id }, false);
            });
        }
        if (this.menuConfig.mode == "runTime") {
            // wsl 2023-01-13 运行时允许用户自己添加自定义菜单，内置菜单只能添加和修改不能删除
            // this.csTreeDragLayoutConfig.dropdown = [];
            // this.csTreeDragLayoutConfig.showTopAdd = false;
        }
    },
    mounted() {
        this.$on("updateMenu", function (data) {
            this.$refs.MenuForm.$emit("updateMenuForm", data);
        });
    },
    watch: {
        $route(to, from) {
            if (to.params.id) {
                this.handleClick({ active: to.params.id }, true);
            } else if (this.menuConfig.systemCode) {
                this.getAuthorizeSystemByCode();
            }
        }
    }
};
</script>

<style lang="less" scoped>
.m-menuManagement {
    height: 100%;
    i {
        cursor: pointer;
        font-size: 16px;
    }
}
</style>
<style lang="less">
.g-addMenu-dialog .el-dialog {
    height: 250px !important;
    margin: auto !important;
    position: absolute !important;
}
</style>
