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 } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { CodeInfo } from "types/code";
import {
  deleteCodeAPI,
  deleteCodeListAPI,
  getAddCodeAPI,
  getCodeListAPI,
  getCodeTemplateAPI,
  postAddCodeAPI,
  putUpdateCodeAPI
} from "@/api/code";
import { getKeyList } from "@pureadmin/utils";
import {
  ElMessageBox,
  type UploadProps,
  type UploadUserFile
} from "element-plus";
import { deleteFileAPI, postUploadFileAPI } from "@/api/file";

export const useCode = (tableRef: Ref) => {
  /**
   * 查询表单
   */
  const form = reactive({
    code: "",
    description: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref(null);
  /**
   * 数据列表
   */
  const dataList = ref<CodeInfo[]>([]);
  /**
   * 加载状态
   */
  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 columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "编码",
      prop: "code",
      formatter: ({ code }) => code.replace(/(\d{2})/g, "$1.").slice(0, -1)
    },
    {
      label: "编码描述",
      prop: "description"
    },
    {
      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 getCodeListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      description: form.description,
      code: form.code
    });
    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: CodeInfo) => {
    const res = await deleteCodeAPI(row.id);
    if (res.success) {
      onSearch();
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /**
   * 处理每页数量变化
   */
  const handleSizeChange = async (val: number) => {
    const res = await getCodeListAPI({
      page: pagination.currentPage,
      pageSize: val,
      description: form.description,
      code: form.code
    });
    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 getCodeListAPI({
      page: val,
      pageSize: pagination.pageSize,
      description: form.description,
      code: form.code
    });
    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 deleteCodeListAPI({
      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?: CodeInfo) => {
    addDialog({
      title: `${title}编码项`,
      props: {
        formInline: {
          title: title,
          description: row?.description ?? "",
          code: row?.code ?? ""
        }
      },
      width: "45%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          formInline: {
            description: row?.description ?? "",
            code: row?.code ?? ""
          },
          ref: formRef
        }),
      beforeSure: async (done, {}) => {
        const FormData = formRef.value.newFormInline;
        let form = {
          description: FormData.name ?? "",
          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 putUpdateCodeAPI(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
    );
  };

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