import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getKeyList } from "@pureadmin/utils";
import { deleteUserOnlineAPI, getUserLoginLogAPI } from "@/api/monitor";
import { usePublicHooks } from "@/views/system/hooks";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted } from "vue";
import type { UserLoginLogInfo } from "types/monitor";

export const useLogin = (tableRef: Ref) => {
  const form = reactive({
    username: "",
    status: "",
    loginTime: ""
  });
  /**
   * 表格数据
   */
  const dataList = ref<UserLoginLogInfo[]>([]);
  /**
   * 表格加载状态
   */
  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: "session_id",
      minWidth: 100
    },
    {
      label: "用户账号",
      prop: "username",
      minWidth: 100
    },
    {
      label: "用户昵称",
      prop: "user_nickname",
      minWidth: 100
    },
    {
      label: "所属部门",
      prop: "department_name",
      minWidth: 100
    },
    {
      label: "登录 IP",
      prop: "login_ip",
      minWidth: 140
    },
    {
      label: "登录地点",
      prop: "login_location",
      minWidth: 140
    },
    {
      label: "操作系统",
      prop: "os",
      minWidth: 100
    },
    {
      label: "浏览器类型",
      prop: "browser",
      minWidth: 100
    },
    {
      label: "登录状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "成功" : "失败"}
        </el-tag>
      )
    },
    {
      label: "登录时间",
      prop: "login_time",
      minWidth: 180,
      formatter: ({ login_time }) =>
        dayjs(login_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  /**
   * 当前页变化
   * @param val
   */
  const handleCurrentChange = async (val: number) => {
    const res = await getUserLoginLogAPI({
      page: val,
      pageSize: pagination.pageSize
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
    }
  };

  /**处理页码变化 */
  const handleSizeChange = async (val: number) => {
    const res = await getUserLoginLogAPI({
      page: pagination.currentPage,
      pageSize: val
    });
    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 getUserLoginLogAPI({
      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 deleteUserHandle = async (id: string) => {
    const res = await deleteUserOnlineAPI(id);
    if (res.success) {
      message("账号强退成功！", {
        type: "success"
      });
      onSearch();
    }
  };

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

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