<template>
    <div class="m-form-container">
        <el-form
            v-if="rightFormConfig.showLoad"
            class="el-form-init"
            :model="rightFormConfig.form"
            :rules="rightFormConfig.rule"
            size="small"
            ref="MenuForm"
            label-width="110px"
        >
            <el-form-item style="display: flex; align-items: center; justify-content: end; padding: 12px 0 8px 0">
                <el-button @click="resetForm('MenuForm')">{{ $t("cs.common.button.reset") }}</el-button>
                <el-button style="margin-left: 16px" type="primary" @click="submitForm('MenuForm')">{{ $t("cs.common.button.save") }}</el-button>
            </el-form-item>
            <el-form-item data-name="菜单名称" :label="$t('cs.menuFrame.menu.menuName')" prop="name">
                <el-input v-model="rightFormConfig.form.name"></el-input>
            </el-form-item>
            <el-form-item data-name="菜单编码" :label="$t('cs.menuFrame.menu.menuCode')" prop="code">
                <el-input :disabled="config.isEdit && rightFormConfig.isSpecialHandlingFormItem" v-model="rightFormConfig.form.code"></el-input>
            </el-form-item>
            <el-form-item data-name="菜单英文名" :label="$t('cs.menuFrame.menu.englishNameOfMenu')" prop="nameEn">
                <el-input v-model="rightFormConfig.form.nameEn"></el-input>
            </el-form-item>
            <el-form-item
                v-if="!rightFormConfig.isSpecialHandlingFormItem"
                data-name="菜单图标"
                :label="$t('cs.menuFrame.menu.menuIcon')"
                prop="icon"
            >
                <el-input v-model="rightFormConfig.form.icon"></el-input>
            </el-form-item>
            <el-form-item
                v-if="!rightFormConfig.isSpecialHandlingFormItem && !getSlotForm('loadType')"
                data-name="加载方式"
                :label="$t('cs.menuFrame.menu.loadType')"
                prop="loadType"
            >
                <el-radio v-model="rightFormConfig.form.loadType" :label="0">{{ $t("cs.menuFrame.menu.route") }}</el-radio>
                <el-radio v-model="rightFormConfig.form.loadType" :label="1">{{ $t("cs.menuFrame.menu.linkAddress") }}</el-radio>
            </el-form-item>
            <slot name="loadType" v-if="getSlotForm('loadType')" :slotProps="rightFormConfig.form"></slot>
            <el-form-item
                v-if="!rightFormConfig.isSpecialHandlingFormItem && rightFormConfig.form.loadType == 0 && !getSlotForm('loadType')"
                data-name="菜单路由"
                :label="$t('cs.menuFrame.menu.menuRouting')"
                prop="routeId"
            >
                <el-select
                    class="directoryPositionSelect"
                    v-model="rightFormConfig.form.routeCode"
                    :placeholder="$t('cs.common.text.pleaseSelect')"
                    ref="CSFormSelectTree"
                    clearable
                    @clear="clearHandler"
                    @visible-change="visibleChangeHandler"
                >
                    <el-option
                        class="sdfgsgfsd"
                        :value="rightFormConfig.form.directoryName"
                        style="background: #fff; height: 240px; padding: 6px 16px"
                    >
                        <CSFormSelectTree
                            v-if="rightFormConfig.showCSFormSelectTree"
                            :activeName="activeName"
                            :searchTreeKey="rightFormConfig.searchTreeKey"
                            :directoryId="rightFormConfig.form.routeId"
                            :root="false"
                            @treeClickHandler="copyTreeClickHandler"
                        />
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                v-if="!rightFormConfig.isSpecialHandlingFormItem && rightFormConfig.form.loadType == 1 && !getSlotForm('loadType')"
                data-name="链接地址"
                :label="$t('cs.menuFrame.menu.linkAddress')"
                prop="linkAddress"
            >
                <el-input v-model="rightFormConfig.form.linkAddress"></el-input>
            </el-form-item>
            <el-form-item
                v-if="!rightFormConfig.isSpecialHandlingFormItem && rightFormConfig.form.loadType != 0 && !getSlotForm('loadType')"
                data-name="打开方式"
                :label="$t('cs.menuFrame.menu.openType')"
                prop="openType"
            >
                <el-radio v-model="rightFormConfig.form.openType" :label="0">{{ $t("cs.menuFrame.menu.embeddedBizSystem") }}</el-radio>
                <el-radio v-model="rightFormConfig.form.openType" :label="1">{{ $t("cs.menuFrame.menu.openNewTab") }}</el-radio>
            </el-form-item>
            <el-form-item data-name="公共菜单" :label="$t('cs.menuFrame.menu.commonMenu')" prop="isPublic">
                <el-radio v-model="rightFormConfig.form.isPublic" :label="1">{{ $t("cs.common.text.yes") }}</el-radio>
                <el-radio v-model="rightFormConfig.form.isPublic" :label="0">{{ $t("cs.common.text.no") }}</el-radio>
                <!-- （为公共菜单时不需要授权即可见） -->
                <span style="color: #c0c4cc">{{ `（${$t("cs.menuFrame.menu.commonMenuMessage")}）` }}</span>
            </el-form-item>
            <el-form-item data-name="是否显示" :label="$t('cs.menuFrame.menu.whetherToDisplay')" prop="isShow">
                <el-radio v-model="rightFormConfig.form.isShow" :label="1">{{ $t("cs.common.text.display") }}</el-radio>
                <el-radio v-model="rightFormConfig.form.isShow" :label="0">{{ $t("cs.common.text.doNotDisplay") }}</el-radio>
            </el-form-item>
            <el-form-item v-if="config.mode != 'runTime'" data-name="扩展参数" :label="$t('cs.menuFrame.menu.extendedParameters')" prop="extendParam">
                <el-input type="textarea" :rows="5" v-model="rightFormConfig.form.extendParam"></el-input>
            </el-form-item>
            <el-form-item data-name="备注" :label="$t('cs.common.text.description')" prop="description">
                <el-input type="textarea" :rows="5" v-model="rightFormConfig.form.description"></el-input>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import CSFormSelectTree from "../../../BusinessCommon/Components/CSFormSelectTree.vue";
