import {
  deleteDeptList,
  getDeptList,
  postDeptList,
  putDeptList
} 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() {
  const form: any = ref({
    deptName: ""
  });
  const UpdateForm: any = ref({
    name: "", //菜单名称
    sortOrder: "", //排序值，越小越靠前
    parentId: "" //父级部门ID
  });
  const dialogType = ref(1);
  const dataList = ref([]);
  const deptList = 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: "weight",
      minWidth: 130
    },
    {
      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 UpdateFormSubmit() {
    if (dialogType.value == 1) {
      const { status, msg } = await postDeptList(UpdateForm.value);
      if (status == 1) {
        ElMessage({
          message: "新增部门成功",
          type: "success"
        });
        dialogUpdateVisible.value = false;
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    } else {
      const { status, msg } = await putDeptList(UpdateForm.value);
      if (status == 1) {
        ElMessage({
          message: "部门修改成功",
          type: "success"
        });
        dialogUpdateVisible.value = false;
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    }
  }
  function handleDelete(row) {
    ElMessageBox.confirm(`是否删除名称为:${row.name}的部门? `, "提示", {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      const { status, msg } = await deleteDeptList(row.id);
      if (status == 1) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    });
  }
  function AddUser() {
    UpdateForm.value = {
      name: "", //菜单名称
      sortOrder: "", //排序值，越小越靠前
      parentId: "" //父级部门ID
    };
    dialogType.value = 1;
    dialogUpdateVisible.value = true;
  }
  function handleUpdate(row) {
    dialogType.value = 2;
    dialogUpdateVisible.value = true;
    UpdateForm.value = {
      name: row.name,
      deptId: row.id,
      sortOrder: "",
      parentId: row.parentId
    };
  }

  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(type = "") {
    if (type == "search" && !Object.values(form).some(item => !!item)) {
      return ElMessage({
        message: "请输入查询条件",
        type: "error"
      });
    }
    if (type == "all") {
      form.value.deptName = "";
    }
    loading.value = true;
    const { data } = await getDeptList({
      ...form.value,
      pageSize: pagination.pageSize,
      pageNum: pagination.currentPage
    });
    dataList.value = data;
    pagination.total = data.length;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  onMounted(() => {
    onSearch();
  });

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