import dayjs from "dayjs";
import { message } from "@/utils/message";
import {
  getOperationLogList,
  getOperationLogDetail,
  deleteOperationLogBatch,
  clearAllOperationLogs,
  getOperationLogStatistics
} from "@/api/operationLog";
import type { PaginationProps } from "@pureadmin/table";
import { onMounted, reactive, ref, toRaw } from "vue";

interface SearchFormProps {
  module: string;
  username: string;
  status: number | undefined;
  startTime: string;
  endTime: string;
}

export function useOperationLog() {
  const form = reactive<SearchFormProps>({
    module: "",
    username: "",
    status: undefined,
    startTime: "",
    endTime: ""
  });
  const loading = ref(true);
  const dataList = ref([]);
  const selectedNum = ref(0);
  const statistics = ref({
    total: 0,
    success: 0,
    failed: 0,
    today: 0
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      type: "selection",
      width: 50,
      reserveSelection: true
    },
    {
      label: "日志ID",
      prop: "id",
      width: 180
    },
    {
      label: "操作模块",
      prop: "module",
      minWidth: 100
    },
    {
      label: "操作类型",
      prop: "operationType",
      minWidth: 100
    },
    {
      label: "操作人",
      prop: "adminName",
      minWidth: 100
    },
    {
      label: "请求URL",
      prop: "requestUrl",
      minWidth: 180,
      showOverflowTooltip: true
    },
    {
      label: "IP地址",
      prop: "ip",
      minWidth: 120
    },
    {
      label: "耗时(ms)",
      prop: "costTime",
      minWidth: 90
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <el-tag type={row.status === 1 ? "success" : "danger"}>
          {row.status === 1 ? "成功" : "失败"}
        </el-tag>
      )
    },
    {
      label: "操作时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      // 只添加非空的搜索条件
      if (form.module) searchParams.module = form.module;
      if (form.username) searchParams.username = form.username;
      if (form.status !== undefined) searchParams.status = form.status;
      if (form.startTime) searchParams.startTime = form.startTime;
      if (form.endTime) searchParams.endTime = form.endTime;
      
      const { data } = await getOperationLogList(searchParams);
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(data.total) || 0;
      }
    } finally {
      loading.value = false;
    }
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    pagination.currentPage = 1;
    onSearch();
  }

  function handleSelectionChange(val) {
    selectedNum.value = val.length;
  }

  async function handleBatchDelete() {
    const selectionRows = tableRef.value?.getTableRef()?.getSelectionRows() || [];
    const ids = selectionRows.map(item => item.id);
    if (ids.length === 0) {
      message("请选择要删除的日志", { type: "warning" });
      return;
    }
    const { code } = await deleteOperationLogBatch(ids);
    if (code === 0) {
      message("批量删除成功", { type: "success" });
      onSearch();
    }
  }

  async function handleClearAll() {
    const { code } = await clearAllOperationLogs();
    if (code === 0) {
      message("清空成功", { type: "success" });
      onSearch();
    }
  }

  const detailVisible = ref(false);
  const detailData = ref<any>(null);
  const detailLoading = ref(false);

  async function handleViewDetail(row) {
    detailVisible.value = true;
    detailLoading.value = true;
    try {
      const { data } = await getOperationLogDetail(row.id);
      detailData.value = data;
    } finally {
      detailLoading.value = false;
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function getStatistics() {
    const { data } = await getOperationLogStatistics();
    if (data) {
      statistics.value = data;
    }
  }

  const tableRef = ref();

  onMounted(() => {
    onSearch();
    getStatistics();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    statistics,
    pagination,
    tableRef,
    onSearch,
    resetForm,
    handleSelectionChange,
    handleBatchDelete,
    handleClearAll,
    handleViewDetail,
    handleSizeChange,
    handleCurrentChange,
    detailVisible,
    detailData,
    detailLoading
  };
}
