import dayjs from "dayjs";
import editForm from "../components/form.vue";
import { message } from "@/utils/message";
import { type Ref, ref, reactive, onMounted, h } from "vue";
import { addDialog, closeDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { CodeImportInfo } from "types/code";
import {
  deleteCodeImportAPI,
  deleteCodeImportListAPI,
  getAddCodeAPI,
  getCodeImportListAPI,
  getCodeTemplateAPI,
  postAddCodeAPI,
  putCodeImportAuditAPI,
  putUpdateCodeImportAPI
} from "@/api/code";
import { getKeyList, handleTree } from "@pureadmin/utils";
import {
  ElMessageBox,
  type UploadProps,
  type UploadUserFile
} from "element-plus";
import { deleteFileAPI, postUploadFileAPI } from "@/api/file";
import type { DepartmentInfo } from "types/system";
import { getDepartmentListAPI } from "@/api/system";

export const useCode = (tableRef: Ref) => {
  /**
   * 查询表单
   */
  const form = reactive({
    code: "",
    description: "",
    username: "",
    department_id: "",
    nickname: "",
    timeRange: [null, null],
    status: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref(null);
  /**
   * 数据列表
   */
  const dataList = ref<CodeImportInfo[]>([]);
  /**
   * 加载状态
   */
  const loading = ref(true);
  /**
   * 已选数量
   */
  const selectedNum = ref<number>(0);
  /**
   * 分页参数
   */
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 30, 40, 50]
  });
  // 上传文件区域显示状态
  const showUploadArea = ref(false);
  const fileList = ref<UploadUserFile[]>([]);
  /**上传成功后文件列表 */
  const fileIds = ref([]);
  const fileId = ref<string>("");
  /**上传按钮状态 */
  const uploadStatus = ref<boolean>(false);

  const getStatusTag = (status: number) => {
    switch (status) {
      case 1:
        return "success";
      case 2:
        return "danger";
      case 3:
        return "warning";
      default:
        return "info";
    }
  };

  const getStatusTagText = (status: number) => {
    switch (status) {
      case 1:
        return "审核通过";
      case 2:
        return "审核未通过";
      case 3:
        return "待审核";
      default:
        return "未知";
    }
  };
  /**
   * 表格列设置
   */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "用户账号",
      prop: "username",
      minWidth: 100
    },
    {
      label: "用户昵称",
      prop: "nickname",
      minWidth: 100
    },
    {
      label: "所属部门",
      prop: "department_name",
      minWidth: 100
    },
    {
      label: "编码",
      prop: "code",
      formatter: ({ code }) => code.replace(/(\d{2})/g, "$1.").slice(0, -1)
    },
    {
      label: "编码描述",
      prop: "description"
    },
    {
      label: "审核状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={getStatusTag(row.status)}>
          {getStatusTagText(row.status)}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      prop: "create_time",
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];
  /**
   * 初次查询
   */
  const onSearch = async () => {
    loading.value = true;
    const res = await getCodeImportListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      description: form.description,
      code: form.code,
      status: form.status,
      username: form.username,
      department_id: form.department_id,
      nickname: form.nickname,
      startTime: form.timeRange[0] ? form.timeRange[0] : null,
      endTime: form.timeRange[1] ? form.timeRange[1] : null
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
      pagination.pageSize = res.data.pageSize;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
    loading.value = false;
  };
  /**
   * 重置表单
   * @param formEl 表单ref
   * @returns
   */
  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  /**
   * 处理删除
   * @param row
   */
  const handleDelete = async (row: CodeImportInfo) => {
    const res = await deleteCodeImportAPI(row.id);
    if (res.success) {
      onSearch();
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /**
   * 处理每页数量变化
   */
  const handleSizeChange = async (val: number) => {
    const res = await getCodeImportListAPI({
      page: pagination.currentPage,
      pageSize: val,
      description: form.description,
      code: form.code,
      status: form.status,
      username: form.username,
      department_id: form.department_id,
      nickname: form.nickname,
      startTime: form.timeRange[0] ? form.timeRange[0] : null,
      endTime: form.timeRange[1] ? form.timeRange[1] : null
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
      pagination.pageSize = res.data.pageSize;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };

  /**
   * 处理页码变化
   * @param val
   */
  const handleCurrentChange = async (val: number) => {
    const res = await getCodeImportListAPI({
      page: val,
      pageSize: pagination.pageSize,
      description: form.description,
      code: form.code,
      status: form.status,
      username: form.username,
      department_id: form.department_id,
      nickname: form.nickname,
      startTime: form.timeRange[0] ? form.timeRange[0] : null,
      endTime: form.timeRange[1] ? form.timeRange[1] : null
    });
    if (res.code === 200) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
      pagination.pageSize = res.data.pageSize;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /** 当CheckBox选择项发生变化时会触发该事件 */
  const handleSelectionChange = async (val: any) => {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  };

  /** 取消选择 */
  const onSelectionCancel = async () => {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  };
  /**
   * 批量删除
   */
  const onbatchDel = async () => {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const res = await deleteCodeImportListAPI({
      ids: getKeyList(curSelected, "id")
    });
    if (res.success) {
      message(res.msg, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    } else {
      message(res.msg, { type: "error", duration: 5000 });
    }
  };
  const openDialog = async (title = "新增", row?: CodeImportInfo) => {
    addDialog({
      title: `${title}编码项`,
      props: {
        formInline: {
          way: title,
          description: row?.description ?? "",
          code: row?.code ?? "",
          status: row?.status ?? 3,
          user_id: row?.user_id ?? "",
          username: row?.username ?? "",
          nickname: row?.nickname ?? "",
          department_id: row?.department_id ?? "",
          department_name: row?.department_name ?? "",
          id: row?.id ?? "",
          create_time: row?.create_time ?? "",
          update_time: row?.update_time ?? ""
        }
      },
      width: "45%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          formInline: {
            way: title,
            description: row?.description ?? "",
            code: row?.code ?? "",
            status: row?.status ?? 3,
            user_id: row?.user_id ?? "",
            username: row?.username ?? "",
            nickname: row?.nickname ?? "",
            department_id: row?.department_id ?? "",
            department_name: row?.department_name ?? "",
            id: row?.id ?? "",
            create_time: row?.create_time ?? "",
            update_time: row?.update_time ?? ""
          },
          ref: formRef
        }),
      beforeSure: async (done, {}) => {
        const FormData = formRef.value.newFormInline;
        let form = {
          description: FormData.description ?? "",
          code: FormData.code ?? ""
        };
        if (title === "新增") {
          const res = await postAddCodeAPI(form);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        } else {
          const res = await putUpdateCodeImportAPI(form, row.id);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        }
      }
    });
  };
  /**下载模版文件 */
  const onDownloadTemplate = async () => {
    try {
      const blob = await getCodeTemplateAPI();

      // 生成下载链接
      // @ts-ignore
      const url = URL.createObjectURL(blob);

      // 创建 <a> 元素并触发下载
      const link = document.createElement("a");
      link.href = url;
      link.download = "上传模版.xlsx"; // 设置下载文件名，确保后缀名正确
      document.body.appendChild(link); // 将 <a> 元素添加到 DOM 中
      link.click(); // 模拟点击下载

      // 清理 URL 对象
      URL.revokeObjectURL(url);
      document.body.removeChild(link); // 移除 <a> 元素
    } catch (error) {
      console.error("下载模板失败:", error);
    }
  };
  /** 上传文件前 */
  const beforeUpload = async file => {
    const isExcel =
      file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || // xlsx
      file.type === "application/vnd.ms-excel" || // xls
      file.name.endsWith(".xlsx") || // 兼容部分浏览器
      file.name.endsWith(".xls"); // 兼容部分浏览器

    // const maxSize = 20 * 1024 * 1024; // 20MB 限制

    if (!isExcel) {
      message("只能上传 xlsx 或 xls 文件!", { type: "error" });
      return false;
    }
    /*
    if (file.size > maxSize) {
      message("文件大小应在 20MB 以内!", { type: "error" });
      return false;
    }
      */

    return true;
  };

  /**处理文件上传 */
  const handleUpload = async () => {
    if (fileList.value.length === 0) {
      message("请先上传文件！", { type: "error", duration: 5000 });
      return;
    }
    uploadStatus.value = true;
    for (const file of fileList.value) {
      if (file.status === "success") {
        const data = await getAddCodeAPI(fileId.value);
        if (data.success) {
          message("导入成功！", { type: "success" });
          await onSearch();
        }
        continue;
      }
      try {
        const res = await postUploadFileAPI({
          file: file.raw
        });
        if (res.success) {
          file.status = "success";
          fileId.value = res.data.id;
          message(`${res.data.name}上传成功！`, { type: "success" });
          fileIds.value.push(res.data);
          const data = await getAddCodeAPI(fileId.value);
          if (data.success) {
            message(`导入成功！`, { type: "success" });
            await onSearch();
          }
        } else {
          file.status = "fail";
        }
      } catch (error) {
        console.error(error);
      }
    }
    uploadStatus.value = false;
  };
  /**移除文件 */
  const beforeRemove: UploadProps["beforeRemove"] = async uploadFile => {
    return ElMessageBox.confirm(`是否移除 ${uploadFile.name} ?`).then(
      async () => {
        if (uploadFile.status === "success") {
          const fileId = fileIds.value.filter(
            item => item.filename === uploadFile.name
          )[0]["fileId"];
          const res = await deleteFileAPI(fileId);
          if (res.code === 200) {
            message(res.msg, { type: "success" });
            return true;
          } else {
            message(res.msg, { type: "error" });
            return false;
          }
        } else {
          return true;
        }
      },
      () => false
    );
  };
  /**部门列表 */
  const departments = ref<DepartmentInfo[]>([]);
  /**获取部门列表 */
  const getDepartments = async () => {
    const res = await getDepartmentListAPI({ page: 1, pageSize: 9999 });
    if (res.success) {
      departments.value = formatHigherOptions(
        handleTree(res.data.result, "id", "parent_id")
      );
    } else {
      departments.value = [];
    }
  };
  const formatHigherOptions = (treeList: any) => {
    // 根据返回数据的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;
  };
  /** 处理审核 */
  const handleAudit = async (row: CodeImportInfo) => {
    addDialog({
      title: `审核编码项`,
      props: {
        formInline: {
          way: "审核",
          description: row?.description ?? "",
          code: row?.code ?? "",
          status: row?.status ?? 3,
          user_id: row?.user_id ?? "",
          username: row?.username ?? "",
          nickname: row?.nickname ?? "",
          department_id: row?.department_id ?? "",
          department_name: row?.department_name ?? "",
          id: row?.id ?? "",
          create_time: row?.create_time ?? "",
          update_time: row?.update_time ?? ""
        }
      },
      width: "45%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,

      contentRenderer: () =>
        h(editForm, {
          formInline: {
            way: "审核",
            description: row?.description ?? "",
            code: row?.code ?? "",
            status: row?.status ?? 3,
            user_id: row?.user_id ?? "",
            username: row?.username ?? "",
            nickname: row?.nickname ?? "",
            department_id: row?.department_id ?? "",
            department_name: row?.department_name ?? "",
            id: row?.id ?? "",
            create_time: row?.create_time ?? "",
            update_time: row?.update_time ?? ""
          },
          ref: formRef
        }),

      footerButtons: [
        {
          label: "取消",
          type: "info",
          btnClick: ({ dialog }) => {
            console.log("取消审核");
            closeDialog(dialog.options!, dialog.index!); // ✅ 调用封装的 `closeDialog`
          }
        },
        {
          label: "通过",
          type: "success",
          popconfirm: {
            title: "确定要通过审核吗？",
            confirmButtonText: "确认",
            cancelButtonText: "取消"
          },
          btnClick: async ({ dialog }) => {
            const res = await putCodeImportAuditAPI({
              status: 1,
              ids: [row.id]
            });
            if (res.success) {
              closeDialog(dialog.options!, dialog.index!); // ✅ 调用封装的 `closeDialog`
              await onSearch();
            }
            message(res.msg, { type: res.success ? "success" : "error" });
          }
        },
        {
          label: "不通过",
          type: "danger",
          popconfirm: {
            title: "确定要驳回审核吗？",
            confirmButtonText: "确认",
            cancelButtonText: "取消"
          },
          btnClick: async ({ dialog }) => {
            const res = await putCodeImportAuditAPI({
              status: 2,
              ids: [row.id]
            });
            if (res.success) {
              closeDialog(dialog.options!, dialog.index!); // ✅ 调用封装的 `closeDialog`
              await onSearch();
            }
            message(res.msg, { type: res.success ? "success" : "error" });
          }
        }
      ]
    });
  };
  /**批量通过 */
  const onbatchAgree = async () => {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const res = await putCodeImportAuditAPI({
      status: 1,
      ids: getKeyList(curSelected, "id")
    });
    if (res.success) {
      message(res.msg, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    } else {
      message(res.msg, { type: "error", duration: 5000 });
    }
  };
  /**批量驳回 */
  const onbatchDisagree = async () => {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const res = await putCodeImportAuditAPI({
      status: 2,
      ids: getKeyList(curSelected, "id")
    });
    if (res.success) {
      message(res.msg, {
        type: "success"
      });
    }
  };

  /**
   * 页面加载执行
   */
  onMounted(async () => {
    await onSearch();
    await getDepartments();
  });
  return {
    form,
    dataList,
    loading,
    pagination,
    columns,
    selectedNum,
    showUploadArea,
    departments,
    fileIds,
    fileList,
    uploadStatus,
    beforeUpload,
    handleUpload,
    beforeRemove,
    openDialog,
    onSearch,
    resetForm,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    onbatchDel,
    onDownloadTemplate,
    handleAudit,
    onbatchDisagree,
    onbatchAgree
  };
};
