<template>
  <!-- ADD EDIT的 抽屉 -->
  <div>
    <MegaDrawer
      :title="$t(title)"
      :visible="drawer"
      :append-to-body="true"
      :wrapper-closable="false"
      width="520"
      @close="drawerClose"
    >
      <div slot="main">
        <a-form-model
          ref="menuForm"
          layout="vertical"
          :model="menuForm"
          :rules="menuFormRules"
          class="menuForm"
        >
          <a-form-model-item :label="$t('SUP_MENU')" prop="parentId">
            <div
              class="transparentDiv"
              :class="disabled ? 'disabledStatus' : ''"
            >
              {{ $t(parentMenuName) }}
            </div>
            <MegaSelectTree
              v-model="menuForm.parentId"
              :tree-data="menuAllList"
              style="width: 100%"
              :disabled="disabled"
              :placeholder="$t('PLACESELECT')"
              @change="handleChangeFormDept"
            ></MegaSelectTree>
            <!-- <a-select
              v-model="menuForm.parentMenuCode"
              class="d-inline-block"
              :disabled="disabled"
              :placeholder="$t('PLACESELECT')"
            >
              <a-select-option
                v-for="item in menuAllList"
                :key="item.id"
                :value="item.id"
                >{{ $t(item.moduleName) }}</a-select-option
              >
            </a-select> -->
          </a-form-model-item>
          <a-form-model-item :label="$t('TYPE')" prop="menuType">
            <!-- <span slot="label">{{ $t("TYPE") }}: </span> -->
            <a-radio-group v-model="menuForm.menuType">
              <a-radio
                v-for="(item, index) in menuTypeList"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <!-- 名称 -->
          <a-form-model-item :label="$t('NAME')" prop="menuName">
            <a-row>
              <a-col>
                <I18nSelect
                  v-if="clientTypeList.length && typeList.length"
                  ref="select"
                  v-model="menuForm.menuName"
                  :client-type-list="clientTypeList"
                  :i18n-type-list="typeList"
                ></I18nSelect>
              </a-col>
            </a-row>
          </a-form-model-item>
          <!-- 序号 -->
          <a-form-model-item :label="$t('SORT')" prop="seq">
            <a-input-number
              v-model="menuForm.seq"
              style="width: 100%"
              :min="0"
            />
          </a-form-model-item>
          <!-- 图标 -->
          <a-form-model-item
            v-if="menuForm.menuType === 'MENU'"
            :label="$t('ICON')"
            prop="icon"
          >
            <IconList v-model="menuForm.icon" />
          </a-form-model-item>
          <!-- 模块 or 目录 -->
          <template v-if="['MODULE', 'CONTENTS'].includes(menuForm.menuType)">
            <!-- 图标 -->
            <a-form-model-item
              v-if="
                menuForm.menuType === 'CONTENTS' ||
                menuForm.menuType === 'MODULE'
              "
              :label="$t('ICON')"
              prop="icon"
            >
              <IconList v-model="menuForm.icon" />
            </a-form-model-item>
            <!-- 是否外链 -->
            <a-form-model-item :label="$t('IS_FRAME')" prop="menuType">
              <a-radio-group v-model="menuForm.isFrame" @change="isFrameChange">
                <a-radio value="Y">{{ $t("YES") }}</a-radio>
                <a-radio value="N">{{ $t("NO") }}</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 是外链处理 -->
            <template v-if="formIsFrame">
              <!-- 外链类型 -->
              <a-form-model-item :label="$t('FRAME_TYPE')" prop="frameType">
                <a-select
                  v-model="menuForm.frameType"
                  :placeholder="$t('PLACESELECT')"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="item in frameTypeList"
                    :key="item.value"
                    :value="item.value"
                    >{{ item.label }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
              <!-- 外链类型为BI 处理 -->
              <a-form-model-item
                v-if="menuForm.frameType === 'BI'"
                :label="$t('REPORT_SERVER')"
                prop="reportServerCode"
              >
                <a-select
                  v-model="menuForm.reportServerCode"
                  :placeholder="$t('PLACESELECT')"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="item in reportServerList"
                    :key="item.code"
                    :value="item.code"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
              <!-- 打开方式 -->
              <a-form-model-item :label="$t('OPEN_TYPE')" prop="openType">
                <a-select
                  v-model="menuForm.openType"
                  :placeholder="$t('PLACESELECT')"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="item in openTypeList"
                    :key="item.value"
                    :value="item.value"
                    >{{ item.label }}</a-select-option
                  >
                </a-select>
              </a-form-model-item>
            </template>
            <!-- 是否关联组件（关联布局） -->
            <a-form-model-item
              v-if="menuForm.isFrame === 'N'"
              :label="$t('IS_RELATED_COMPONENT')"
              prop="isRelated"
            >
              <a-radio-group v-model="menuForm.isRelated">
                <a-radio value="Y">{{ $t("YES") }}</a-radio>
                <a-radio value="N">{{ $t("NO") }}</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 关联组件（布局） 处理（地址 组件） -->
            <!-- 路由 -->
            <a-form-model-item
              v-if="formIsFrame || formIsRelated"
              :label="$t('MENU_PATH')"
              prop="menuPath"
            >
              <a-input
                v-model.trim="menuForm.menuPath"
                allow-clear
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
            <!-- 组件 -->
            <a-form-model-item
              v-if="menuForm.isFrame === 'N' && menuForm.isRelated !== 'N'"
              :label="$t('COMPONENT')"
              prop="component"
            >
              <a-input
                v-model.trim="menuForm.component"
                allow-clear
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
            <!-- 是否可见 -->
            <a-form-model-item :label="$t('IS_VISIBLE')" prop="visible">
              <a-radio-group v-model="menuForm.visible">
                <a-radio value="Y">{{ $t("YES") }}</a-radio>
                <a-radio value="N">{{ $t("NO") }}</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 模块判断处理 -->
            <template v-if="menuForm.menuType === 'MODULE'">
              <!-- 是否存在移动端 -->
              <a-form-model-item
                :label="$t('EXIST_MOBILE_TERMINAL')"
                prop="mobileAppFlag"
              >
                <a-radio-group v-model="menuForm.mobileAppFlag">
                  <a-radio value="1">{{ $t("YES") }}</a-radio>
                  <a-radio value="0">{{ $t("NO") }}</a-radio>
                </a-radio-group>
              </a-form-model-item>
              <!-- 移动端首页地址 -->
              <a-form-model-item
                :label="$t('MOBILE_HOME_ADDRESS')"
                prop="appHomeUrl"
              >
                <a-input
                  v-model.trim="menuForm.appHomeUrl"
                  allow-clear
                  :placeholder="$t('PLACEENTER')"
                />
              </a-form-model-item>
              <!-- 背景色 -->
              <a-form-model-item
                :label="$t('BACKGROUND_COLOR')"
                prop="backgroundColor"
              >
                <MegaColorPicker
                  v-model="menuForm.backgroundColor"
                  color-format="hex"
                />
              </a-form-model-item>
            </template>
          </template>

          <!-- 菜单 -->
          <template v-if="menuForm.menuType === 'MENU'">
            <!-- 是否外链 -->
            <a-form-model-item :label="$t('IS_FRAME')" prop="menuType">
              <a-radio-group v-model="menuForm.isFrame" @change="isFrameChange">
                <a-radio value="Y">{{ $t("YES") }}</a-radio>
                <a-radio value="N">{{ $t("NO") }}</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 是外链处理 -->
            <template v-if="formIsFrame">
              <!-- 外链类型 -->
              <a-form-model-item :label="$t('FRAME_TYPE')" prop="frameType">
                <a-select
                  v-model="menuForm.frameType"
                  :placeholder="$t('PLACESELECT')"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="item in frameTypeList"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <!-- 外链类型为BI 处理 -->
              <a-form-model-item
                v-if="menuForm.frameType === 'BI'"
                :label="$t('REPORT_SERVER')"
                prop="reportServerCode"
              >
                <a-select
                  v-model="menuForm.reportServerCode"
                  :placeholder="$t('PLACESELECT')"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="item in reportServerList"
                    :key="item.code"
                    :value="item.code"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <!-- 打开方式 -->
              <a-form-model-item :label="$t('OPEN_TYPE')" prop="openType">
                <a-select
                  v-model="menuForm.openType"
                  :placeholder="$t('PLACESELECT')"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="item in openTypeList"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </template>
            <!-- 路由 -->
            <a-form-model-item :label="$t('MENU_PATH')" prop="menuPath">
              <a-input
                v-model.trim="menuForm.menuPath"
                allow-clear
                :placeholder="$t('PLACEENTER')"
              />
            </a-form-model-item>
            <!-- 组件 （外链不需要组件和keep alive）-->
            <template v-if="!formIsFrame">
              <a-form-model-item :label="$t('COMPONENT')" prop="component">
                <a-input
                  v-model.trim="menuForm.component"
                  allow-clear
                  :placeholder="$t('PLACEENTER')"
                />
              </a-form-model-item>
              <!-- keep alive -->
              <a-form-model-item :label="$t('STATE_CACHE')" prop="keepAlive">
                <a-radio-group v-model="menuForm.keepAlive">
                  <a-radio value="1">{{ $t("YES") }}</a-radio>
                  <a-radio value="0">{{ $t("NO") }}</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </template>
            <!-- 是否可见 -->
            <a-form-model-item :label="$t('IS_VISIBLE')" prop="visible">
              <a-radio-group v-model="menuForm.visible">
                <a-radio value="Y">{{ $t("YES") }}</a-radio>
                <a-radio value="N">{{ $t("NO") }}</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 背景色 -->
            <a-form-model-item
              :label="$t('BACKGROUND_COLOR')"
              prop="backgroundColor"
            >
              <MegaColorPicker
                v-model="menuForm.backgroundColor"
                color-format="hex"
              />
            </a-form-model-item>
          </template>

          <!-- 按钮 -->
          <template v-if="menuForm.menuType === 'BUTTON'">
            <!-- 是否关联组件 -->
            <a-form-model-item
              :label="$t('IS_RELATED_COMPONENT')"
              prop="isRelated"
            >
              <a-radio-group v-model="menuForm.isRelated">
                <a-radio value="Y">{{ $t("YES") }}</a-radio>
                <a-radio value="N">{{ $t("NO") }}</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 关联组件 处理（地址 组件 keepalive） -->
            <template v-if="formIsRelated">
              <!-- 路由 -->
              <a-form-model-item :label="$t('MENU_PATH')" prop="menuPath">
                <a-input
                  v-model.trim="menuForm.menuPath"
                  allow-clear
                  :placeholder="$t('PLACEENTER')"
                />
              </a-form-model-item>
              <!-- 组件 -->
              <a-form-model-item :label="$t('COMPONENT')" prop="component">
                <a-input
                  v-model.trim="menuForm.component"
                  allow-clear
                  :placeholder="$t('PLACEENTER')"
                />
              </a-form-model-item>
              <!-- tab name -->
              <a-form-model-item :label="$t('TAB_NAME')" prop="menuTag">
                <I18nSelect
                  v-if="clientTypeList.length && typeList.length"
                  ref="select"
                  v-model="menuForm.menuTag"
                  :client-type-list="clientTypeList"
                  :i18n-type-list="typeList"
                ></I18nSelect>
              </a-form-model-item>
              <!-- keep alive -->
              <a-form-model-item :label="$t('STATE_CACHE')" prop="keepAlive">
                <a-radio-group v-model="menuForm.keepAlive">
                  <a-radio value="1">{{ $t("YES") }}</a-radio>
                  <a-radio value="0">{{ $t("NO") }}</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </template>
          </template>
          <!-- 权限标识 -->
          <a-form-model-item :label="$t('PERMISSION_ID')" prop="perms">
            <a-input
              v-model.trim="menuForm.perms"
              allow-clear
              :placeholder="$t('PLACEENTER')"
              maxlength="50"
            />
          </a-form-model-item>
          <!-- 权重 -->
          <a-form-model-item :label="$t('WEIGHT')" prop="weight">
            <a-select
              v-model="menuForm.weight"
              :placeholder="$t('PLACESELECT')"
              style="width: 100%"
            >
              <a-select-option
                v-for="item in weightList"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </div>
      <template slot="footer">
        <a-button type="primary" @click="confirm">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="cancel">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </template>
    </MegaDrawer>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  Drawer as MegaDrawer,
  SelectTree as MegaSelectTree,
  ColorPicker as MegaColorPicker,
  IconList,
  Icon,
} from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import I18nSelect from "@/components/I18nSelect";

