<script setup lang="ts">
import { reactive, ref } from "vue";
import { FormRules, ElForm } from "element-plus";
import { httpUpdate, httpAdd } from "/@/api/system/menuOperator";
import { menuTypeList, menuPrivateList } from "/@/utils/status";
import { responseHandle } from "/@/utils/responseHandle";
import { IconSelect } from "/@/components/ReIcon";
import { useNav } from "/@/layout/hooks/nav";
import type { IMenuTree } from "../types";

enum FROM_TYPE {
  create = "create",
  edit = "edit",
  view = "view"
}

const { logout } = useNav();
const showModel = ref(false);
const currentMenuId = ref("");
const TYPE = ref<FROM_TYPE>(FROM_TYPE.create);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const currentNode = ref<IMenuTree | null>(null);
const loading = ref(false);
const titleType = ref("");

const emit = defineEmits(["reload"]);
const initform = {
  menu_name: "",
  menu_type: "1",
  menu_img: "",
  menu_route: "",
  menu_url: "",
  private: "1",
  weight: "1",
  pid: "0",
  level: "",
  id: ""
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  menu_name: [
    { required: true, message: "请输入菜单名称", trigger: "blur" },
    // { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
  ],
  menu_type: [
    {
      required: true,
      message: "请选择菜单类型",
      trigger: "change"
    }
  ],
  menu_img: [
    {
      required: true,
      message: "请选择菜单图标",
      trigger: "change"
    }
  ],
  menu_route: [
    {
      required: true,
      message: "请输入菜单路由",
      trigger: "blur"
    },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
  ],

  menu_url: [
    {
      required: true,
      message: "请输入文件地址",
      trigger: "blur"
    },
    { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" }
  ],
  private: [
    {
      required: true,
      message: "请选择页面是否显示",
      trigger: "change"
    }
  ],
  weight: [
    {
      required: true,
      message: "请输入排序权重",
      trigger: "blur"
    }
  ],
  level: [
    {
      required: true,
      message: "请选择菜单权限等级",
      trigger: "blur"
    }
  ]
});

function show(node: any, id: string, isCreate: string) {
  console.log(node);
  currentNode.value = node;
  Object.keys(ruleForm.value).forEach(key => {
    if (key == "private") {
      ruleForm.value[key] =
        isCreate === "create" ? "1" : String(node["is_private"]);
    } else {
      ruleForm.value[key] =
        isCreate === "create" ? initform[key] : String(node[key]);
    }
  });
  if (id !== "" && isCreate === "create") {
    ruleForm.value.pid = id;
  }
  TYPE.value = isCreate;
  switch (TYPE.value) {
    case "create":
      titleType.value = "新建菜单";
      break;
    case "edit":
      titleType.value = "编辑菜单";
      break;
    case "view":
      titleType.value = "菜单详情";
      break;
    default:
      titleType.value = "新建菜单";
  }

  console.log(ruleForm.value);
  menu_type_change();
  showModel.value = true;
}

function handleUpdate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpUpdate
  };
}

function handleCreate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpAdd
  };
}

function handleSave() {
  formRef.value.validate(async valid => {
    if (valid) {
      if (loading.value) return;
      const handler =
        TYPE.value === FROM_TYPE.create ? handleCreate : handleUpdate;
      loading.value = true;
      const { api, data } = handler();
      const { message, code } = await api(data);

      responseHandle({
        code,
        message,
        logout,
        handler: () => {
          showModel.value = false;
          loading.value = false;
          emit("reload");
        }
      });
    }
  });
}
function menu_type_change() {
  const { menu_type } = ruleForm.value;
  rules.menu_url[0].required = menu_type === "2";
}

defineExpose({
  show,
  changeCurrentMenuId: (id: string) => (currentMenuId.value = id)
});
</script>

<template>
  <div>
    <el-dialog
      v-model="showModel"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
      append-to-body
      destroy-on-close
      :width="'700px'"
      :title="titleType"
      v-loading="loading"
    >
      <el-form
        ref="formRef"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        class="demo-ruleForm"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单名称" prop="menu_name">
              <el-input
                v-model="ruleForm.menu_name"
                :disabled="TYPE === 'view'"
                placeholder="菜单名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="menu_type">
              <el-select
                v-model="ruleForm.menu_type"
                style="width: 100%"
                @change="menu_type_change"
                :disabled="TYPE === 'view'"
                placeholder="菜单类型"
              >
                <el-option
                  v-for="(si, sii) in menuTypeList"
                  :key="'type' + si.value + sii"
                  :label="si.label"
                  :value="si.value"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="菜单图标" prop="menu_img">
              <IconSelect v-model="ruleForm.menu_img" />
              <!-- <IconifyIconOffline icon="user" /> -->
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="菜单路由" prop="menu_route">
              <el-input
                v-model="ruleForm.menu_route"
                :disabled="TYPE === 'view'"
                placeholder="菜单路由" /></el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="页面显示" prop="private">
              <el-radio-group
                v-model="ruleForm.private"
                :disabled="TYPE === 'view'"
              >
                <el-radio
                  v-for="(si, sii) in menuPrivateList"
                  :key="si.value + sii"
                  :label="si.value"
                  :value="si.value"
                  >{{ si.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item></el-col
          >

          <el-col :span="24" v-if="ruleForm.menu_type === '2'">
            <el-form-item label="页面地址" prop="menu_url">
              <el-input
                v-model="ruleForm.menu_url"
                placeholder="页面地址"
                :disabled="TYPE === 'view'"
              >
                <template #prepend>views/</template>
                <template #append>.vue</template></el-input
              >
            </el-form-item></el-col
          >

          <el-col :span="12">
            <el-form-item label="排序权重" prop="weight">
              <el-input-number
                v-model="ruleForm.weight"
                :precision="0"
                style="width: 100%"
                :min="1"
                :max="999"
                :disabled="TYPE === 'view'"
              /> </el-form-item
          ></el-col>

          <el-col :span="12">
            <el-form-item label-width="120px" label="菜单权限等级" prop="level">
              <el-select v-model="ruleForm.level">
                <el-option label="公共" value="0" />
                <el-option label="超管" value="1" />
                <el-option label="平台端" value="2" />
                <el-option label="供应商端" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="flex justify-end">
          <el-button :loading="loading" type="primary" @click="handleSave"
            >保存</el-button
          >
          <el-button @click="showModel = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
