<template>
  <div class="container">
    <Breadcrumb :items="['系统管理', '操作日志']" />
    <a-card class="general-card" title=" ">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="right"
          >
            <a-row :gutter="18">
              <a-col :span="9">
                <a-form-item field="moduleType" label="模块类型">
                  <a-input
                    v-model="formModel.moduleType"
                    style="width: 360px"
                    placeholder="请输入模块类型"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item field="Time" label="时间">
                  <a-range-picker
                    show-time
                    format="YYYY-MM-DD HH:mm"
                    @ok="timeRang"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="9">
                <a-form-item field="functionType" label="功能类型">
                  <a-input
                    v-model="formModel.functionType"
                    style="width: 360px"
                    placeholder="请输入功能类型"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <a-divider style="margin-top: 0" />
      <a-row>
        <a-col :span="12">
          <a-space>
            <a-button
              type="primary"
              status="danger"
              @click="deleteLog(selectedIds)"
            >
              <template #icon><icon-delete /></template>
              批量删除
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="
            display: flex;
            align-items: center;
            justify-content: end;
            padding-bottom: 20px;
          "
        >
          <a-tooltip content="刷新">
            <div class="action-icon" @click="search">
              <icon-refresh size="18" />
            </div>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="false"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        :row-selection="rowSelection"
        v-model:selected-keys="selectedIds"
        style="margin-bottom: 40px"
        @page-change="onPageChange"
      >
        <template #makeTime="{ record }">
          {{ dayjs(record.makeTime).format('YYYY-MM-DD HH:mm') }}
        </template>
      </a-table>
      <a-pagination
        style="float: right; position: relative; right: 1px; bottom: 25px"
        :total="pagination.total"
        :size="size"
        show-total
        show-jumper
        show-page-size
        @page-size-change="onSizeChange"
        @change="onPageChange"
      />
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, onMounted, reactive, ref, watch } from 'vue';
  import useLoading from '@/hooks/loading';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import useTableOption from '@/hooks/table-option';
  import usePagination from '@/hooks/pagination';
  import dayjs from 'dayjs';
  import { LogsRecord, queryLogList, deleteLogs } from '@/api/log';
  import { Message } from '@arco-design/web-vue';

  const generateFormModel = () => {
    return {
      moduleType: '',
      functionType: '',
      publishTimeBegin: '',
      publishTimeEnd: '',
    };
  };

  const { pagination, setPagination } = usePagination();
  const { loading, setLoading } = useLoading(true);
  const renderData = ref<any[]>([]);
  const formModel = ref(generateFormModel());
  const selectedIds = ref<number[]>([]);
  const { cloneColumns, size, deepClone } = useTableOption();

  const columns = computed<TableColumnData[]>(() => [
    {
      title: '模块类型',
      dataIndex: 'moduleType',
    },
    {
      title: '功能类型',
      dataIndex: 'functionType',
    },
    {
      title: '操作时间',
      dataIndex: 'makeTime',
      slotName: 'makeTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '操作内容',
      dataIndex: 'content',
    },
    // {
    //   title: '操作',
    //   dataIndex: 'operation',
    // },
  ]);
  const rowSelection = {
    type: 'checkbox',
    showCheckedAll: true, // 默认选中的行 ID
  };


  // 获取日志列表
  const fetchData = async (params = { size: 10, current: 1 }) => {
    setLoading(true);
    try {
      const res: any = await queryLogList(params);
      renderData.value = res.data.records;
      setPagination(res.data);
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  // 查询
  const search = () => {
    fetchData({
      ...pagination.value,
      ...formModel.value,
    } as unknown as LogsRecord);
    selectedIds.value = [];
  };

  // 分页发生改变
  const onPageChange = (current: number) => {
    pagination.value.page = current;
    pagination.value.current = current;
    search();
  };

  // 时间范围
  const timeRang = (dateString: string[]) => {
    // eslint-disable-next-line prefer-destructuring
    formModel.value.publishTimeBegin = dateString[0];
    // eslint-disable-next-line prefer-destructuring
    formModel.value.publishTimeEnd = dateString[1];
  };

  // 数据条数改变
  const onSizeChange = (Size: number) => {
    pagination.value.size = Size;
    search();
  };

  // 重置
  const reset = () => {
    formModel.value = generateFormModel();
  };

  // 批量删除日志
  const deleteLog = async (ids: number[]) => {
    if (ids.length === 0) {
      // 如果没有选中任何日志，提示用户
      Message.warning('请选择要删除的日志');
      return;
    }
    try {
      // 调用批量删除日志的接口
      await deleteLogs(ids);
      Message.success('日志删除成功');
      // 删除成功后刷新日志列表
      search();
    } catch (error) {
      Message.error('日志删除失败');
    }
  };

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

  watch(() => columns.value, deepClone, { deep: true, immediate: true });
</script>
