<script setup lang="tsx">
import { message, Modal, Tag } from 'ant-design-vue';
import type { Key } from 'ant-design-vue/es/_util/type';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { SimpleScrollbar } from '~/packages/materials/src';
import logSearch from './modules/log-search.vue';
import { useI18n } from "vue-i18n";
import { saveAs } from 'file-saver';
const { t } = useI18n();


const wrapperEl = shallowRef<HTMLElement | null>(null);
const { height: wrapperElHeight } = useElementSize(wrapperEl);

const scrollConfig = computed(() => {
  return {
    y: wrapperElHeight.value - 72,
    x: 1000
  };
});

const { columns, columnChecks, data, loading, getData, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: doGetlogList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    status: undefined,
  },
  rowKey: 'operId',
  columns: () => [
    {
      key: 'operId',
      dataIndex: 'operId',
      title: t('page.manage.log.logId'),
      align: 'center'
    },
    {
      key: 'title',
      dataIndex: 'title',
      title: t('page.manage.log.module'),
      align: 'center'
    },
    {
      key: 'operatorType',
      dataIndex: 'operatorType',
      title: t('page.manage.log.operType'),
      align: 'center',
      customRender: ({ record }: any) => {
        if (record.operatorType === null) {
          return null;
        }
        const tagMap: any = {
          0: t('page.manage.log.other'),
          1: t('page.manage.log.backUser'),
          2: t('page.manage.log.phoneUser'),
        };
        const tagColor: any = {
          '0': 'pink',
          '1': 'warning',
          '2': 'blue',
        };
        return <Tag color={tagColor[record.operatorType]}> {tagMap[record.operatorType]} </Tag>;
      }
    },
    {
      key: 'operName',
      dataIndex: 'operName',
      title: t('page.manage.log.operName'),
      align: 'center'
    },
    {
      key: 'operIp',
      dataIndex: 'operIp',
      title: t('page.manage.log.operIp'),
      align: 'center',
    },
    {
      key: 'status',
      dataIndex: 'status',
      align: 'center',
      customRender: ({ record }: any) => {
        if (record.status === null) {
          return null;
        }
        const tagMap: any = {
          0: t('common.normal'),
          1: t('common.abnormal'),
        };
        const tagColor: any = {
          '0': 'success',
          '1': 'error'
        };
        return <Tag color={tagColor[record.status]}> {tagMap[record.status]} </Tag>;
      },
      title: t('page.manage.log.operStatus'),
    },
    {
      key: 'operTime',
      dataIndex: 'operTime',
      align: 'center',
      title: t('page.manage.log.operTime'),
    },
    {
      key: 'costTime',
      dataIndex: 'costTime',
      align: 'center',
      title: t('page.manage.log.useTime'),
      customRender: ({ record }: any) => {
        if (!record.costTime) {
          return '0ms';
        }

        return `${record.costTime} ${t('common.ms')}`;
      },

    },
  ]
});

const {
  handleAdd,
  checkedRowKeys,
  onBatchDeleted,
  // closeDrawer
} = useTableOperate(data, { getData, idKey: 'operId' });
const deptTreeData = ref<Api.Common.CommonTree>([]);

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

async function handleBatchDelete() {
  const { error } = await doDeleteLog(checkedRowKeys.value);
  if (!error) {
    onBatchDeleted();
    // 取消勾选
    if (checkedRowKeys.value.length > 0) {
      checkedRowKeys.value = [];
    }
  }
}


function handleUserSelectChange(selectedRowKeys: Key[], selectedRows: any[]) {
  checkedRowKeys.value = selectedRowKeys as number[];
}



async function getUserDeptTree() {
  const { error, data: tree } = await doGetUserDeptTree();
  if (!error) {
    deptTreeData.value = tree;
  }
}

function handleExport() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('common.exportTip'),
    onOk() {
      const key = 'exportJob';
      message.loading({ content: t('common.loading'), key });
      doExportLog().then(res => {
        if (!res.error) {
          message.success({
            content: t('common.exportOk'),
            key,
            duration: 2,
          });
          saveAs(res.data, `oper_${Date.now()}.xlsx`);
        }
      });
    },
  });
}

</script>

<template>
  <SimpleScrollbar>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
      <logSearch v-model:model="searchParams" :dept-tree-data="deptTreeData" @reset="resetSearchParams"
        @search="getData" />
      <ACard :title="t('page.manage.user.title')" :bordered="false" :body-style="{ flex: 1, overflow: 'hidden' }"
        class="flex-col-stretch sm:flex-1-hidden card-wrapper">
        <template #extra>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading" :show-delete="true" @add="handleAdd" @delete="handleBatchDelete" @export="handleExport"
            @refresh="getData" :not-show-add="true" :show-export="true" />
        </template>
        <ATable ref="wrapperEl" row-key="operId" :columns="columns" :data-source="data" :loading="loading"
          :row-selection="{
            selectedRowKeys: checkedRowKeys,
            onChange: handleUserSelectChange,
          }" size="small" :pagination="mobilePagination" :scroll="scrollConfig" class="h-full" />

      </ACard>
    </div>
  </SimpleScrollbar>
</template>

<style scoped></style>
