<script setup lang="ts">
import { Page, useVbenModal } from '@vben/common-ui';
import type { VxeGridListeners } from '#/adapter/vxe-table';
import { getUserLogAssetApi } from '#/api/core/log';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { inject, ref } from 'vue';
import { globalState } from '#/store/globalState';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { VbenFormProps } from '#/adapter/form';
import { ItemData } from '#/store/item';
import { eventModal } from '#/component';
import dayjs from 'dayjs';

// 接收父组件传递的 props
const props = defineProps<{
  uid: number;
  serverId?: string;
  app?: number;
}>();

const state = inject('globalState', globalState);
const [Modal, modalApi] = useVbenModal({
  connectedComponent: eventModal,
  class: 'width:1800px;',

});
interface RowType {
  Uid: number;
  change_type: string;
  change_num: string;
  change_after: string;
  item_id: string;
  timestamp: string;
}

const formatType = (cellValue: string) => {
  switch (cellValue) {
    case "gain":
      return '增加';
    case "consume":
      return '减少';
    default:
      return cellValue;
  }
}
const formatItemName = (cellValue: number) => {
  // console.log(cellValue); 
  return ItemData.find((item) => item.Id === cellValue)?.Name || cellValue;
}
const d = ref({
  sum: 0,
  psum: 0,
  nsum: 0,
});
const startDate = dayjs().startOf('day');
const endDate = dayjs().endOf('day');
const itemIdOptions = ref([
  { label: '能量', value: 100001 },
  { label: '宠物币', value: 100002 },
  { label: '钻石', value: 100003 },
]);
const formOptions: VbenFormProps = {
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  // 默认展开
  collapsed: false,
  schema: [
    {
      disabled: true,
      component: 'Input',
      componentProps: {
        placeholder: 'Uid',
      },
      defaultValue: state.uid,
      fieldName: 'Uid',
      label: 'Uid',
    },
    {
      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: '结束时间',
    },
    {
      component: 'Select',
      componentProps: {
        options: itemIdOptions,
        allowClear: true,
      },
      fieldName: 'ItemId',
      label: '道具id',
    },
    {
      component: 'Select',
      componentProps: {
        options: [
          { label: '增加', value: 'gain' },
          { label: '减少', value: 'consume' },
        ],
        allowClear: true,
      },
      fieldName: 'Event',
      label: '变化类型',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
}
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', align: 'center' },
    { field: 'change_type', title: '变化类型', formatter: ({ cellValue }) => formatType(cellValue), align: 'center' },
    { field: 'change_num', title: '变化数值', align: 'center', width: 120 },
    { field: 'change_after', title: '变化后数值', align: 'center' },
    { field: 'change_reason', title: '原因', align: 'center' },
    { field: 'item_id', title: '道具名称', formatter: ({ cellValue }) => formatItemName(cellValue), align: 'center' },
    { field: 'timestamp', title: '时间', formatter: ({ cellValue }) => new Date(cellValue * 1000).toLocaleString(), align: 'center' },
  ],
  stripe: true,
  round: true,
  height: '800px',
  exportConfig: {
    filename: '用户资产日志',
    type: 'csv',
    mode: 'current',
    download: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    zoom: true,
  },
  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;
        const ItemId = parseInt(formValues.ItemId, 10);

        console.log(formValues.StartTime.unix());
        const r = await getUserLogAssetApi({
          Id: uid,
          AppId: props.app,
          Event: formValues.Event,
          StartTime: formValues.StartTime.unix(),
          EndTime: formValues.EndTime.unix(),
          ItemId: ItemId,
          CurrentPage: page.currentPage,
          PageSize: page.pageSize,
        });
        // 动态收集 item_id 与 item_name 生成下拉
        if (Array.isArray(r.data)) {
          itemIdOptions.value = [
            { label: '能量', value: 100001 },
            { label: '宠物币', value: 100002 },
            { label: '钻石', value: 100003 },
          ];
          const exist = new Set(itemIdOptions.value.map(o => String(o.value)));
          for (const row of r.data as any[]) {
            const idRaw = (row as any).item_id;
            const nameRaw = String(formatItemName(idRaw));
            if (idRaw !== undefined && idRaw !== null) {
              const idStr = String(idRaw);
              if (!exist.has(idStr)) {
                exist.add(idStr);
                itemIdOptions.value.push({
                  label: nameRaw,
                  value: parseInt(idStr, 10) || idRaw,
                });
              }
            }
          }
        }
        d.value.sum = r.sum;
        d.value.psum = r.psum;
        d.value.nsum = r.nsum;
        return r
      },
    },
  },

  rowConfig: {
    isHover: true,
  },
};

const [Grid] = useVbenVxeGrid({ formOptions, gridOptions, gridEvents });

</script>

<template>
  <div>
    <Page auto-content-height class="h-[800px]">
      <Grid>
        <template #empty>
          <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;">
            <img src="https://n.sinaimg.cn/sinacn17/w120h120/20180314/89fc-fyscsmv5911424.gif" alt="no-data"
              style="max-width:200px;display:block;">
            <p style="margin:8px 0 0;">没有更多数据了！</p>
          </div>
        </template>
        <template #toolbar-tools>
          总数:<span style="margin-right: 10px;margin-left: 5px;"> {{ d.sum }} </span>
          正数和: <span style="margin-right: 10px;margin-left: 5px;color:green">{{ d.psum }} </span>
          负数和: <span style="color: red;margin-left: 5px;">{{ d.nsum }} </span>
        </template>
      </Grid>
    </Page>
    <Modal class="w-[1200px]"> </Modal>
  </div>
</template>
