import { reactive, ref, shallowRef } from 'vue';
import { LoginLogItem, LoginLogPageRequest } from '@/types/log/type';
import { DEFAULT_PAGE_SIZE } from '@/types/common/constants';
import { cloneDeep } from 'lodash-es';
import { queryLoginLogList } from '@/api/system/log';

const defaultLoginLogRequest: LoginLogPageRequest = {
  pageNumber: 1,
  pageSize: DEFAULT_PAGE_SIZE,
  queryParam: {
    userName: '',
    device: '',
    startTime: '',
    endTime: '',
    deptId: undefined,
    date: '',
    queryType: '',
    queryTypeContent: '',
  },
};

export default function useLoginLogRequest() {
  const requestParams = reactive<LoginLogPageRequest>(cloneDeep(defaultLoginLogRequest));
  const loginLogList = shallowRef<LoginLogItem[]>([]);
  const total = ref(0);
  const loading = ref(false);

  const queryLoginLogPage = async () => {
    try {
      loading.value = true;
      const { date, queryType, queryTypeContent } = requestParams.queryParam;
      Object.entries(requestParams.queryParam).forEach(([key, value]) => {
        if (value) {
          if (queryType) {
            requestParams.queryParam[queryType] = queryTypeContent;
          }
        }
      });
      if (date && date.length > 0) {
        requestParams.queryParam.startTime = date[0] + ' 00:00:00';
        requestParams.queryParam.endTime = date[1] + ' 23:59:59';
      }

      const data = await queryLoginLogList(requestParams);
      loginLogList.value = data.records;
      total.value = data.totalRow;
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  };

  const resetRequestParams = () => {
    requestParams.queryParam.startTime = '';
    requestParams.queryParam.endTime = '';
    requestParams.queryParam.queryTypeContent = '';
    requestParams.queryParam.userName = '';
    requestParams.queryParam.realName = '';
    Object.assign(requestParams, defaultLoginLogRequest);
  };

  return {
    requestParams,
    total,
    loading,
    loginLogList,
    queryLoginLogPage,
    resetRequestParams,
  };
}