import CoreAPI from "../../../Common/JS/CoreAPI.js";

const BLURNAME = async (rule, value, callback) => {
    if (CloudServiceCommon.Methods.isStartOrLastHaveSpace(value)) {
        callback(
            new Error(
                vm.$t("cs.common.verification.isThereASpaceBeforeAndAfter", {
                    verifyName: vm.$t("cs.menuFrame.menu.menuName")
                })
            )
        );
    } else {
        callback();
    }
};
export default {
    props: {
        current: {
            default() {
                return {};
            }
        },
        activeName: {
            type: String,
            default: ""
        },
        config: {
            default() {
                return {};
            }
        }
    },
    components: {
        CSFormSelectTree
    },
    data() {
        return {
            rightFormConfig: {
                form: {
                    id: "",
                    parentId: null,
                    name: "",
                    nameEn: "",
                    code: "",
                    type: 0,
                    icon: "",
                    isPublic: 0,
                    isShow: 1,
                    dynamicMenuApi: "",
                    routeId: "",
                    description: "",
                    routeCode: "",
                    extendParam: "",
                    iconType: 0,
                    isDefault: 1,
                    loadType: 0,
                    linkAddress: "",
                    openType: 0,
                    isUserCustom: 0,
                    loadValueExtend: null
                },
                rule: {
                    name: [
                        { validator: BLURNAME, trigger: "change" },
                        {
                            max: 255,
                            message: vm.$t("cs.common.verification.verifyLength4", {
                                verifyName: vm.$t("cs.menuFrame.menu.menuName"),
                                total: 255
                            }),
                            trigger: "change"
                        }
                    ],
                    code: [
                        {
                            max: 255,
                            message: vm.$t("cs.common.verification.verifyLength4", {
                                verifyName: vm.$t("cs.menuFrame.menu.menuCode"),
                                total: 255
                            }),
                            trigger: "change"
                        }
                    ],
                    nameEn: [
                        {
                            max: 255,
                            message: vm.$t("cs.common.verification.verifyLength4", {
                                verifyName: vm.$t("cs.menuFrame.menu.englishNameOfMenu"),
                                total: 255
                            }),
                            trigger: "change"
                        }
                    ],
                    icon: [
                        {
                            max: 255,
                            message: vm.$t("cs.common.verification.verifyLength4", {
                                verifyName: vm.$t("cs.menuFrame.menu.menuIcon"),
                                total: 255
                            }),
                            trigger: "change"
                        }
                    ],
                    extendParam: [
                        {
                            max: 4000,
                            message: vm.$t("cs.common.verification.verifyLength4", {
                                verifyName: vm.$t("cs.menuFrame.menu.extendedParameters"),
                                total: 4000
                            }),
                            trigger: "change"
                        }
                    ],
                    description: [
                        {
                            max: 4000,
                            message: vm.$t("cs.common.verification.verifyLength4", {
                                verifyName: vm.$t("cs.common.text.description"),
                                total: 4000
                            }),
                            trigger: "change"
                        }
                    ],
                    linkAddress: [
                        {
                            max: 4000,
                            message: this.$t("cs.common.verification.verifyLength4", {
                                verifyName: vm.$t("cs.menuFrame.menu.linkAddress"),
                                total: 4000
                            }),
                            trigger: "change"
                        }
                    ]
                },
                isEdit: true,
                searchTreeKey: "",
                showLoad: false,
                showCSFormSelectTree: false,
                showCSFormLoadType: false,
                showCSFormOpenType: false,
                // 是否需要特殊处理表单项
                isSpecialHandlingFormItem: false
            },
            routeCopy: null
        };
    },
    methods: {
        /*----------  表单相关  ----------*/

        //获取当前动态表单插槽
        getSlotForm(slotName) {
            let slot = null;
            if (this.config.formConfig.slots.list) {
                this.config.formConfig.slots.list.forEach(element => {
                    if (element.slotName === slotName) {
                        slot = element;
                    }
                });
            }
            return slot;
        },
        //处理动态的验证规则
        setRules() {
            let this_ = this;
            setRequired();
            function createValidator(requiredConfig) {
                return {
                    required: true,
                    message: this_.$t("cs.common.verification.verifyIsNull", {
                        verifyName: this_.$t(requiredConfig.label)
                    }),
                    trigger: requiredConfig.trigger
                };
            }
            function setRequired() {
                let required = this_.config.formConfig.ruleConfig.required;
                for (let i = 0; i < required.length; i++) {
                    const element = required[i];
                    //处理必填项
                    this_.rightFormConfig.rule[element.code].forEach((item, index) => {
                        if (item.required) {
                            this_.rightFormConfig.rule[element.code].splice(index, 1);
                        }
                    });
                    this_.rightFormConfig.rule[element.code].unshift(createValidator(element));
                }
            }
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let this_ = this;
                    let postData = {
                        id: this_.current.directoryId,
                        parentId: null,
                        userIdRecord: CloudServiceCommon.User.userId,
                        orgIdRecord: CloudServiceCommon.User.organizationId,
                        type: 0,
                        systemId: this_.activeName
                    };

                    postData = Object.assign(postData, this_.rightFormConfig.form);

                    let addFn = this_.rightFormConfig.isEdit ? CoreAPI.updateMenuFrameMenu : CoreAPI.addMenuFrameMenu;

                    addFn(postData)
                        .then(res => {
                            this_.$emit("submitForm", res);
                            this_.$message.success(this_.$t("cs.common.message.submitSuccessConfirmation"));
                        })
                        .catch(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
                                );
                            }
                            CloudServiceCommon.Log.debug(err);
                        });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName] && this.$refs[formName].resetFields();
            this.rightFormConfig.form.loadValueExtend = null;
            this.rightFormConfig.form.routeId = this.routeCopy?.routeId;
            this.rightFormConfig.form.routeCode = this.routeCopy?.routeCode;
        },
        //目录点击
        copyTreeClickHandler(data) {
            this.rightFormConfig.form.routeId = data.directoryId;
            this.rightFormConfig.form.routeCode = data.directoryName;
            this.$refs["CSFormSelectTree"].blur();
        },
        //清空选项
        clearHandler() {
            this.rightFormConfig.form.routeId = "";
            this.rightFormConfig.form.routeCode = "";
        },
        visibleChangeHandler(show) {
            this.rightFormConfig.showCSFormSelectTree = show;
        },
        loadTypeChange(show) {
            this.rightFormConfig.showCSFormLoadType = show;
        },
        openTypeChange(show) {
            this.rightFormConfig.showCSFormOpenType = show;
        },
        getMenu() {
            if (!this.current || JSON.stringify(this.current) == "{}") {
                //如果是新建的话初始化动态表单的值
                if (this.config.formConfig.slots.list) {
                    this.config.formConfig.slots.list.forEach(element => {
                        this.rightFormConfig.form[element.formKey] = element.formInitValue;
                    });
                }
                this.rightFormConfig.showLoad = true;
                return;
            }
            CoreAPI.getMenuFrameMenuById(this.current.directoryId)
                .then(res => {
                    ({ ...this.rightFormConfig.form } = res);
                    if (!this.routeCopy) {
                        this.routeCopy = {
                            routeId: this.rightFormConfig.form.routeId,
                            routeCode: this.rightFormConfig.form.routeCode
                        };
                    }
                    this.rightFormConfig.showLoad = true;
                    // wsl add 2023-01-13 只有运行时内置菜单的表单项需要特殊处理，其他菜单的表单项不需要特殊处理
                    if (this.config.mode == "runTime" && this.rightFormConfig.form.isDefault == 1) {
                        this.rightFormConfig.isSpecialHandlingFormItem = true;
                    }
                })
                .catch(err => {
                    this.rightFormConfig.showLoad = true;
                    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);
                });
        }
    },
    created() {
        this.rightFormConfig.form.parentId = this.config.parentId;
        this.rightFormConfig.isEdit = this.config.isEdit;
        this.setRules();
        // wsl add 2023-01-13 运行时用户自己添加的菜单，isDefault值为0,修改菜单isUserCustom：为1
        if (this.config.mode == "runTime" && !this.config.isEdit) {
            this.rightFormConfig.form.isDefault = 0;
            this.rightFormConfig.form.isUserCustom = 1;
        }
        this.getMenu();
    },
    mounted() {
        let this_ = this;
        this_.$on("updateMenuForm", function({ key = "", value }) {
            this_.$set(this_.rightFormConfig.form, key, value);
        });
        if ($bus) {
            $bus.$on("langChange", function() {
                this_.resetForm("MenuForm");
                this_.setRules();
            });
        }
    }
};
</script>

<style lang="less" scoped>
.m-form-container {
    margin: auto;
    max-width: 800px;
    height: 539px;
    @media (max-width: 1380px) {
        padding: 13px 30px;
    }
    .directoryPositionSelect {
        width: 100%;
    }
}
</style>
<style lang="less">
.m-form-container .el-radio {
    line-height: 32px;
}
</style>
