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 { CodeFeedbackInfo } from "types/code";
import {
  deleteCodeFeedbackAPI,
  deleteCodeFeedbackListAPI,
  getCodeFeedbackListAPI,
  postAddCodeFeedbackAPI,
  putCodeFeedbackAuditAPI,
  putUpdateCodeFeedbackAPI
} from "@/api/code";
import { getKeyList, handleTree } from "@pureadmin/utils";
import type { DepartmentInfo } from "types/system";
import { getDepartmentListAPI } from "@/api/system";
import { transformI18n } from "@/plugins/i18n";

export const useCode = (tableRef: Ref) => {
  /**
   * 查询表单
   */
  const form = reactive({
    code: "",
    feedback_code: "",
    feedback_description: "",
    username: "",
    department_id: "",
    nickname: "",
    timeRange: [null, null],
    status: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref(null);
  /**
   * 数据列表
   */
  const dataList = ref<CodeFeedbackInfo[]>([]);
  /**
   * 加载状态
   */
  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 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: transformI18n("menus.review.tag.account"),
      prop: "username",
      minWidth: 100
    },
    {
      label: transformI18n("menus.review.tag.userName"),
      prop: "nickname",
      minWidth: 100
    },
    {
      label: transformI18n("menus.review.tag.department"),
      prop: "department_name",
      minWidth: 100
    },
    {
      label: transformI18n("menus.review.tag.htsCode"),
      prop: "code",
      formatter: ({ code }) =>
        code ? code.replace(/(\d{2})/g, "$1.").slice(0, -1) : ""
    },
    {
      label: transformI18n("menus.review.tag.description"),
      prop: "description"
    },
    {
      label: transformI18n("menus.review.tag.feedbackHtsCode"),
      prop: "feedback_code"
    },
    {
      label: transformI18n("menus.review.tag.feedbackDescription"),
      prop: "feedback_description"
    },
    {
      label: transformI18n("menus.review.tag.status"),
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={getStatusTag(row.status)}>
          {getStatusTagText(row.status)}
        </el-tag>
      )
    },
    {
      label: transformI18n("menus.import.tag.loadTime"),
      prop: "create_time",
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: transformI18n("buttons:Operation"),
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];
  /**
   * 初次查询
   */
  const onSearch = async () => {
    loading.value = true;
    const res = await getCodeFeedbackListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      feedback_code: form.feedback_code,
      feedback_description: form.feedback_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: CodeFeedbackInfo) => {
    const res = await deleteCodeFeedbackAPI(row.id);
    if (res.success) {
      onSearch();
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /**
   * 处理每页数量变化
   */
  const handleSizeChange = async (val: number) => {
    const res = await getCodeFeedbackListAPI({
      page: pagination.currentPage,
      pageSize: val,
      feedback_code: form.feedback_code,
      feedback_description: form.feedback_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 getCodeFeedbackListAPI({
      page: val,
      pageSize: pagination.pageSize,
      feedback_code: form.feedback_code,
      feedback_description: form.feedback_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 deleteCodeFeedbackListAPI({
      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?: CodeFeedbackInfo) => {
    addDialog({
      title: `${title}编码项`,
      props: {
        formInline: {
          way: title,
          feedback_code: row?.feedback_code ?? "",
          feedback_description: row?.feedback_description ?? "",
          code_id: row?.code_id ?? "",
          code: row?.code ?? "",
          description: row?.description ?? "",
          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,
            feedback_description: row?.feedback_description ?? "",
            feedback_code: row?.feedback_code ?? "",
            code_id: row?.code_id ?? "",
            code: row?.code ?? "",
            description: row?.description ?? "",
            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 = {
          feedback_description: FormData.feedback_description ?? "",
          feedback_code: FormData.feedback_code ?? "",
          code_id: FormData.code_id ?? ""
        };
        if (title === "新增") {
          const res = await postAddCodeFeedbackAPI(form);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        } else {
          const res = await putUpdateCodeFeedbackAPI(form, row.id);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        }
      }
    });
  };

  /**部门列表 */
  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: CodeFeedbackInfo) => {
    addDialog({
      title: `审核编码项`,
      props: {
        formInline: {
          way: "审核",
          feedback_code: row?.feedback_code ?? "",
          feedback_description: row?.feedback_description ?? "",
          code_id: row?.code_id ?? "",
          code: row?.code ?? "",
          description: row?.description ?? "",
          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: "审核",
            feedback_code: row?.feedback_code ?? "",
            feedback_description: row?.feedback_description ?? "",
            code_id: row?.code_id ?? "",
            code: row?.code ?? "",
            description: row?.description ?? "",
            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 putCodeFeedbackAuditAPI({
              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 putCodeFeedbackAuditAPI({
              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 putCodeFeedbackAuditAPI({
      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 putCodeFeedbackAuditAPI({
      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,
    departments,
    openDialog,
    onSearch,
    resetForm,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    onbatchDel,
    handleAudit,
    onbatchDisagree,
    onbatchAgree
  };
};
