import {
  deleteRoleList,
  getMenuList,
  getRoleList,
  getRoleRightList,
  postRoleList,
  putRoleList,
  putRoleMenuList
} 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 = reactive({
    roleName: ""
  });
  const AddForm = ref([]);
  const AddFormdata: any = ref({
    roleName: "",
    roleDesc: "",
    roleCode: ""
  });
  const dialogType = ref(1);
  const AddFormvalueStrictly = ref([]);
  const dataList = ref([]);
  const loading = ref(true);
  const dialogAddVisible = 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: "roleId",
      minWidth: 130
    },
    {
      label: "角色名称",
      prop: "roleName",
      minWidth: 130
    },
    {
      label: "角色描述",
      prop: "roleDesc",
      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"
    ];
  });
  async function AddFormSubmit() {
    if (dialogType.value == 1) {
      console.log(AddFormdata.value);
      const { status, msg } = await postRoleList(AddFormdata.value);
      if (status == 1) {
        ElMessage({
          message: "添加角色成功",
          type: "success"
        });
        dialogAddVisible.value = false;
        AddFormvalueStrictly.value = [];
        AddFormdata.value = {
          roleName: "",
          roleDesc: "",
          roleCode: ""
        };
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    } else {
      const { status, msg } = await putRoleList(AddFormdata.value);
      if (status == 1) {
        ElMessage({
          message: "编辑角色成功",
          type: "success"
        });
        dialogAddVisible.value = false;
        AddFormvalueStrictly.value = [];
        AddFormdata.value = {
          roleName: "",
          roleDesc: "",
          roleCode: ""
        };
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    }
  }
  // 删除角色
  function handleDelete(row) {
    ElMessageBox.confirm(
      `是否删除该角色?  角色名称为:${row.roleName}`,
      "提示",
      {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(async () => {
      const { status, msg } = await deleteRoleList(row.roleId);
      if (status == 1) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch();
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      }
    });
  }
  // 添加角色
  function AddUser() {
    dialogType.value = 1;
    AddFormvalueStrictly.value = [];
    AddFormdata.value = {
      roleName: "",
      roleDesc: "",
      roleCode: "roleCode"
    };
    dialogAddVisible.value = true;
  }
  // 编辑角色
  async function handleUpdate(row) {
    dialogType.value = 2;
    loading.value = false;
    AddFormdata.value.roleId = row.roleId; //角色ID
    AddFormdata.value.roleName = row.roleName; //角色名称
    AddFormdata.value.roleCode = row.roleCode; //角色编码
    AddFormdata.value.roleDesc = row.roleDesc; //角色描述
    AddFormdata.value.createBy = row.createBy; //创建人
    AddFormdata.value.updateBy = row.updateBy; //修改人
    dialogAddVisible.value = true;
  }
  // 当前页数量切换
  function handleSizeChange(val: number) {
    if (typeof val === "number") {
      pagination.pageSize = val;
      onSearch();
    }
  }
  // 当前页码切换
  function handleCurrentChange(val: number) {
    if (typeof val === "number") {
      pagination.currentPage = val;
      onSearch();
    }
  }
  // 选择表格项
  function handleSelectionChange() { }
  // 搜索函数（请求表格数据列表）
  function submit(e: { keyCode: number }) {
    if (e.keyCode == 229) {
      return;
    } else {
      onSearch("search");
    }
  }
  // 搜索列表
  async function onSearch(type = "") {
    if (type == "search" && !Object.values(form).some(item => !!item)) {
      return ElMessage({
        message: "请输入查询条件",
        type: "error"
      });
    }
    if (type == "all") {
      form.roleName = "";
    }
    loading.value = true;
    const { data } = await getRoleList({
      ...form,
      pageSize: pagination.pageSize,
      pageNum: pagination.currentPage
    });
    dataList.value = data.records;
    pagination.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  // 树形结构格式化
  function TreeFormatter(data) {
    const result = data.map(item => {
      if (item.children) {
        return {
          label: item.name,
          id: item.id,
          // value: item.id,
          children: TreeFormatter(item.children)
        };
      } else {
        return {
          label: item.name,
          id: item.id
          // value: item.id
        };
      }
    });
    return result;
  }

  // 个人权限树形结构格式化
  function RoleTreeFormatter(data) {
    const arr = [];
    data.forEach(item => {
      if (item.children && item.children.length !== 0) {
        arr.push(item.id);
        arr.push(...RoleTreeFormatter(item.children));
      } else {
        arr.push(item.id);
      }
    });
    return arr;
  }

  // 获取角色权限树
  async function getrolelisttree(row) {
    const { data } = await getRoleRightList({ roleId: row.roleId });
    return data;
  }

  const AuthorizationVisible = ref(false);
  // 获取权限树
  async function getroletree() {
    loading.value = true;
    const { data } = await getMenuList({});
    AddForm.value = TreeFormatter(data);
    console.log(AddForm.value);
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  getroletree();
  const roleId = ref("");
  // 授权
  async function handleAuthorization(row) {
    roleId.value = row.roleId;
    const arr = await getrolelisttree(row);
    console.log(arr);
    AddFormvalueStrictly.value = arr.menus;
    AuthorizationVisible.value = true;
    menuTree.value.setCheckedKeys(arr.setCheckedKeys);
  }
  const menuTree = ref();
  // 提交授权修改
  async function AddAuthorization() {
    const menuIds = [
      ...menuTree.value.getHalfCheckedKeys(),
      ...menuTree.value.getCheckedKeys()
    ];
    const { status, msg } = await putRoleMenuList({
      roleId: roleId.value,
      menuIds
    });
    if (status == 1) {
      ElMessage({
        message: "调整授权成功",
        type: "success"
      });
      AuthorizationVisible.value = false;
    } else {
      ElMessageBox.alert(msg, "提示", {
        confirmButtonText: "关闭",
        type: "warning"
      });
    }
  }
  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    dialogAddVisible,
    AddFormSubmit,
    submit,
    AddFormvalueStrictly,
    AddForm,
    AddFormdata,
    dialogType,
    AddUser,
    onSearch,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleAuthorization,
    AuthorizationVisible,
    menuTree,
    AddAuthorization
  };
}
