import dayjs from "dayjs";
import Detail from "./components/form.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { getKeyList } from "@pureadmin/utils";
import { getUserOperationsAPI } from "@/api/monitor";
import { usePublicHooks } from "@/views/system/hooks";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, h } from "vue";
import type { OperationLogInfo } from "types/monitor";

export function useOperation(tableRef: Ref) {
  const form = reactive({
    module: "",
    status: "",
    operatingTime: ""
  });
  const dataList = ref<OperationLogInfo[]>([]);
  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 getOperationType = (type: number) => {
    switch (type) {
      case 1:
        return "primary";
      case 2:
        return "success";
      case 3:
        return "warning";
      case 4:
        return "danger";
      case 5:
        return "success";
      case 6:
        return "primary";
      case 7:
        return "success";
      case 8:
        return "danger";
      default:
        return "info";
    }
  };
  const getOperationName = (type: number) => {
    switch (type) {
      case 1:
        return "查询";
      case 2:
        return "新增";
      case 3:
        return "修改";
      case 4:
        return "删除";
      case 5:
        return "授权";
      case 6:
        return "导出";
      case 7:
        return "导入";
      case 8:
        return "强退";
      default:
        return "其他";
    }
  };
  const getRequestType = (method: string) => {
    switch (method) {
      case "GET":
        return "primary";
      case "POST":
        return "success";
      case "PUT":
        return "warning";
      case "DELETE":
        return "danger";
      case "PATCH":
        return "info";
      default:
        return "info";
    }
  };
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "操作人员账号",
      prop: "operator_name",
      minWidth: 100
    },
    {
      label: "操作人员昵称",
      prop: "operator_nickname",
      minWidth: 100
    },
    {
      label: "操作名称",
      prop: "operation_name",
      minWidth: 100
    },
    {
      label: "操作类型",
      prop: "operation_type",
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={getOperationType(row.operation_type)}>
          {getOperationName(row.operation_type)}
        </el-tag>
      )
    },
    {
      label: "操作IP",
      prop: "host"
    },
    {
      label: "操作地点",
      prop: "location"
    },
    {
      label: "请求方法",
      prop: "request_method",
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={getRequestType(row.request_method)}>
          {row.request_method}
        </el-tag>
      )
    },
    {
      label: "请求路径",
      prop: "request_path"
    },
    {
      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: "os",
      hide: true
    },
    {
      label: "浏览器类型",
      prop: "browser",
      hide: true
    },
    {
      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 getUserOperationsAPI({
      page: pagination.currentPage,
      pageSize: val
    });
    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 getUserOperationsAPI({
      page: val,
      pageSize: pagination.pageSize
    });
    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 onbatchDel = () => {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除序号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  };

  /** 清空日志 */
  const clearAll = async () => {
    // 根据实际业务，调用接口删除所有日志数据
    message("已删除所有日志数据", {
      type: "success"
    });
    await onSearch();
  };

  const onSearch = async () => {
    loading.value = true;
    const res = await getUserOperationsAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    });
    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();
  };

  const onDetailHandle = () => {
    addDialog({
      title: `详情`,
      props: {},
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(Detail, {}),
      beforeSure: (done, {}) => {
        done();
      }
    });
  };

  onMounted(async () => {
    await onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    clearAll,
    resetForm,
    onbatchDel,
    getOperationName,
    onDetailHandle,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
