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


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

const chargeDisplay = computed(() => (Number(info.value?.Charge ?? 0)).toFixed(2));

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

  // 使用 tailwindcss grid布局
  // 提交函数
  // 垂直布局，label和input在不同行，值为vertical
  layout: 'horizontal',
  // 水平布局，label和input在同一行
  schema: [
    {
      component: 'Mentions',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入gm命令，输入@可查看命令列表',
        options: [
          // 基础
          { label: 'additem 100002 100 增加宠物币100', value: 'additem 100002 100' },
          { label: 'additem 100001 100 增加能量100', value: 'additem 100001 100' },
          { label: 'additem 100003 100 增加钻石100', value: 'additem 100003 100' },
          { label: 'subitem 100002 100 减少宠物币100', value: 'subitem 100002 100' },
          { label: 'addexp 100 增加100经验', value: 'addexp 100' },
          { label: 'setlv 1 设置为1级', value: 'setlv 1' },
          { label: 'AllFace 获取所有头像和头像框', value: 'AllFace' },
          { label: 'resetFace 重置用户头像和头像框', value: 'resetFace' },
          { label: 'addEmoji 获取所有表情', value: 'addEmoji' },
          { label: 'initEmoji 重置表情', value: 'initEmoji' },


          // 订单
          { label: 'reset_order 重置订单', value: 'reset_order' },
          { label: 'orderMerge 获取订单所需棋子', value: 'orderMerge' },
          // 模拟充值
          { label: 'pay 10 模拟充值10挡位', value: 'pay 10' },
          // 棋盘
          { label: 'AddPart 增加所有类型零件10000个', value: 'AddPart' },
          { label: 'resetChess 重置棋盘', value: 'resetChess' },
          { label: 'addChessStar 5 增加5点棋子碎片', value: 'addChessStar 5' },
          { label: 'resetRetire 重置棋子退役', value: 'resetRetire' },
          { label: 'cleanBuff 清空缓存区', value: 'cleanBuff' },
          { label: 'addAllChess 获取所有棋子', value: 'addAllChess' },
          { label: 'addSeasonChess 获取当前轮次全部棋子', value: 'addSeasonChess' },

          // 卡牌
          { label: 'add_card_star 5 增加5点卡包碎片', value: 'add_card_star 5' },
          { label: 'add_card 1 增加id为1的卡牌', value: 'add_card 1' },
          { label: 'addAddCard 获取所有卡牌', value: 'addAddCard' },
          { label: 'addAddCard 获取当前轮次全部卡牌', value: 'addAddCard' },
          { label: 'resetCardSeasonFirst 重置卡牌赛季初始奖励', value: 'resetCardSeasonFirst' },
          { label: 'reset_card_reward 重置卡牌大奖', value: 'reset_card_reward' },

          // 每日任务
          { label: 'setSevenLoginActive 20 设置签到进度为20', value: 'setSevenLoginActive 20' },
          { label: 'addDailyActive 增加每日任务活跃度', value: 'addDailyActive 10' },

          // 限时事件
          { label: 'setProgress 4 设置转盘进度为4', value: 'setProgress 4' },
          { label: 'setProgressReward 完成限时事件转盘', value: 'setProgressReward' },

          // 锦标赛
          { label: 'champshipGroup 锦标赛分组', value: 'champshipGroup' },

          // 游戏模拟
          { label: 'zeroUpdate 模拟0点更新', value: 'zeroUpdate' },

          // Playroom
          { label: 'playroomTrigger 生成playroom触发式订单', value: 'playroomTrigger' },
          { label: 'playroomCollect 获取playroom所有装饰', value: 'playroomCollect' },
          { label: 'addChip 增加playroom房间纸屑', value: 'addChip' },
          { label: 'addFriendStar 4 在宠物宝藏中增加4个宠物币', value: 'addFriendStar 4' },
          { label: 'addPhysiology type num 增加生理类型为type的数值num', value: 'addPhysiology type num' },
          { label: 'resetTriggerTime 重置playroom触发订单cd', value: 'resetTriggerTime' },
          { label: 'playroomDress 获取playroom所有服装', value: 'playroomDress' },
          { label: 'playroomAir 获取playroom所有飞行背包', value: 'playroomAir' },
          { label: 'resetCollect 重置playroom家具', value: 'resetCollect' },
          { label: 'playroomDress 解锁所有playroom服装', value: 'playroomDress' },
          { label: 'resetAir 重置playroom飞行背包', value: 'resetAir' },

          // 好友
          { label: 'addFriend 对方uid 仅用于调试，对方好友列表不会增加', value: 'addFriend 对方uid' },

          // 场景
          { label: 'setDecorateArea 1 设置装饰区域id', value: 'setDecorateArea 1' },
          { label: 'setDecorateProgress 1 设置装饰进度', value: 'setDecorateProgress 1' },

          // 图鉴
          { label: 'handbook 解锁所有图鉴', value: 'handbook' },

          // 猜颜色
          { label: 'guessColorReload 重置猜颜色游戏', value: 'guessColorReload' },
          // 挖矿
          { label: 'miningReload 重置挖矿游戏', value: 'miningReload' },
          // 赛跑
          { label: 'raceReload 重置赛跑游戏', value: 'raceReload' },
          // 猫草大作战
          { label: 'catnipReload 重置猫草大作战游戏', value: 'catnipReload' },
        ],
      },
      label: 'Gm:',
      fieldName: 'gm',
    },
  ],
  handleSubmit: async (values) => {
    const cv = modalApi.getData<Record<string, any>>();
    let gm = values.gm;
    gm = String(gm || '').replace(/@/g, '');
    const r = await userGmApi({
      Uid: cv.uid,
      AppId: cv.AppId,
      ServerId: cv.Node,
      Command: 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[];
  Friend: friendRecord[];
  MaxCharge?: number;
}>({
  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: [],
  Friend: [],
  MaxCharge: 0,
});
let trendItems: WorkbenchTrendItem[] = [

];
const [Modal, modalApi] = useVbenModal({
  fullscreen: true,
  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,
          Node: data.value.Node,
          AppId: data.value.AppId,
        });
        trendItems = [];
        let id = 0;
        if (r.ActLog) {
          for (const logEntry of r.ActLog.reverse()) {
            let [title, content] = formatActLog(logEntry.Type, logEntry.Param)
            trendItems.push({
              Id: id++,
              avatar: 'svg:avatar-1',
              content: content || '',
              date: dayjs(logEntry.Time * 1000).format('YYYY-MM-DD HH:mm:ss'),
              title: title || '未知玩家',
            });
          }
        }
        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;
        info.value.MaxCharge = r.MaxCharge;
        info.value.Friend = r.FriendList || [];
        // 计算封号剩余天数（如果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
          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: chessArr,
            color: '#3fb27f',
            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);
      }
    }
  },
});

