import dayjs from "dayjs";
import editForm from "../components/form.vue";
import { message } from "@/utils/message";

import {
  deleteRoleAPI,
  getPermissionListAPI,
  getRoleListAPI,
  postAddRoleAPI,
  putUpdateRoleAPI,
  getRolePermissionsAPI,
  putUpdateRolePermissionsAPI,
  getDepartmentListAPI
} from "@/api/system";

import { handleTree } from "@/utils/tree";
import { usePublicHooks } from "../../hooks";
import { getKeyList } from "@pureadmin/utils";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, h, watch, toRaw } from "vue";
import type {
  DepartmentInfo,
  RoleInfo,
  RolePermissionInfo
} from "types/system";

export const useRole = (treeRef: Ref) => {
  /**查询表单 */
  const form = reactive({
    name: "",
    code: "",
    status: "",
    department_id: "",
    description: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref();
  /**
   * 数据列表
   */
  const dataList = ref<RoleInfo[]>([]);
  /**
   * 加载状态
   */
  const loading = ref(true);
  /**
   * 标签样式
   */
  const { tagStyle } = usePublicHooks();
  /**树形列表id列表 */
  const treeIds = ref<string[]>([]);
  /**
   * 树形列表
   */
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  /**
   * 分页参数
   */
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 30, 40, 50]
  });
  const curRow = ref();
  /**
   * 树形列表数据
   */
  const treeData = ref([]);
  /**是否显示 */
  const isShow = ref<boolean>(false);
  /**是否关联 */
  const isLinkage = ref<boolean>(false);
  /**查询值 */
  const treeSearchValue = ref<string>("");
  /**是否展开 */
  const isExpandAll = ref<boolean>(false);
  /**是否全选 */
  const isSelectAll = ref<boolean>(false);
  const columns: TableColumnList = [
    {
      label: "角色名称",
      prop: "name",
      minWidth: 120
    },
    {
      label: "角色标识",
      prop: "code",
      minWidth: 150
    },
    {
      label: "状态",
      minWidth: 130,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "角色描述",
      prop: "description",
      minWidth: 150
    },
    {
      label: "所属部门",
      prop: "department_name",
      minWidth: 150
    },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "create_time",
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "更新时间",
      minWidth: 180,
      prop: "update_time",
      formatter: ({ update_time }) =>
        dayjs(update_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 300,
      slot: "operation"
    }
  ];
  /**
   * 初次查询
   */
  const onSearch = async () => {
    loading.value = true;
    const data = await getRoleListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...toRaw(form)
    });
    dataList.value = data.data.result;
    pagination.total = data.data.total;
    pagination.currentPage = data.data.page;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  };
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  /**处理页码变化 */
  const handleSizeChange = async (val: number) => {
    const res = await getRoleListAPI({
      page: pagination.currentPage,
      pageSize: val
    });
    if (res.success) {
      const data = res.data;
      dataList.value = data.result;
      pagination.total = data.total;
      pagination.currentPage = data.page;
    }
  };
  /**处理每页数量变化 */
  const handleCurrentChange = async (val: number) => {
    const res = await getRoleListAPI({
      page: val,
      pageSize: pagination.pageSize
    });
    if (res.success) {
      const data = res.data;
      dataList.value = data.result;
      pagination.total = data.total;
      pagination.currentPage = data.page;
    }
  };

  const handleDelete = async (row: RoleInfo) => {
    const res = await deleteRoleAPI(row.id);
    if (res.success) {
      message(`您删除了角色名称为${row.name}的这条数据`, { type: "success" });
      onSearch();
    } else {
      message(`删除失败！`, { type: "error" });
    }
  };
  const openDialog = (title = "新增", row?: RoleInfo) => {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          code: row?.code ?? "",
          description: row?.description ?? "",
          status: row?.status ?? 1,
          department_id: row?.department_id ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          ref: formRef,
          formInline: {
            id: row?.id ?? "",
            name: row?.name ?? "",
            code: row?.code ?? "",
            description: row?.description ?? "",
            status: row?.status ?? 1,
            department_id: row?.department_id ?? ""
          }
        }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        let curData = options.props.formInline as RoleInfo;
        function chores() {
          message(`您${title}了角色名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async (valid: any) => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              const res = await postAddRoleAPI(curData);
              if (res.success) {
                chores();
              } else {
                message(`添加失败！`, {
                  type: "error"
                });
                done();
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const res = await putUpdateRoleAPI(curData, row.id);
              if (res.success) {
                chores();
              } else {
                message(`修改失败！`, {
                  type: "error"
                });
                done();
              }
            }
          }
        });
      }
    });
  };

  /**
   * 角色权限
   */
  const handleMenu = async (row?: RolePermissionInfo) => {
    const { id } = row;
    if (id) {
      curRow.value = row;
      isShow.value = true;
      const res = await getRolePermissionsAPI(id);
      if (res.success) {
        treeRef.value.setCheckedKeys(
          getKeyList(res.data.result, "permission_id")
        );
        isExpandAll.value = true;
      } else {
        treeRef.value.setCheckedKeys([]);
        isExpandAll.value = true;
      }
    } else {
      curRow.value = null;
      isShow.value = false;
      isExpandAll.value = false;
    }
  };

  /** 高亮当前权限选中行 */
  const rowStyle = ({ row: { id } }) => {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  };
  /**保存角色权限 */
  const handleSave = async () => {
    const { id, name } = curRow.value;
    // 根据用户 id 调用实际项目中菜单权限修改接口
    let permissions = treeRef.value.getCheckedKeys();
    let halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
    permissions = [...new Set(permissions.concat(halfCheckedKeys))];
    const res = await putUpdateRolePermissionsAPI(id, {
      permission_ids: permissions
    });
    if (res.success) {
      message(`角色名称为${name}的权限修改成功~`, {
        type: "success"
      });
    } else {
      message(`角色名称为${name}的权限修改失败！`, {
        type: "error"
      });
    }
  };
  /**查询权限变化 */
  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  /**过滤方法 */
  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };
  /**部门列表 */
  const departments = ref<DepartmentInfo[]>([]);
  /**获取部门列表 */
  const getDepartments = async () => {
    const res = await getDepartmentListAPI({ page: 1, pageSize: 9999 });
    if (res.success) {
      departments.value = formatHigherOptions(res.data.result);
    } else {
      departments.value = [];
    }
  };
  const formatHigherOptions = treeList => {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  };

  onMounted(async () => {
    onSearch();
    const res = await getPermissionListAPI({ page: 1, pageSize: 99999 });
    const data = res.data.result;
    treeIds.value = getKeyList(data, "id");
    treeData.value = handleTree(data, "id", "parent_id");
    await getDepartments();
  });
  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    departments,
    rowStyle,
    onSearch,
    resetForm,
    openDialog,
    handleMenu,
    handleSave,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    handleSizeChange,
    handleCurrentChange
  };
};
