import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getKeyList, handleTree } from "@pureadmin/utils";
import {
  deleteUserOnlineAPI,
  getUserLoginLogAPI,
  deleteUserLoginLogAPI,
  deleteUserOnlineListAPI,
  deleteUserLoginLogListAPI
} 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";
import type { DepartmentInfo } from "types/system";
import { getDepartmentListAPI } from "@/api/system";

export const useLogin = (tableRef: Ref) => {
  const form = reactive({
    username: "",
    nickname: "",
    status: "",
    department_id: "",
    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: "online",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} type={row.online ? "success" : ""}>
          {row.online ? "在线" : "离线"}
        </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",
      width: 200
    }
  ];

  /**
   * 当前页变化
   * @param val
   */
  const handleCurrentChange = async (val: number) => {
    const res = await getUserLoginLogAPI({
      page: val,
      pageSize: pagination.pageSize,
      department_id: form.department_id,
      status: form.status,
      username: form.username,
      nickname: form.nickname,
      startTime: form.loginTime[0] ? form.loginTime[0] : null,
      endTime: form.loginTime[1] ? form.loginTime[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;
    }
  };

  /**处理页码变化 */
  const handleSizeChange = async (val: number) => {
    const res = await getUserLoginLogAPI({
      page: pagination.currentPage,
      pageSize: val,
      department_id: form.department_id,
      status: form.status,
      username: form.username,
      nickname: form.nickname,
      startTime: form.loginTime[0] ? form.loginTime[0] : null,
      endTime: form.loginTime[1] ? form.loginTime[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;
    }
  };

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

  /** 取消选择 */
  const onSelectionCancel = () => {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  };
  /**处理删除 */
  /**
   * 处理删除
   * @param row
   */
  const handleDelete = async (row: UserLoginLogInfo) => {
    const res = await deleteUserLoginLogAPI(row.id);
    if (res.success) {
      onSearch();
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /** 批量删除 */
  const onbatchDel = async () => {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const res = await deleteUserLoginLogListAPI({
      ids: getKeyList(curSelected, "id")
    });
    if (res.success) {
      message(res.msg, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    } else {
      message(res.msg, {
        type: "error"
      });
    }
  };

  /**批量强退 */
  const onbatchForce = async () => {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const res = await deleteUserOnlineListAPI({
      ids: getKeyList(curSelected, "id")
    });
    if (res.success) {
      message(res.msg, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    } else {
      message(res.msg, {
        type: "error"
      });
    }
  };

  const onSearch = async () => {
    loading.value = true;
    const res = await getUserLoginLogAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      department_id: form.department_id,
      status: form.status,
      username: form.username,
      nickname: form.nickname,
      startTime: form.loginTime[0] ? form.loginTime[0] : null,
      endTime: form.loginTime[1] ? form.loginTime[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;
    }
    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();
    }
  };
  /**部门列表 */
  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;
  };

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

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