function formatActLog(type: number, content = ''): [string, string] {
  const splitPair = (s: string): [string, string] => {
    if (!s) return ['', ''];
    const parts = s.split('|');
    return [parts[0] ?? '', parts[1] ?? ''];
  };

  const rankText = (s: string) => {
    const n = Number(s);
    return Number.isFinite(n) && n > 0 ? `在锦标赛中获得了第${n}名！` : `在锦标赛中获得了第${s || 'X'}名！`;
  };

  const activityRewardText = (s: string) => {
    const [act, reward] = splitPair(s);
    if (act && reward) return `在${act}活动中获得了${reward}！`;
    if (act) return `在${act}活动中获得了奖励！`;
    return `在活动中获得了奖励！`;
  };

  switch (type) {
    case 1:
      return ['首次登入游戏', '加入了拯救小猫的行列！'];
    case 2:
      return ['完成休息室', '为小猫建造了一个温暖的家！'];
    case 3:
      return ['完成餐厅', '为小猫准备了丰盛的食物！'];
    case 4:
      return ['完成浴室', '把小猫整理得香喷喷的！'];
    case 5:
      return ['完成衣帽间', '把小猫打扮得漂漂亮亮的！'];
    case 6:
      return ['获得新头像', '收藏了一个新的头像！'];
    case 7:
      return ['获得新头像框', '收藏了一个新的头像框！'];
    case 8:
      return ['获得新表情', '收藏了一个新的表情！'];
    case 9:
      return ['获得新装饰品', '获得了新的房间装饰！'];
    case 10:
      return ['获得新服装', '获得了漂漂亮亮的新衣服！'];
    case 11: {
      const subject = content || '某个角色';
      return ['完成卡册收集', `收集了${subject}的所有卡牌！`];
    }
    case 12: {
      const subject = content || '某个系列';
      return ['完成全卡牌收集', `收集了${subject}的所有卡牌！`];
    }
    case 13:
      return ['获得锦标赛名次', rankText(content)];
    case 14:
      return ['获得锦标赛大奖', '完成了锦标赛！'];
    case 15:
      return ['获得限时活动大奖', activityRewardText(content)];
    case 16:
      return ['参加好友合作类活动', '参加了合作伙伴活动！'];
    case 17:
      return ['获得拜访小游戏大奖', '把邻居家的小猫关了起来！'];
    case 18:
      return ['获得拜访小游戏大奖', '薅走了邻居的宠物币！'];
    case 19: {
      const who = content || '好友们';
      return ['打开宠物宝藏', `${who}一起找到了宝藏！`];
    }
    case 20:
      return ['拜访时点赞', '给邻居点了个大大的赞！'];
    case 21: {
      const subject = content || '某个系列';
      return ['完成图鉴收集成就', `收集了${subject}的所有物品！`];
    }
    case 22: {
      const chap = content || 'X';
      return [`完成第${chap}章所有场景`, `将章节${chap}的场景变得焕然一新！`];
    }
    case 23:
      return ['流失用户回归', '回来看小猫了！'];
    // 保留原始常见文本类型（兼容之前的简短日志）
    case 4_00:
      return ['发表文章', `发表文章 <a>${content}</a>`];
    case 5_00:
      return ['回复问题', `回复了 <a>某人</a> 的问题 <a>${content}</a>`];
    case 6_00:
      return ['关闭问题', `关闭了问题 <a>${content}</a>`];
    case 7_00:
      return ['代码推送', `推送了代码到 <a>${content}</a>`];
    default:
      return ['未知行为', content || ''];
  }
}

