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

const defaultLoginLogRequest: SystemLogRequest = {
  pageNumber: 1,
  pageSize: DEFAULT_PAGE_SIZE,
  queryParam: {
    eventType: undefined,
    startTime: '',
    endTime: '',
    date: '',
  },
};

export default function useSystemLogRequest() {
  const requestParams = reactive<SystemLogRequest>(cloneDeep(defaultLoginLogRequest));
  const systemLogList = shallowRef<SystemLogItem[]>([]);
  const total = ref(0);
  const loading = ref(false);

  const querySystemLogPage = async () => {
    try {
      loading.value = true;
      const { date } = requestParams.queryParam;
      if (date && date.length > 0) {
        requestParams.queryParam.startTime = date[0] + ' 00:00:00';
        requestParams.queryParam.endTime = date[1] + ' 23:59:59';
      }

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

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

  return {
    requestParams,
    total,
    loading,
    systemLogList,
    querySystemLogPage,
    resetRequestParams,
  };
}
