import dayjs from "dayjs";
import timezone from "dayjs/plugin/timezone"; // 时区插件
import utc from "dayjs/plugin/utc"; // UTC 插件

dayjs.extend(utc);
dayjs.extend(timezone);
import { usePublicHooks } from "@/views/system/hooks";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted } from "vue";
import type { QueryCodeLogInfo } from "types/code";
import * as XLSX from "xlsx";
import { getCodeLogListAllAPI, getCodeLogListAPI } from "@/api/code";
import { message } from "@/utils/message";
import { cloneDeep, getKeyList } from "@pureadmin/utils";

export const useQueryLog = (tableRef: Ref) => {
  /**查询表单 */
  const form = reactive({
    timeRange: [null, null]
  });
  /**数据列表 */
  const dataList = ref<QueryCodeLogInfo[]>([]);
  /**等待状态 */
  const loading = ref(true);
  const selectedNum = ref(0);
  const { tagStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 30, 40, 50]
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "查询ID",
      prop: "id"
    },
    {
      label: "操作人员账号",
      prop: "operator_name",
      minWidth: 100
    },
    {
      label: "操作人员昵称",
      prop: "operator_nickname",
      minWidth: 100
    },
    {
      label: "查询统计",
      prop: "query_count"
    },
    {
      label: "结果统计",
      prop: "result_count"
    },
    {
      label: "查询耗时",
      prop: "cost_time",
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.cost_time < 1000 ? "success" : "warning"}
          effect="plain"
        >
          {row.cost_time.toFixed(2)} ms
        </el-tag>
      )
    },
    {
      label: "查询状态",
      prop: "status",
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "成功" : "失败"}
        </el-tag>
      )
    },
    {
      label: "操作时间",
      prop: "operation_time",
      minWidth: 180,
      formatter: ({ operation_time }) =>
        dayjs(operation_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 100,
      slot: "operation"
    }
  ];
  const handleSizeChange = async (val: number) => {
    const res = await getCodeLogListAPI({
      page: pagination.currentPage,
      pageSize: val,
      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;
    }
  };
  const handleCurrentChange = async (val: number) => {
    const res = await getCodeLogListAPI({
      page: val,
      pageSize: pagination.pageSize,
      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;
    }
  };

  /** 当CheckBox选择项发生变化时会触发该事件 */
  const handleSelectionChange = val => {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  };

  /** 取消选择 */
  const onSelectionCancel = () => {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  };
  const onSearch = async () => {
    loading.value = true;
    const res = await getCodeLogListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      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;
    }

    setTimeout(() => {
      loading.value = false;
    }, 500);
  };

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  /** 日期、时间选择器快捷选项，常搭配 [DatePicker](https://element-plus.org/zh-CN/component/date-picker.html) 和 [DateTimePicker](https://element-plus.org/zh-CN/component/datetime-picker.html) 的`shortcuts`属性使用 */
  const getPickerShortcuts = (): Array<{
    text: string;
    value: Date | Function;
  }> => {
    return [
      {
        text: "今天",
        value: () => {
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          const todayEnd = new Date();
          todayEnd.setHours(23, 59, 59, 999);
          return [today, todayEnd];
        }
      },
      {
        text: "昨天",
        value: () => {
          const yesterday = new Date();
          yesterday.setDate(yesterday.getDate() - 1);
          yesterday.setHours(0, 0, 0, 0);
          const yesterdayEnd = new Date();
          yesterdayEnd.setDate(yesterdayEnd.getDate() - 1);
          yesterdayEnd.setHours(23, 59, 59, 999);
          return [yesterday, yesterdayEnd];
        }
      },
      {
        text: "前天",
        value: () => {
          const beforeYesterday = new Date();
          beforeYesterday.setDate(beforeYesterday.getDate() - 2);
          beforeYesterday.setHours(0, 0, 0, 0);
          const beforeYesterdayEnd = new Date();
          beforeYesterdayEnd.setDate(beforeYesterdayEnd.getDate() - 2);
          beforeYesterdayEnd.setHours(23, 59, 59, 999);
          return [beforeYesterday, beforeYesterdayEnd];
        }
      },
      {
        text: "本周",
        value: () => {
          const today = new Date();
          const startOfWeek = new Date(
            today.getFullYear(),
            today.getMonth(),
            today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1)
          );
          startOfWeek.setHours(0, 0, 0, 0);
          const endOfWeek = new Date(
            startOfWeek.getTime() +
              6 * 24 * 60 * 60 * 1000 +
              23 * 60 * 60 * 1000 +
              59 * 60 * 1000 +
              59 * 1000 +
              999
          );
          return [startOfWeek, endOfWeek];
        }
      },
      {
        text: "上周",
        value: () => {
          const today = new Date();
          const startOfLastWeek = new Date(
            today.getFullYear(),
            today.getMonth(),
            today.getDate() -
              today.getDay() -
              7 +
              (today.getDay() === 0 ? -6 : 1)
          );
          startOfLastWeek.setHours(0, 0, 0, 0);
          const endOfLastWeek = new Date(
            startOfLastWeek.getTime() +
              6 * 24 * 60 * 60 * 1000 +
              23 * 60 * 60 * 1000 +
              59 * 60 * 1000 +
              59 * 1000 +
              999
          );
          return [startOfLastWeek, endOfLastWeek];
        }
      },
      {
        text: "本月",
        value: () => {
          const today = new Date();
          const startOfMonth = new Date(
            today.getFullYear(),
            today.getMonth(),
            1
          );
          startOfMonth.setHours(0, 0, 0, 0);
          const endOfMonth = new Date(
            today.getFullYear(),
            today.getMonth() + 1,
            0
          );
          endOfMonth.setHours(23, 59, 59, 999);
          return [startOfMonth, endOfMonth];
        }
      },
      {
        text: "上个月",
        value: () => {
          const today = new Date();
          const startOfLastMonth = new Date(
            today.getFullYear(),
            today.getMonth() - 1,
            1
          );
          startOfLastMonth.setHours(0, 0, 0, 0);
          const endOfLastMonth = new Date(
            today.getFullYear(),
            today.getMonth(),
            0
          );
          endOfLastMonth.setHours(23, 59, 59, 999);
          return [startOfLastMonth, endOfLastMonth];
        }
      },
      {
        text: "本年",
        value: () => {
          const today = new Date();
          const startOfYear = new Date(today.getFullYear(), 0, 1);
          startOfYear.setHours(0, 0, 0, 0);
          const endOfYear = new Date(today.getFullYear(), 11, 31);
          endOfYear.setHours(23, 59, 59, 999);
          return [startOfYear, endOfYear];
        }
      }
    ];
  };
  /**导出为excel */
  const exportToExcel = (dataList: QueryCodeLogInfo[], filename: string) => {
    if (dataList.length) {
      const headers = [
        "序号",
        "查询批次ID",
        "查询人ID",
        "查询人账号",
        "查询人昵称",
        "查询人部门ID",
        "查询人部门",
        "查询文本(总)",
        "查询统计",
        "结果统计",
        "查询状态",
        "耗时(毫秒)",
        "操作时间",
        "待查询文本ID",
        "待查询文本",
        "查询结果状态"
      ];
      for (let i = 1; i <= 5; i++) {
        headers.push(
          `匹配结果ID${i}`,
          `匹配编码${i}`,
          `匹配结果${i}`,
          `匹配率(百分比)${i}`
        );
      }
      const data = [];
      let index = 1;
      for (const jsonData of dataList) {
        const batchId = jsonData.id;
        const opeartion_id = jsonData.operator_id;
        const opeartion_name = jsonData.operator_name;
        const opeartion_nickname = jsonData.operator_nickname;
        const department_id = jsonData.department_id;
        const department_name = jsonData.department_name;
        const queryText = jsonData.request_params;
        const queryCount = jsonData.query_count;
        const resultCount = jsonData.result_count;
        const status = jsonData.status === 1 ? "成功" : "失败";
        const costTime = jsonData.cost_time;
        const operationTime = jsonData.operation_time;
        jsonData.response_result = JSON.parse(
          jsonData.response_result.replace(/'/g, '"').replace(/None/g, "null")
        );
        // @ts-ignore
        jsonData.response_result.forEach(response => {
          const queryId = response.id;
          const queryTextDetail = response.query_text;
          const queryStatus = response.status === 1 ? "成功" : "失败";

          const row = [
            index++,
            batchId,
            opeartion_id,
            opeartion_name,
            opeartion_nickname,
            department_id,
            department_name,
            queryText,
            queryCount,
            resultCount,
            status,
            costTime,
            operationTime,
            queryId,
            queryTextDetail,
            queryStatus
          ];

          for (let i = 0; i < 5; i++) {
            if (i < response.result_text.length) {
              const match = response.result_text[i];
              row.push(
                match.id,
                match.code,
                match.description,
                match.match_rate
              );
            } else {
              row.push("", "", "", "");
            }
          }
          data.push(row);
        });
      }
      const worksheet = XLSX.utils.aoa_to_sheet([headers, ...data]);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Query Results");
      XLSX.writeFile(workbook, `${filename}.xlsx`);
      message("导出成功！", { type: "success" });
    }
  };
  /**导出所有查询结果 */
  const onExportQueryAll = async () => {
    const res = await getCodeLogListAllAPI({
      startTime: form.timeRange[0] ? form.timeRange[0] : null,
      endTime: form.timeRange[1] ? form.timeRange[1] : null
    });
    if (res.success) {
      exportToExcel(res.data.result, "全部查询结果");
    }
  };
  /**批量导出 */
  const onbatchExport = async () => {
    // 获取当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();

    const ids = getKeyList(curSelected, "id");

    let data = cloneDeep(dataList.value); // 拷贝的数据

    let selecteList = data.filter((item: QueryCodeLogInfo) =>
      ids.includes(item.id)
    ); // 筛选出选中的数据

    exportToExcel(selecteList, "查询结果");
  };
  onMounted(async () => {
    await onSearch();
  });
  return {
    form,
    loading,
    dataList,
    columns,
    selectedNum,
    pagination,
    onSearch,
    getPickerShortcuts,
    resetForm,
    handleCurrentChange,
    handleSizeChange,
    handleSelectionChange,
    onSelectionCancel,
    onExportQueryAll,
    onbatchExport
  };
};
