<script lang="ts" setup>
import { ref, watch } from 'vue';
import MergeData from '#/store/MergeData.json';
import { orderTypeData, orderDiffData } from '#/store/order';
import { faceTypeData } from '#/store/face';
import { useVbenModal, useVbenForm } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { getUserlogInfoApi } from '#/api/core/log';
import { userGmApi, userBanApi } from '#/api/core/user';
import { calendar } from '#/component/index';
import type { dataType } from '#/component/index';
// 引入 cal-heatmap 样式
import 'cal-heatmap/cal-heatmap.css';
import type { WorkbenchProjectItem } from '@vben/common-ui';
import { orderComponent, chessComponent } from '#/component/index';
import type { Order, Merge, Chess } from '#/model/type';
import dayjs from 'dayjs';
import { WorkbenchDetail } from '@vben/common-ui';
import UserHeader from './user-header.vue';
import { AccessControl } from '@vben/access';



// 这是一个示例数据，实际项目中需要根据实际情况进行调整
// url 也可以是内部路由，在 navTo 方法中识别处理，进行内部跳转
// 例如：url: /dashboard/workspace
const projectItems: WorkbenchProjectItem[] = [];

const [BaseForm] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },

  // 使用 tailwindcss grid布局
  // 提交函数
  // 垂直布局，label和input在不同行，值为vertical
  layout: 'horizontal',
  // 水平布局，label和input在同一行
  schema: [
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入gm命令',
      },
      label: 'Gm:',
      fieldName: 'gm',
    },
  ],
  handleSubmit: async (values) => {
    const cv = modalApi.getData<Record<string, any>>();
    const r = await userGmApi({
      Uid: cv.uid,
      AppId: cv.AppId,
      ServerId: cv.ServerId,
      Command: values.gm,
    });
    message.success(r.Msg);
  },
  showDefaultActions: true,
  // 大屏一行显示3个，中屏一行显示2个，小屏一行显示1个
  wrapperClass: 'grid-cols-2 ',
});

const [BanForm] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },

  // 使用 tailwindcss grid布局
  // 提交函数
  // 垂直布局，label和input在不同行，值为vertical
  layout: 'horizontal',
  // 水平布局，label和input在同一行
  schema: [
    {
      component: 'Select',
      defaultValue: '',
      componentProps: {
        options: [
          { label: '封号1天', value: 1 },
          { label: '封号7天', value: 7 },
          { label: '封号30天', value: 30 },
          { label: '封号永久', value: -1 },
          { label: '解封', value: 0 },
        ],
      },
      label: '封号:',
      fieldName: 'ban',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入封号原因',
      },
      label: '原因:',
      fieldName: 'reason',
    },
  ],
  handleSubmit: async (values) => {
    const cv = modalApi.getData<Record<string, any>>();
    const r = await userBanApi({
      Uid: cv.uid,
      AppId: cv.AppId,
      ServerId: cv.ServerId,
      Day: values.ban,
      Reason: values.reason,
    });
    message.success(r.Msg);
  },
  showDefaultActions: true,
  // 大屏一行显示3个，中屏一行显示2个，小屏一行显示1个
  wrapperClass: 'grid-cols-3 ',
});

