import {
  deleteMenuList,
  getMenuList,
  postMenuList,
  putMenuList
} from "@/api/system";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, computed, onMounted } from "vue";

export function useUser() {
  //是否可见，0隐藏，1显示
  const visibleswitchvalue = ref("1");
  // 是否缓存，0否，1是
  const keepAliveswitchvalue = ref("1");
  const UpdateForm: any = ref({
    name: "", //菜单名称
    enName: "", //英文名称
    permission: "", //权限标识
    path: "", //路由路径
    parentId: "-1", //父菜单ID
    icon: "", //菜单图标
    sortOrder: "0", //排序值，越小越靠前
    embedded: "0", //是否内嵌，0否，1是
    menuType: "0" //菜单类型，0菜单，1按钮
  });
  const dialogType = ref(1);
  const dataList = ref([]);
  const menuList = ref([]);
  const loading = ref(false);
  const dialogUpdateVisible = ref(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "ID",
      prop: "id",
      minWidth: 130
    },
    {
      label: "菜单名",
      prop: "name",
      minWidth: 130
    },
    {
      label: "组件路径",
      prop: "path",
      minWidth: 130
    },
    {
      label: "图标",
      prop: "meta.icon",
      minWidth: 130,
      cellRenderer: ({ props, row }) => (
        <el-text size={props.size}>{row.meta.icon}</el-text>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  // 树形结构格式化
  function TreeFormatter(data) {
    const result = data.map(item => {
      if (item.children && item.children.length != 0) {
        return {
          label: item.name,
          value: item.id,
          children: TreeFormatter(item.children)
        };
      } else if (item.menuType == 1) {
        return {
          disabled: true,
          label: item.name,
          value: item.id
        };
      } else {
        return {
          label: item.name,
          value: item.id
        };
      }
    });
    return result;
  }
  // 获取全部菜单列表
  async function Menu() {
    const { data } = await getMenuList({});
    menuList.value = TreeFormatter(data);
    menuList.value.unshift({
      label: "作为顶级菜单",
      value: "-1"
    });
  }
  Menu();
  async function UpdateFormSubmit() {
    if (dialogType.value == 1) {
      const { status, msg } = await postMenuList({
        name: UpdateForm.value.name,
        enName: UpdateForm.value.enName,
        permission: UpdateForm.value.permission,
        path: UpdateForm.value.path,
        parentId:
          UpdateForm.value.parentId === "null"
            ? null
            : UpdateForm.value.parentId,
        icon: UpdateForm.value.icon,
        visible: visibleswitchvalue.value,
        sortOrder: UpdateForm.value.sortOrder,
        keepAlive: keepAliveswitchvalue.value,
        embedded: UpdateForm.value.embedded,
        menuType: UpdateForm.value.menuType
      });
      if (status == 1) {
        ElMessage({
          message: "新增菜单成功",
          type: "success"
        });
        dialogUpdateVisible.value = false;
        onSearch();
        Menu();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    } else {
      const { status, msg } = await putMenuList({
        name: UpdateForm.value.name,
        enName: UpdateForm.value.enName,
        permission: UpdateForm.value.permission,
        path: UpdateForm.value.path,
        parentId:
          UpdateForm.value.parentId === "null"
            ? null
            : UpdateForm.value.parentId,
        icon: UpdateForm.value.icon,
        visible: visibleswitchvalue.value,
        sortOrder: UpdateForm.value.sortOrder,
        keepAlive: keepAliveswitchvalue.value,
        embedded: UpdateForm.value.embedded,
        menuType: UpdateForm.value.menuType,
        menuId: UpdateForm.value.menuId
      });
      if (status == 1) {
        ElMessage({
          message: "菜单修改成功",
          type: "success"
        });
        dialogUpdateVisible.value = false;
        onSearch();
        Menu();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    }
  }
  function handleDelete(row) {
    ElMessageBox.confirm(`是否删除名称为:${row.name}的菜单? `, "提示", {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      const { status, msg } = await deleteMenuList(row.id);
      if (status == 1) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch();
        Menu();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    });
  }
  function AddUser() {
    UpdateForm.value = {
      name: "", //菜单名称
      enName: "", //英文名称
      permission: "", //权限标识
      path: "", //路由路径
      parentId: "", //父菜单ID
      icon: "", //菜单图标
      sortOrder: "0", //排序值，越小越靠前
      embedded: "0", //是否内嵌，0否，1是
      menuType: "0" //菜单类型，0菜单，1按钮
    };
    dialogType.value = 1;
    dialogUpdateVisible.value = true;
  }
  function handleUpdate(row) {
    dialogType.value = 2;
    dialogUpdateVisible.value = true;
    UpdateForm.value = {
      menuId: row.id ? row.id : "",
      name: row.name ? row.name : "", //菜单名称
      enName: row.meta.enName ? row.meta.enName : "", //英文名称
      permission: row.permission ? row.permission : "", //权限标识
      path: row.path ? row.path : "", //路由路径
      parentId: row.parentId ? row.parentId : "", //父菜单ID
      icon: row.meta.icon ? row.meta.icon : "", //菜单图标
      sortOrder: row.sortOrder, //排序值，越小越靠前
      embedded: row.embedded ? row.embedded : "0", //是否内嵌，0否，1是
      menuType: row.menuType ? row.menuType : "" //菜单类型，0菜单，1按钮
    };
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    if (typeof val !== "number") return;
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
    onSearch();
  }

  // 搜索函数（请求表格数据列表）
  function submit(e: { keyCode: number }) {
    if (e.keyCode == 229) {
      return;
    } else {
      onSearch();
    }
  }
  async function onSearch() {
    loading.value = true;
    const { data } = await getMenuList({});
    console.log('testlog', data);
    dataList.value = data;
    pagination.total = data.length;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  onMounted(() => {
    onSearch();
  });

  return {
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    dialogUpdateVisible,
    visibleswitchvalue,
    keepAliveswitchvalue,
    UpdateFormSubmit,
    submit,
    UpdateForm,
    menuList,
    dialogType,
    AddUser,
    onSearch,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
