<script setup lang="ts">
import YlIconSelector from "@/components/yl-icon-selector.vue";
import { iconSelector, userinfo } from "@/store/store.ts";
import { ref, watch } from "vue";
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { FormInstance } from "element-plus";
// 编辑菜单信息页面
const props = defineProps<{
  dialog: {
    title: string;
    visible: boolean;
  };
  data: sysMenuList;
  run: () => void;
  firstList?: sysMenuList[];
}>();
const formRef = ref<FormInstance>();
const level = ref("first");
const first = ref("");
const second = ref("");
const name = ref("");
const route_only = ref(false);
const path = ref("");
const icon = ref("");
const user_type = ref<string[]>([]);
const white_list = ref<string[]>([]);
const filterUserList = ref<typeUserList[]>([]);

const { data: sysSettings } = useRequest<{
  data: { name: string; data: sysSettings[] }[];
}>(() => myRequest(`/admin/sys`, userinfo.token), {
  ready: () => Boolean(userinfo.token),
});
const { data: userList } = useRequest<{ data: typeUserList[] }>(
  () => myRequest(`/admin/user`, userinfo.token),
  { ready: () => Boolean(userinfo.token) },
);
const { runAsync: updateMenu } = useRequest(
  () =>
    myRequest(
      `/admin/menus`,
      userinfo.token,
      props.data,
      props.dialog.title === "添加菜单" ? "post" : "put",
    ),
  { manual: true },
);

const checkID = (_: any, value: string, callback: (e?: Error) => void) => {
  if (
    !value ||
    isNaN(Number(value)) ||
    (value.length !== 3 && level.value === "first") ||
    (value.length !== 5 && level.value === "second")
  ) {
    callback(new Error("菜单id格式错误"));
  } else if (
    props.dialog.title === "新增菜单" &&
    props.firstList &&
    props.firstList.filter((e) => e.menu_id === value).length > 0
  ) {
    callback(new Error("菜单id已存在"));
  } else {
    callback();
  }
};
const checkPath = (_: any, value: string, callback: (e?: Error) => void) => {
  if (level.value !== "first" && !value) {
    callback(new Error("二级菜单路径不能为空"));
  } else {
    callback();
  }
};

const rules = ref({
  menu_id: [{ validator: checkID, trigger: "blur" }],
  user_type: [{ required: true, message: "请选择用户权限", trigger: "blur" }],
  path: [
    {
      validator: checkPath,
      trigger: "blur",
    },
  ],
  name: [{ required: true, message: "请填写菜单名称", trigger: "blur" }],
});

const onSubmit = () => {
  // emits("update", props.data);
  props.data.menu_id =
    level.value === "first" ? first.value : `${first.value}${second.value}`;
  props.data.user_type = user_type.value.join(",");
  props.data.white_list = white_list.value.join(",");
  props.data.name = name.value;
  props.data.path = path.value;
  props.data.icon = icon.value;
  props.data.route_only = route_only.value;
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      updateMenu().then(() => props.run());
    }
  });
};
const userFilter = (val: string) => {
  filterUserList.value = userList.value
    ? userList.value.data.filter(
        (item) =>
          item.username.indexOf(val) !== -1 ||
          item.nickname.indexOf(val) !== -1,
      )
    : [];
};
watch(props, () => {
  level.value = props.data.menu_id.length === 5 ? "second" : "first";
  first.value = props.data.menu_id.substring(0, 3);
  second.value = props.data.menu_id.substring(3, 5);
  name.value = props.data.name;
  path.value = props.data.path;
  icon.value = props.data.icon;
  route_only.value = props.data.route_only;
  user_type.value = props.data.user_type ? props.data.user_type.split(",") : [];
  white_list.value = props.data.white_list
    ? props.data.white_list.split(",")
    : [];
});
</script>

<template>
  <el-dialog :title="dialog.title" v-model="dialog.visible" destroy-on-close>
    <el-form
      :model="data"
      label-width="100px"
      class="menu-edit"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="菜单级别">
        <el-radio-group v-model="level">
          <el-radio value="first">一级菜单</el-radio>
          <el-radio value="second">二级菜单</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="ID" prop="menu_id">
        <div class="flex between" style="width: 100%">
          <el-select
            :validate-event="false"
            v-model="first"
            v-if="level !== 'first'"
            clearable
            placeholder="选择一级菜单"
            style="width: 40%"
          >
            <el-option
              v-for="item in firstList?.filter((e) => e.menu_id.length === 3)"
              :key="item.menu_id"
              :label="item.name"
              :value="item.menu_id"
            />
          </el-select>
          <el-input
            :validate-event="false"
            v-model="second"
            v-if="level !== 'first'"
            placeholder="2位二级菜单ID，不可与已有ID重复"
            style="width: 50%"
          />
          <el-input
            :validate-event="false"
            v-model="first"
            v-else
            placeholder="3位一级菜单ID，不可与已有ID重复"
          />
        </div>
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input
          v-model="name"
          placeholder="填写菜单名称"
          :validate-event="false"
        />
      </el-form-item>
      <el-form-item label="菜单路径" prop="path" :required="level !== 'first'">
        <el-input
          v-model="path"
          placeholder="填写菜单路径"
          :validate-event="false"
        />
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <el-tooltip
          placement="right"
          content="点击选择图标"
          :validate-event="false"
        >
          <el-icon
            size="28px"
            class="menu-icon"
            @click="iconSelector.visible = true"
            ><i :class="icon"></i></el-icon
        ></el-tooltip>
        <yl-icon-selector @update="(value) => (icon = value)" />
      </el-form-item>
      <el-form-item label="仅路由模式" prop="route_only">
        <el-switch :validate-event="false" v-model="route_only"></el-switch>
      </el-form-item>
      <el-form-item label="用户权限" prop="user_type">
        <el-select
          v-model="user_type"
          placeholder="选择用户权限"
          multiple
          :validate-event="false"
        >
          <el-option
            v-for="item in sysSettings?.data.filter(
              (e) => e.name === 'user_type',
            )[0].data"
            :key="item.value"
            :label="item.cn_name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="白名单" prop="white_list">
        <el-select
          v-model="white_list"
          placeholder="选择用户"
          multiple
          filterable
          :filter-method="userFilter"
          :validate-event="false"
        >
          <el-option
            v-for="item in filterUserList"
            :key="item.username"
            :label="item.nickname || item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>
.menu-edit {
  padding-right: 2rem;
}
.menu-icon {
  padding-left: 1rem;
}
</style>
