<script setup lang="tsx">
import { ref } from 'vue';
import { type DataTableSortState, NButton, NPopconfirm, NTag } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useDownLoadFile } from '@/hooks/common/download';
import { $t } from '@/locales';
import { getDicts } from '@/service/api/system/dict';
import { useAppStore } from '@/store/modules/app';
import { cleanOperlog, delOperlog, list } from '@/service/api/monitor/operlog';
import OperlogSearch from '@/views/system/log_oper-log/modules/operlog-search.vue';
import OperlogView from '@/views/system/log_oper-log/modules/operlog-view.vue';

defineOptions({
  name: 'OperLog'
});

const appStore = useAppStore();
const { loading: exportLoading, downLoadExcelPost } = useDownLoadFile();

const typeOptions = ref<Api.SystemManage.DictInfo[]>([]);
const statusOptions = ref<Api.SystemManage.DictInfo[]>([]);
getDicts('sys_oper_type').then(response => {
  if (!response.error) {
    typeOptions.value = response.data as Api.SystemManage.DictInfo[];
  }
});
getDicts('sys_common_status').then(response => {
  if (!response.error) {
    statusOptions.value = response.data as Api.SystemManage.DictInfo[];
  }
});

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: list,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    operName: null,
    businessType: null,
    status: null,
    params: null,
    orderByColumn: null,
    isAsc: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'operId',
      title: '日志编号',
      align: 'center'
    },
    {
      key: 'title',
      title: '系统模块',
      align: 'center'
    },
    {
      key: 'businessType',
      title: '操作类型',
      align: 'center',
      render: row => {
        if (row.businessType === null) {
          return null;
        }
        const obj = typeOptions.value.find(item => item.dictValue === row.businessType.toString());
        return <NTag type="success">{obj?.dictLabel}</NTag>;
      }
    },
    {
      key: 'requestMethod',
      title: '请求方式',
      align: 'center'
    },
    {
      key: 'operName',
      title: '操作人员',
      align: 'center',
      sorter: true
    },
    {
      key: 'operIp',
      title: '操作地址',
      align: 'center'
    },
    {
      key: 'operLocation',
      title: '请求方式',
      align: 'center'
    },
    {
      key: 'status',
      title: '操作类型',
      align: 'center',
      render: row => {
        if (row.status === null) {
          return null;
        }
        const obj = statusOptions.value.find(item => item.dictValue === row.status.toString());
        return <NTag type={obj?.listClass === 'danger' ? 'error' : obj?.listClass}>{obj?.dictLabel}</NTag>;
      }
    },
    {
      key: 'operTime',
      title: '操作时间',
      align: 'center',
      sorter: true
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => handleView(row)}>
            详细
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.operId)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const { drawerVisible, editingData, checkedRowKeys, onDeleted, onBatchDeleted } = useTableOperate(data, getData);

// 单个删除
function handleDelete(id: Api.SystemManage.Operlog['operId']) {
  delOperlog([id]).then(() => {
    if (!res.error) {
      onDeleted();
    }
  });
}

// 批量删除
function handleBatchDelete() {
  delOperlog(checkedRowKeys.value as Api.SystemManage.Operlog['operId'][]).then(() => {
    if (!res.error) {
      onBatchDeleted();
    }
  });
}

function handleView(row: Api.SystemManage.Operlog) {
  editingData.value = row;
  drawerVisible.value = true;
}

function handleClear() {
  cleanOperlog().then(() => {
    if (!res.error) {
      getDataByPage();
    }
  });
}

// 导出
function handleExport() {
  downLoadExcelPost('/monitor/operlog/export', searchParams);
}

function handleSorterChange(sorter: DataTableSortState) {
  console.log('handleSorterChange', sorter);
  searchParams.orderByColumn = sorter.columnKey as string;
  searchParams.isAsc = sorter.order === 'ascend' ? 'asc' : sorter.order === 'descend' ? 'desc' : null;
  getDataByPage();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <OperlogSearch
      v-model:model="searchParams"
      :type-options="typeOptions"
      :status-options="statusOptions"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <NCard title="操作日志" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-add-btn="false"
          @delete="handleBatchDelete"
          @refresh="getData"
        >
          <template #middle>
            <NButton :loading="exportLoading" type="success" ghost size="small" @click="handleExport">
              <template #icon>
                <SvgIcon icon="mdi:file-export-outline"></SvgIcon>
              </template>
              导出
            </NButton>
            <NPopconfirm @positive-click="handleClear">
              <template #trigger>
                <NButton size="small" ghost type="error">
                  <template #icon>
                    <SvgIcon icon="mdi:delete-outline"></SvgIcon>
                  </template>
                  清空
                </NButton>
              </template>
              确认清空操作日志吗？
            </NPopconfirm>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="({ operId }) => operId"
        :pagination="mobilePagination"
        class="sm:h-full"
        @update:sorter="handleSorterChange"
      />
      <OperlogView
        v-model:visible="drawerVisible"
        :type-options="typeOptions"
        :status-options="statusOptions"
        :row-data="editingData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
