<script setup lang="ts">

import { getUserlogEventApi } from '#/api/core/log';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { inject } from 'vue';
import type { VxeGridListeners } from 'vxe-table';
import { globalState } from '#/store/globalState';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { VbenFormProps } from '#/adapter/form';
import { Page, useVbenModal, VbenIcon } from '@vben/common-ui';
import { assetModal } from '#/component';
import { Tag } from 'ant-design-vue';
import dayjs from 'dayjs';
import { formatUTC8Time } from '#/store/util';
const state = inject('globalState', globalState);
const [Modal, modalApi] = useVbenModal({
  connectedComponent: assetModal,
  class: 'width:1800px;',

});
// 接收父组件传递的 props
const props = defineProps<{
  uid: number;
  serverId?: string;
  app?: number;
}>();
const startDate = dayjs().startOf('day');
const endDate = dayjs().endOf('day');
interface RowType {
  Uid: string;
  Event: string;
  Param: string;
  Timestamp: string;
}
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      disabled: true,
      component: 'Input',
      componentProps: {
        placeholder: 'Uid',
      },
      defaultValue: state.uid,
      fieldName: 'Uid',
      label: 'Uid',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: 'Event',
      },
      defaultValue: state.Event,
      fieldName: 'Event',
      label: '事件类型',
    },
    {
      component: 'DatePicker',
      defaultValue: startDate,
      componentProps: {
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
      fieldName: 'StartTime',
      label: '开始时间',
    },
    {
      component: 'DatePicker',
      defaultValue: endDate,
      componentProps: {
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
      fieldName: 'EndTime',
      label: '结束时间',
    }
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-5',
}
const gridEvents: VxeGridListeners<RowType> = {
  cellDblclick: async ({ row }) => {
    console.log(row);
    modalApi.setData({
      StartTime: row.Timestamp,
      EndTime: row.Timestamp,
    });
    modalApi.open();
  },
};
const gridOptions: VxeGridProps<RowType> = {
  columns: [
    // { field: 'Uid', title: 'Uid' },
    { field: 'Label', title: '事件名称', width: 160 },
    { field: 'Event', title: '事件类型',width:120, slots: { default: 'event' } },
    { field: 'Param', title: '参数' },
    { field: 'Timestamp', title: '时间',width:180, formatter: ({ cellValue }) => formatUTC8Time(cellValue), slots: { header: 'time_header' } },
  ],
  stripe: true,
  height: '800px',
  pagerConfig: {},
  proxyConfig: {
    response: {
      total: "total",
      result: "data"
    },
    ajax: {
      query: async ({ page }, formValues) => {
        let Uid = parseInt(formValues.Uid, 10);
        if (Uid == 0) {
          return []
        }
        state.uid = Uid;
        state.Event = formValues.Event;
        let startTimeUnix = 0;
        let endTimeUnix = 0;
        // formValues.StartTime/EndTime 可能是 string（当 DatePicker 设置了 valueFormat 时）
        // 也可能是 dayjs 对象（未设置 valueFormat 时）
        if (formValues.StartTime) {
          if (typeof formValues.StartTime === 'string') {
            startTimeUnix = dayjs(formValues.StartTime).unix();
          } else if (dayjs.isDayjs(formValues.StartTime)) {
            startTimeUnix = formValues.StartTime.unix();
          } else if (typeof (formValues.StartTime as any).unix === 'function') {
            startTimeUnix = (formValues.StartTime as any).unix();
          } else {
            startTimeUnix = dayjs(formValues.StartTime).unix();
          }
        }
        if (formValues.EndTime) {
          if (typeof formValues.EndTime === 'string') {
            endTimeUnix = dayjs(formValues.EndTime).unix();
          } else if (dayjs.isDayjs(formValues.EndTime)) {
            endTimeUnix = formValues.EndTime.unix();
          } else if (typeof (formValues.EndTime as any).unix === 'function') {
            endTimeUnix = (formValues.EndTime as any).unix();
          } else {
            endTimeUnix = dayjs(formValues.EndTime).unix();
          }
        }
        // 使用计算好的 unix 时间调用接口
        return await getUserlogEventApi({
          AppId: props.app,
          Id: Uid,
          Event: formValues.Event,
          StartTime: startTimeUnix,
          EndTime: endTimeUnix,
          CurrentPage: page.currentPage,
          PageSize: page.pageSize,
        });
      },
    },
  },

  rowConfig: {
    isHover: true,
  },
};

const [Grid] = useVbenVxeGrid({ formOptions, gridOptions, gridEvents });
function getTag(event:string){
    switch(event){
        case 'func_exec_error':
            return ["error"];
        default:
            return ['success'];
    }
}

function getTagColor(tag:string){
    switch(tag){
        case 'error':
            return "red";
        default:
            return "green";
    }
}

function getTagIcon(tag: string) {
  switch (tag) {
    case 'error':
      return 'solar:danger-circle-bold';
    default:
      return 'solar:check-circle-bold';
  }
}
</script>

<template>
  <div class="event-log-page">
    <Page auto-content-height>
      <div class="event-log-panel">
        <Grid>
          <template #toolbar-tools>
            <div class="event-log-toolbar">
              <Tag color="processing" class="event-log-toolbar__tag">
                <VbenIcon icon="solar:user-id-bold" class="mr-1" />
                UID {{ props.uid || '-' }}
              </Tag>
              <Tag color="blue" class="event-log-toolbar__tag">
                <VbenIcon icon="solar:cursor-square-bold" class="mr-1" />
                双击日志可查看资产快照
              </Tag>
            </div>
          </template>
        <template #time_header>
          时间 <span style="color: red">(UTC+8)</span>
        </template>
        <template #event="{ row }">
          <Tag
            v-for="(label, index) in getTag(row.Event)"
            :key="index"
            :color="getTagColor(label)"
            class="event-log-status-tag"
          >
            <VbenIcon :icon="getTagIcon(label)" class="mr-1" />
            {{ label }}
          </Tag>
        </template>
        </Grid>
      </div>
    </Page>
    <Modal class="w-[800px]"> </Modal>
  </div>

</template>

<style lang="css">
.event-log-page {
  min-height: 100%;
}

.event-log-panel {
  overflow: hidden;
  border-radius: 22px;
  background: linear-gradient(180deg, rgb(255 255 255 / 98%) 0%, rgb(247 250 255 / 98%) 100%);
  box-shadow: 0 16px 30px rgb(15 23 42 / 8%);
}

.event-log-toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.event-log-toolbar__tag {
  display: inline-flex;
  align-items: center;
  padding-inline: 10px;
  border-radius: 999px;
  font-weight: 600;
}

.event-log-status-tag {
  display: inline-flex;
  align-items: center;
  border-radius: 999px;
  font-weight: 700;
}
</style>
