<script setup lang="ts">
import { Page, useVbenModal, VbenIcon } 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 { getUnixTime, formatUTC8Time } from "#/store/util";
import { Tag } from 'ant-design-vue';
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: getUnixTime(row.timestamp),
      EndTime: row.timestamp,
    });
    modalApi.open();
  },
};
const gridOptions: VxeGridProps<RowType> = {
  columns: [
    // { field: 'Uid', title: 'Uid', align: 'center' },
    { field: 'change_type', title: '变化类型', align: 'center', slots: { default: 'change_type' } },
    { field: 'change_num', title: '变化数值', align: 'center', width: 120 },
    { field: 'change_after', title: '变化后数值', align: 'center' },
    { field: 'change_reason', title: '原因', align: 'center', slots: { default: 'change_reason' } },
    { field: 'item_name', title: '道具名称', align: 'center', slots: { default: 'item_name' } },
    { field: 'timestamp', title: '时间', formatter: ({ cellValue }) => formatUTC8Time(cellValue), align: 'center', slots: { header: 'time_header' } },
  ],
  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);
        const StartTime = getUnixTime(formValues.StartTime);
        const EndTime = getUnixTime(formValues.EndTime);
        const r = await getUserLogAssetApi({
          Id: uid,
          AppId: props.app,
          Event: formValues.Event,
          StartTime: StartTime,
          EndTime: EndTime,
          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 });

function getChangeTypeColor(type: string) {
  return type === 'consume' ? 'error' : 'success';
}

function getChangeTypeIcon(type: string) {
  return type === 'consume' ? 'solar:arrow-to-down-left-bold' : 'solar:arrow-to-top-left-bold';
}

</script>

<template>
  <div class="asset-log-page">
    <Page auto-content-height>
      <div class="asset-log-panel">
        <Grid>
        <template #empty>
          <div class="asset-log-empty">
            <img src="https://n.sinaimg.cn/sinacn17/w120h120/20180314/89fc-fyscsmv5911424.gif" alt="no-data"
              class="asset-log-empty__image">
            <p class="asset-log-empty__text">没有更多数据了！</p>
          </div>
        </template>
        <template #time_header>
          时间 <span style="color: red">(UTC+8)</span>
        </template>
        <template #change_type="{ row }">
          <Tag :color="getChangeTypeColor(row.change_type)" class="asset-log-change-tag">
            <VbenIcon :icon="getChangeTypeIcon(row.change_type)" class="mr-1" />
            {{ formatType(row.change_type) }}
          </Tag>
        </template>
        <template #change_reason="{ row }">
          <span class="asset-log-reason">{{ row.change_reason || '-' }}</span>
        </template>
        <template #item_name="{ row }">
          <span class="asset-log-item-chip">{{ row.item_name || '-' }}</span>
        </template>
        <template #toolbar-tools>
          <div class="asset-log-toolbar">
            <Tag color="processing" class="asset-log-toolbar__tag">
              <VbenIcon icon="solar:user-id-bold" class="mr-1" />
              UID {{ props.uid || '-' }}
            </Tag>
            <Tag color="blue" class="asset-log-toolbar__tag">
              总数 {{ d.sum }}
            </Tag>
            <Tag color="success" class="asset-log-toolbar__tag">
              正数和 {{ d.psum }}
            </Tag>
            <Tag color="error" class="asset-log-toolbar__tag">
              负数和 {{ d.nsum }}
            </Tag>
          </div>
        </template>
        </Grid>
      </div>
    </Page>
    <Modal class="w-[1200px]"> </Modal>
  </div>
</template>

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

.asset-log-panel {
  overflow: hidden;
  border-radius: 22px;
  box-shadow: 0 16px 30px rgb(15 23 42 / 8%);
}

.asset-log-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.asset-log-empty__image {
  display: block;
  max-width: 200px;
}

.asset-log-empty__text {
  margin-top: 8px;
  color: #475569;
  font-weight: 600;
}

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

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

.asset-log-change-tag {
  display: inline-flex;
  align-items: center;
  border-radius: 999px;
  font-weight: 700;
}

.asset-log-item-chip {
  display: inline-flex;
  align-items: center;
  padding: 4px 10px;
  border-radius: 999px;
  background: linear-gradient(135deg, #e0ecff 0%, #dbeafe 100%);
  color: #1d4ed8;
  font-weight: 700;
}
</style>
