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

const defaultOperationLogRequest: OperationLogPageRequest = {
  pageNumber: 1,
  pageSize: DEFAULT_PAGE_SIZE,
  queryParam: {
    operatorName: '',
    realName: '',
    platform: '',
    module: '',
    operatorType: '',
    startTime: '',
    endTime: '',
    date: '',
    queryType: '',
    queryTypeContent: '',
  },
};

export default function useOperationLogRequest() {
  const requestParams = reactive<OperationLogPageRequest>(cloneDeep(defaultOperationLogRequest));
  const operationLogList = shallowRef<OperationLogItem[]>([]);
  const total = ref(0);
  const loading = ref(false);

  const queryOperationLogPage = 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 queryOperationLogList(requestParams);
      operationLogList.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, defaultOperationLogRequest);
  };

  return {
    requestParams,
    total,
    loading,
    operationLogList,
    queryOperationLogPage,
    resetRequestParams,
  };
}