export default {
  name: "Drawer",
  components: {
    MegaDrawer,
    MegaSelectTree,
    MegaColorPicker,
    IconList,
    Icon,
    I18nSelect,
  },
  props: {
    drawer: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
    menuForm: {
      type: Object,
      default: null,
    },
    menuFormRules: {
      type: Object,
      default: null,
    },
    menuTypeList: {
      type: Array,
      default: () => [],
    },
    typeList: {
      type: Array,
      default: () => [],
    },
    moduleList: {
      type: Array,
      default: () => [],
    },
    menuAllList: {
      type: Array,
      default: () => [],
    },
    menuData: {
      type: Array,
      default: () => [],
    },
    openTypeList: {
      type: Array,
      default: () => [],
    },
    weightList: {
      type: Array,
      default: () => [],
    },
    frameTypeList: {
      type: Array,
      default: () => [],
    },
    reportServerList: {
      type: Array,
      default: () => [],
    },
    codeRule: {
      type: Number,
      default: 0,
    },
    cancel: {
      type: Function,
      default: () => {},
    },
    confirm: {
      type: Function,
      default: () => {},
    },
    isFrameChange: {
      type: Function,
      default: () => {},
    },
    drawerClose: {
      type: Function,
      default: () => {},
    },
    selected: {
      type: Function,
      default: () => {},
    },
  },
  data() {
    return {
      clicked: false,
      isSelected: false,
      dictFormRules: {
        dataLabel: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        dataValue: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        dataOrder: [],
        remark: [
          {
            max: 255,
            message: this.$t("PLACEENTER") + 255 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      },
      treeValue: "",
      parentMenuName: "",
      disabled: false,
      // 类别字典
      dictCategoryList: [],
      dataStatusList: [],
      oldI18nCode: null,

      clientTypeList: [],
    };
  },
  computed: {
    ...mapState({
      locale: (state) => state.app.locale,
    }),
    formIsFrame() {
      // 是否外链
      return this.menuForm.isFrame === "Y";
    },
    formIsRelated() {
      // 是否关联组件或布局
      return this.menuForm.isRelated === "Y";
    },
    treeData() {
      const currentMenuCode = this.menuForm.parentMenuCode || "";
      const menuData = JSON.parse(JSON.stringify(this.menuData));
      if (currentMenuCode && menuData.length > 0) {
        const delTreeNode = (data) => {
          // eslint-disable-next-line
          for (let t = 0; t < data.length; t++) {
            if (
              data[t].menuCode === currentMenuCode ||
              data[t].menuType === "BUTTON"
            ) {
              data.splice(t, 1);
            } else if (
              Array.isArray(data[t].children) &&
              data[t].children.length > 0
            ) {
              delTreeNode(data[t].children);
            }
          }
        };
        delTreeNode(menuData);
        return menuData;
      }
      return [];
    },
    selectIconType() {
      if (this.menuForm.clientType === "PAD") {
        return "mobile";
      }
      return "pc";
    },
  },
  watch: {
    menuForm: {
      handler(newVal) {
        this.disabled = false;
        this.$nextTick(() => {
          this.parentMenuName = "";
          const { clientType, treeLevel, parentId, id } = newVal;
          this.disabled = false;
          if ((treeLevel < 2 && parentId === "0") || !parentId) {
            if (!this.moduleList || !this.moduleList.length) return;
            const data = this.moduleList
              .filter((item) => item.value === clientType)
              .shift();
            this.parentMenuName = data.label || "";
            this.disabled = true;
          } else if (parentId) {
            const treeFind = (tree) => {
              // eslint-disable-next-line
              for (const item of tree) {
                if (item.id && item.id === parentId) return item;
                if (item.children) {
                  const res = treeFind(item.children);
                  if (res) return res;
                }
              }
              return null;
            };
            const result = treeFind(this.menuData);
            this.parentMenuName =
              result && result.menuName ? result.menuName : "";
            if (!id) {
              this.disabled = true;
            }
          } else {
            this.disabled = true;
          }
        });
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.getDictByCode("DIC:CORE:MOM_VERSION").then((res) => {
      this.clientTypeList = res.data.data || [];
    });
  },
  methods: {
    fatherMethod() {
      this.clicked = false;
    },
    handleClickChange(visible) {
      this.clicked = visible;
    },
    // 表单中的组织选择
    handleChangeFormDept(value) {
      // eslint-disable-next-line vue/no-mutating-props
      this.menuForm.parentId = value;
    },
    // 自定义render
    _renderFun(h, { node, data, store }) {
      return <span>{this.$t(data.menuName)}</span>;
    },
    i18nSave(val) {
      const { id, i18nCode, type, clientType } = val;
      const params = {
        i18nCode,
        type,
        clientType,
        items: this.$store.state.app.languages.map((item) => {
          const { label, value } = item;
          return {
            dataValue: val[value],
            i18nCode,
            languageCode: value,
            languageName: label,
          };
        }),
      };
      this.$refs.selectI18n.$refs.drawerForm.$refs.iForm.validate((valid) => {
        if (valid) {
          if (val.i18nCode === this.oldI18nCode && id) {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/sys/i18n`, {
                id,
                ...params,
              })
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                // this.$set(this.menuForm, 'menuName', this.dialogForm.i18nCode)
                this.$emit("saveMenuCodeI18n", val.i18nCode);
                this.$refs.selectI18n.cancel();
                this.$emit("refreshTable");
                // this.$parent.handleRefreshI18n();
              });
          } else {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/sys/i18n`, params)
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$emit("saveMenuCodeI18n", val.i18nCode);
                this.$set(this.menuForm, "menuName", val.i18nCode);
                this.$set(
                  this.menuForm,
                  "name",
                  `${val.i18nCode}(${val[this.locale]})`
                );
                this.$refs.selectI18n.cancel();
                this.$emit("refreshTable");
                // this.$parent.handleRefreshI18n();
              });
          }
        }
      });
    },
  },
};
</script>

<style lang="less">
.menuForm .transparentDiv {
  position: absolute;
  left: 10px;
  width: 230px;
  top: -5px;
  height: 30px;
  color: #606266;
  font-size: inherit;
  line-height: 30px;
}
.disabledStatus {
  background: rgb(245, 245, 245);
  z-index: 1;
}
</style>