const data = ref();
const info = ref<{
  Level: number;
  Star: number;
  Name: string;
  Charge: number;
  AreaId: number;
  LoginTime: string;
  Diamond: number;
  Energy: number;
  Mac: string;
  Uid: number;
  Cumulative: string;
  TodayCumulative: string;
  Bonus?: number;
  Code?: string;
  RegisterTime?: string;
  Ban?: number;
  Face?: string;
  Order: Order[];
  Heatmap: dataType[];
  Chess: Chess[];
}>({
  Level: 0,
  Star: 0,
  Name: '',
  Charge: 0,
  Uid: 0,
  AreaId: 0,
  LoginTime: '',
  Diamond: 0,
  Energy: 0,
  Mac: '',
  Face: '',
  Cumulative: '0h',
  TodayCumulative: '0h',
  Order: [],
  Heatmap: [],
  Chess: [],
});
const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm() {
    message.info('onConfirm');
    // modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>();
      try {
        const r = await getUserlogInfoApi({
          Id: data.value.uid,
          Event: 'someEvent', // replace 'someEvent' with the actual event
          PageSize: 10, // replace 10 with the actual page size
          CurrentPage: 1, // replace 1 with the actual current page
        });

        info.value.Uid = data.value.uid;
        info.value.Level = r.Level;
        info.value.Star = r.Star;
        info.value.Name = r.Name;
        info.value.Charge = r.Charge;
        info.value.AreaId = r.AreaId;
        // 计算封号剩余天数（如果Ban为时间戳且大于当前时间，则计算剩余天数，否则为0或-1）
        if (r.Ban && r.Ban > 0) {
          const now = Math.floor(Date.now() / 1000);
          if (r.Ban > now) {
            info.value.Ban = Math.ceil((r.Ban - now) / 86400); // 剩余天数
          } else {
            info.value.Ban = 0; // 已解封
          }
        } else {
          info.value.Ban = r.Ban; // -1永久封号，0未封号
        }
        info.value.LoginTime = dayjs(r.Login * 1000).format(
          'YYYY-MM-DD HH:mm:ss',
        ); // 转换时间戳
        info.value.Diamond = r.Diamond;
        info.value.Energy = r.Energy;
        info.value.Mac = r.Mac;
        info.value.Cumulative = (r.Cumulative / 3600).toFixed(2) + 'h';
        info.value.TodayCumulative =
          (r.TodayCumulative / 3600).toFixed(2) + 'h';
        info.value.Order = [];
        info.value.Code = r.Code || '';
        info.value.RegisterTime = dayjs(r.RegisterTime * 1000).format(
          'YYYY-MM-DD HH:mm:ss',
        ); // 转换注册时间戳
        info.value.Heatmap = r.Heatmap || [];
        info.value.Face = faceTypeData[r.Face || 0] || '未知';
        info.value.Chess = Array.from({ length: 63 }, () => ({} as Chess));
        if (r.ChessMap) {
          for (const [key, value] of Object.entries(r.ChessMap)) {
            const [colStr = '0', rowStr = '0', lock = '0'] = key.split('@');
            const pos = parseInt(rowStr, 10) * 7 + parseInt(colStr, 10);
            info.value.Chess.splice(pos, 1, {
              Id: parseInt(value),
              Icon: ((MergeData as Record<string, Merge>)[
                value
              ]?.Icon) ?? '',
              Pos: pos,
              Lock: parseInt(lock, 10),
            });
          }
        }
        for (const i in r.Order) {
          var chessArr = r.Order[i]?.ChessId
            ? r.Order[i]?.ChessId.split(' ')
            : [];
          var ChessData: Merge[] = [];
          for (const chessId of chessArr) {
            const key = String(parseInt(chessId));
            const chessInfo = (MergeData as Record<string, Merge>)[key];
            if (chessInfo) {
              ChessData.push(chessInfo);
            }
          }
          var orderTypeName = Object.entries(orderTypeData).find(
            ([key]) => Number(key) === r.Order[i]?.Type
          )?.[1];
          var diffName = Object.entries(orderDiffData).find(
            ([key]) => Number(key) === r.Order[i]?.Diff
          )?.[1];
          info.value.Order.push({
            id: r.Order[i]?.Id || 0,
            merge: ChessData,
            color: '#3fb27f',
            content: r.Order[i]?.ChessId || '',
            typeName: orderTypeName || '未知类型',
            diff: r.Order[i]?.Diff || 0,
            diffName: diffName || '未知',
            date:
              dayjs((r.Order[i]?.Time ?? 0) * 1000).format(
                'YYYY-MM-DD HH:mm:ss',
              ) || '',
            group: String(r.Order[i]?.Type) || '',
            icon: 'lets-icons:order',
            title: String(r.Order[i]?.Id) || '',
            url: 'https://merge-pet-web.oss-cn-heyuan.aliyuncs.com/favicon.ico',
          });
        }
      } catch (error) {
        //console.error('Error fetching user info:', error);
      }
    }
  },
});

// 添加对热力图数据的监听
watch(
  () => info.value.Heatmap,
  (newHeatmap) => {
    if (newHeatmap && newHeatmap.length > 0) {
      // 可以在这里触发热力图重新渲染
    }
  },
  { deep: true },
);
</script>
<template>
  <Modal title="玩家详情">
    <div class="p-5">
      <UserHeader :avatar="info.Face" :ban="info.Ban">
        <template #nick_name> nick_name: {{ info.Name || 'N/A' }} </template>
        <template #user_name> user_name: {{ info.Mac }} </template>
        <template #uid> uid: {{ info.Uid }} </template>
        <template #level>{{ info.Level }}</template>
        <template #star>{{ info.Star }}</template>
        <template #energy>{{ info.Energy }} </template>
        <template #diamond>{{ info.Diamond }}</template>
      </UserHeader>
      <AccessControl :codes="['super', 'admin']" type="role">
        <div class="mt-5">
          <Card class="card-box flex flex-col p-5">
            <BaseForm />
          </Card>
        </div>
      </AccessControl>

      <AccessControl :codes="['super', 'admin']" type="role">
        <div class="mt-5">
          <Card class="card-box flex flex-col p-5">
            <BanForm />
          </Card>
        </div>
      </AccessControl>

      <div class="mt-5 flex flex-col lg:flex-row">
        <div class="mr-4 w-full lg:w-3/5">
          <orderComponent :items="info.Order" title="订单" />
          <chessComponent :items="info.Chess" title="棋盘" class="mt-6" />
        </div>
        <div class="w-full lg:w-2/5">
          <WorkbenchDetail :items="projectItems" class="mt-5 lg:mt-0" title="玩家详情">
            <template #areaid> {{ info.AreaId }}</template>
            <template #charge> <b>$</b>{{ info.Charge.toFixed(2) }}</template>
            <template #RegisterTime> {{ info.RegisterTime }}</template>
            <template #logintime> {{ info.LoginTime }}</template>
            <template #Cumulative>{{ info.Cumulative }}</template>
            <template #AreaId>{{ info.AreaId }}</template>
            <template #Code>{{ info.Code || 0 }}</template>
            <template #TodayCumulative>{{ info.TodayCumulative }}</template>
          </WorkbenchDetail>
          <calendar v-if="info.Heatmap.length > 0" style="margin-top: 15px" :dataList="info.Heatmap" title="热力图"
            :key="`heatmap-${info.Uid}`" />
          <div v-else style="
              margin-top: 15px;
              padding: 20px;
              text-align: center;
              color: #999;
            ">
            暂无热力图数据
          </div>
          <!-- <WorkbenchTodo :items="todoItems" class="mt-5" title="待办事项" /> -->
        </div>
      </div>
    </div>
  </Modal>
</template>
