<template>
  <div class="m-4">
    <div>
      <XTTitle title="登录日志" :go-back="true" :right-data="titleData" @click="handleImport" />
      <div class="flex items-center justify-between my-4">
        <XTTab
          type="opLog"
          :width="120"
          :selected="tabSelected"
          :data="typeOptions"
          @item-click="callTab"
        />
        <XTForm :form-data="formData" @change="callForm" />
      </div>
    </div>
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'type'">
          <Tag :color="formatDictColor(typeOptions, record.type)">
            {{ formatDictValue(typeOptions, record.type) }}
          </Tag>
        </template>
        <template v-if="column.key === 'duration'"> {{ record.duration }}ms </template>
        <template v-if="column.key === 'responseType'">
          <Tag :color="formatDictColor(responseTypeOptions, record.responseType)">
            {{ formatDictValue(responseTypeOptions, record.responseType) }}
          </Tag>
        </template>
        <template v-if="column.key === 'resultJson'">
          <Tag :color="formatDictColor(resultJsonOptions, record.resultJson)">
            {{ formatDictValue(resultJsonOptions, record.resultJson) }}
          </Tag>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                auth: 'sys:log:query',
                icon: 'icon-eye|iconfont',
                tooltip: '查看',
                label: '查看',
                onClick: handleView.bind(null, record),
              },
              {
                auth: 'sys:log:remove	',
                icon: 'icon-delete|iconfont',
                tooltip: '删除',
                label: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <FormDrawer @register="registerDrawer" @success="handleSuccess" />
    <ViewDrawer @register="registerDrawerView" @success="handleSuccess" />
    <importView @register="registerModal" />
  </div>
</template>
<script lang="ts" setup>
  import { onBeforeMount, ref } from 'vue';
  import { Tag } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/TableCard';
  import { useMessage } from '/@/hooks/web/useMessage';
  import FormDrawer from './formDrawer.vue';
  import ViewDrawer from './viewDrawer.vue';
  import importView from './importModal/importView.vue';
  import { columns, searchFormSchema } from './data';

  import { LogQueryPage, LogRemove, LogLoginExport } from '/@/api/monitor/LogApi';
  import { listDictModel } from '/@/api/common';
  import { formatDictColor, formatDictValue } from '/@/utils'; //
  import { useDrawer } from '/@/components/Drawer';

  import { XTTitle } from '/@/components/XTTitle/index';
  import { XTTab } from '/@/components/XTTab/index';
  import { XTForm } from '/@/components/XTForm/index';
  import { useModal } from '/@/components/Modal';

  // 标题组件右侧按钮
  const titleData = [
    {
      type: 'import',
      icon: 'icon-xt-import_default',
    },
  ];
  // formdata
  const formData = [
    {
      name: 'opName',
      componentType: 'Input',
      placeholder: '请输入操作名称',
      width: 200,
      prefix: 'icon-xt-search',
    },
  ];
  const typeOptions = ref();
  const responseTypeOptions = ref();
  const resultJsonOptions = ref();
  // tab 切换选中
  const tabSelected = ref();
  onBeforeMount(async () => {
    typeOptions.value = await listDictModel({ dictCode: 'sys_login_log_type' });
    responseTypeOptions.value = await listDictModel({ dictCode: 'sys_response_type' });
    resultJsonOptions.value = await listDictModel({ dictCode: 'sys_response_type' });
    typeOptions.value = typeOptions.value.map(ele => {
      ele.key = ele.value;
      return ele;
    });
    tabSelected.value = typeOptions.value[0].value;
  });
  const { createConfirm, createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerDrawer] = useDrawer(); // , { openDrawer }
  const [registerDrawerView, { openDrawer: openDrawerView }] = useDrawer();

  // 操作名称
  const opName = ref('');

  const tableSort = ref([
    {
      field: 'create_time',
      direction: 'DESC',
    },
  ]) as any;

  const [registerTable, { reload, getSelectRowKeys, clearSelectedRowKeys }] = useTable({
    title: '',
    api: LogQueryPage,
    batchDelApi: LogRemove,
    batchExportApi: LogLoginExport,
    exportAuthList: ['sys:log:export:login'],
    delAuthList: ['sys:log:remove'],
    rowKey: 'id',
    columns,
    showIndexColumn: true,
    rowSelection: { type: 'checkbox' },
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      baseColProps: { xs: 24, sm: 12, md: 12, lg: 8 },
      resetButtonOptions: {
        preIcon: 'icon-delete|iconfont',
      },
      submitButtonOptions: {
        preIcon: 'icon-search|iconfont',
      },
    },
    useSearchForm: true,
    bordered: true,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
    sortFn: handleSortFn,
  });
  // 详情按钮事件
  function handleView(record: Recordable) {
    console.log(record);
    openDrawerView(true, {
      record,
    });
  }

  // 导入按钮
  function handleImport() {
    openModal(true);
  }

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    if (record) {
      await LogRemove([record.id]);
      createMessage.success('删除成功！');
      await reload();
    } else {
      const keys = getSelectRowKeys();
      if (keys.length > 0) {
        createConfirm({
          content: '你确定要删除?',
          iconType: 'warning',
          onOk: async () => {
            await LogRemove(keys);
            createMessage.success('删除成功！');
            await reload();
            clearSelectedRowKeys();
          },
        });
      } else {
        createMessage.warning('请选择要删除的数据');
      }
    }
  }
  // 表格点击字段排序
  function handleSortFn(sortInfo) {
    if (sortInfo?.order && sortInfo?.columnKey) {
      // 默认单列排序
      tableSort.value = [
        {
          field: sortInfo.columnKey,
          direction: sortInfo.order.replace(/(\w+)(end)/g, '$1').toUpperCase(),
        },
      ];
    }
  }

  // 表格请求之前，对参数进行处理, 添加默认 排序
  function handleBeforeFetch(params) {
    return { ...params, orders: tableSort.value, type: tabSelected.value, opName: opName.value };
  }

  // 弹窗回调事件
  async function handleSuccess({ isUpdate, values }) {
    console.log(isUpdate);
    console.log(values);
    await reload();
  }

  // 组件回调
  async function callTab(data) {
    tabSelected.value = data.value;
    await reload();
  }
  async function callForm(data) {
    opName.value = data.opName;
    await reload();
  }
</script>