// 添加对热力图数据的监听
watch(
  () => info.value.Heatmap,
  (newHeatmap) => {
    if (newHeatmap && newHeatmap.length > 0) {
      // 可以在这里触发热力图重新渲染
    }
  },
  { deep: true },
);

</script>
<template>
  <Modal title="玩家详情" class="h-[100%]">
    <div class="p-5">
      <Tabs>
        <Tabs.TabPane key="1" tab="玩家信息">
          <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 flex">
              <Card class="card-box flex flex-col p-5 w-[50%]">
                <BaseForm />
              </Card>
              <Card class="card-box flex flex-col p-5 w-[45%] ml-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="订单" />
              <WorkbenchTrends :items="trendItems" class="mt-5" title="最新动态" />
            </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>{{ chargeDisplay }}</template>
                <template #maxCharge> <b>$</b>{{ info.MaxCharge }}</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>
              <chessComponent :items="info.Chess" title="棋盘" class="mt-6" />
              <friendComponent :Items="info.Friend" title="好友" class="mt-6" />
              <!-- <WorkbenchTodo :items="todoItems" class="mt-5" title="待办事项" /> -->
            </div>
          </div>

        </Tabs.TabPane>
        <Tabs.TabPane key="2" tab="操作日志">
          <eventTable :uid="info.Uid" :serverId="data?.Node" :app="data?.AppId" />
        </Tabs.TabPane>
        <Tabs.TabPane key="3" tab="资产日志">
          <assetTable :uid="info.Uid" :serverId="data?.Node" :app="data?.AppId" />
        </Tabs.TabPane>
        <Tabs.TabPane key="4" tab="订单日志">
          <orderTable :uid="info.Uid" :serverId="data?.Node" :app="data?.AppId"  />
        </Tabs.TabPane>
      </Tabs>

    </div>
  </Modal>
</template>
