<script setup lang="tsx">
import { Button, Popconfirm, Tag, Tooltip } from 'ant-design-vue';
import dayjs from 'dayjs';

import SvgIcon from '@/components/custom/svg-icon.vue';
import { UNIFORM_TEXT } from '@/enum';
import { I18N_COMMON } from '@/enum/i18n';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import {
  activateActivationCode,
  delActivationCode,
  getActivationCodeList,
  getAllCodeTypes,
  refundActivationCode,
  revokeActivationCode,
} from '@/service/api';
import { useAuthStore } from '@/store/modules/auth';

import ExportModal from './modules/export-modal.vue';
import HeaderSearch from './modules/header-search.vue';
import ImportDrawer from './modules/import-drawer.vue';
import RefundModal from './modules/refund-modal.vue';
import { computed, onMounted, ref } from 'vue';

const expandStats = ref(false);

// 计算统计信息
const stats = computed(() => {
  if (!tableInfo.value || !Array.isArray(tableInfo.value)) {
    return {
      totalCount: 0,
      activeCount: 0,
      refundCount: 0,
      revokedCount: 0,
      inactiveCount: 0,
      // 按类型统计
      typeStats: {},
      // 按类型+激活状态统计
      detailedStats: {},
    };
  }

  const info = tableInfo.value;
  const typeStats: Record<string, number> = {};
  const detailedStats: Record<string, {
    total: number;
    active: number;
    refunded: number;
    revoked: number;
    inactive: number;
  }> = {};

  // 遍历 info 数组进行统计
  info.forEach((item: any) => {
    const typeId = item.typeId || 'unknown';
    const typeName = activationCodeTypeOptions.value.find(opt => opt.id === typeId)?.label || `类型${typeId}`;

    // 统计总数
    typeStats[typeName] = (typeStats[typeName] || 0) + 1;

    // 初始化详细统计
    if (!detailedStats[typeName]) {
      detailedStats[typeName] = {
        total: 0,
        active: 0,
        refunded: 0,
        revoked: 0,
        inactive: 0,
      };
    }

    // 更新详细统计
    detailedStats[typeName].total += 1;
    if (item.activated) {
      detailedStats[typeName].active += 1;
    } else {
      detailedStats[typeName].inactive += 1;
    }
    if (item.refunded) {
      detailedStats[typeName].refunded += 1;
    }
    if (item.revoked) {
      detailedStats[typeName].revoked += 1;
    }
  });

  // 计算总体统计
  const totalCount = info.length;
  const activeCount = info.filter(item => item.activated).length;
  const refundCount = info.filter(item => item.refunded).length;
  const revokedCount = info.filter(item => item.revoked).length;
  const inactiveCount = info.filter(item => !item.activated).length;

  return {
    totalCount,
    activeCount,
    refundCount,
    revokedCount,
    inactiveCount,
    typeStats,
    detailedStats,
  };
});
const { userInfo } = useAuthStore();

// 激活码类型选项
const activationCodeTypeOptions = ref<{ label: string; value: string; id: string }[]>([]);

// 获取激活码类型列表
const getCodeTypeOptions = async () => {
  try {
    const { data, error } = await getAllCodeTypes();
    if (!error && data) {
      activationCodeTypeOptions.value = data.records.map((item: Api.CodeType.CodeType) => ({
        label: item.name,
        value: item.id,
        id: item.id,
      }));
    }
  } catch (error) {
    console.error('获取激活码类型失败:', error);
  }
};

// 获取激活码类型标签颜色
const getTypeTagColor = (record: Api.ActivationCode.ActivationCode) => {
  const colors = ['volcano', 'orange', 'gold', 'lime', 'green', 'cyan', 'blue', 'purple'];

  // 优先使用新的 typeId
  if (record.typeId) {
    const index = activationCodeTypeOptions.value.findIndex(opt => opt.id === record.typeId);
    return colors[index % colors.length] || 'default';
  }

  // 回退到旧的 type 字段（兼容性）
  const oldColors: Record<number, string> = {
    1: 'volcano',
    15: 'orange',
    30: 'gold',
    182: 'lime',
    365: 'green',
  };
  return oldColors[record.type] || 'default';
};

// 获取激活码类型标签文本
const getTypeTagText = (record: Api.ActivationCode.ActivationCode) => {
  // 优先使用新的 typeId
  if (record.typeId) {
    const option = activationCodeTypeOptions.value.find(opt => opt.id === record.typeId);
    return option?.label || '未知类型';
  }

  // 回退到旧的 type 字段（兼容性）
  const oldTypeLabels: Record<number, string> = {
    1: '1天KEY',
    15: '15天KEY',
    30: '30天KEY',
    182: '182天KEY',
    365: '365天KEY',
  };
  return oldTypeLabels[record.type] || `${record.type}天`;
};

const { tableWrapperRef, scrollConfig } = useTableScroll(1400);

// 导入抽屉显示状态
const importDrawerVisible = ref(false);

// 导出弹窗显示状态
const exportModalVisible = ref(false);

// 退款弹窗显示状态
const refundModalVisible = ref(false);
const refundingRecord = ref<Api.ActivationCode.ActivationCode | null>(null);

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  updateSearchParams,
  resetSearchParams,
  info: tableInfo, // 改为 info 字段
} = useTable({
  apiFn: getActivationCodeList,
  apiParams: {
    code: undefined,
    type: undefined,
    typeId: undefined,
    activated: undefined,
    refunded: undefined,
    revoked: undefined,
    startDate: undefined,
    endDate: undefined,
    current: 1,
    size: 10,
  },
  columns: () => [
    {
      key: 'index',
      title: '序号',
      align: 'center',
      width: 80,
      customRender: ({ index }) => index + 1,
    },
    {
      key: 'type',
      dataIndex: 'type',
      title: '类型',
      align: 'center',
      width: 100,
      customRender: ({ record }) => (
        <Tag bordered={false} color={getTypeTagColor(record)}>
          {getTypeTagText(record)}
        </Tag>
      ),
    },
    {
      key: 'code',
      dataIndex: 'code',
      title: '激活码',
      align: 'center',
      width: 200,
      ellipsis: true,
      customRender: ({ text }) =>
        text ? (
          <Tooltip title={text} placement="topLeft">
            <span class="font-mono">{text}</span>
          </Tooltip>
        ) : (
          UNIFORM_TEXT.NULL
        ),
    },
    // {
    //   key: 'dataDate',
    //   dataIndex: 'dataDate',
    //   title: '数据日期',
    //   align: 'center',
    //   width: 180,
    //   customRender: ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : UNIFORM_TEXT.NULL),
    // },
    {
      key: 'importedAt',
      dataIndex: 'importedAt',
      title: '导入时间',
      align: 'center',
      width: 180,
      customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      key: 'activated',
      dataIndex: 'activated',
      title: '激活状态',
      align: 'center',
      width: 120,
      customRender: ({ text, record }) => (
        <Button type={text ? 'primary' : 'default'} size="small" onClick={() => handleActivate(record)}>
          {text ? '取消激活' : '点击激活'}
        </Button>
      ),
    },
    {
      key: 'activatedAt',
      dataIndex: 'activatedAt',
      title: '激活时间',
      align: 'center',
      width: 180,
      customRender: ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : UNIFORM_TEXT.NULL),
    },
    {
      key: 'refunded',
      dataIndex: 'refunded',
      title: '退款状态',
      align: 'center',
      width: 120,
      customRender: ({ text, record }) => (
        <Button
          type={text ? 'primary' : 'default'}
          size="small"
          disabled={!record.activated}
          onClick={() => handleRefund(record)}
        >
          {text ? '取消退款' : '点击退款'}
        </Button>
      ),
    },
    {
      key: 'refundedAt',
      dataIndex: 'refundedAt',
      title: '退款时间',
      align: 'center',
      width: 180,
      customRender: ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : UNIFORM_TEXT.NULL),
    },
    {
      key: 'refundNote',
      dataIndex: 'refundNote',
      title: '原因备注',
      align: 'center',
      width: 150,
      ellipsis: true,
      customRender: ({ text }) =>
        text ? (
          <Tooltip title={text} placement="topLeft">
            {text}
          </Tooltip>
        ) : (
          UNIFORM_TEXT.NULL
        ),
    },
    {
      key: 'revoked',
      dataIndex: 'revoked',
      title: '收回状态',
      align: 'center',
      width: 120,
      customRender: ({ text, record }) => (
        <Button
          type={text ? 'primary' : 'default'}
          size="small"
          disabled={!record.activated}
          onClick={() => handleRevoke(record)}
        >
          {text ? '取消收回' : '点击收回'}
        </Button>
      ),
    },
    {
      key: 'revokedAt',
      dataIndex: 'revokedAt',
      title: '收回时间',
      align: 'center',
      width: 180,
      customRender: ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : UNIFORM_TEXT.NULL),
    },
    {
      key: 'operate',
      title: $t(I18N_COMMON.OPERATE),
      align: 'center',
      width: 100,
      fixed: 'right',
      customRender: ({ record }) => (
        <div class="flex-center gap-8px">
          <Popconfirm title={$t(I18N_COMMON.CONFIRM_DELETE)} onConfirm={() => handleDelete(record.id)}>
            <Button danger size="small">
              {$t(I18N_COMMON.DELETE)}
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ],
  // 可选：通过回调接收统计信息
  onStatsUpdate: (newStats) => {
    console.log('统计信息更新:', newStats);
  },
});

const { checkedRowKeys, onDeleted } = useTableOperate(data, getData);

const toastMessage = (message: string, type: 'success' | 'error' = 'success') => {
  window.$message?.[type](message);
};

/** @description: 删除激活码 */
const handleDelete = async (id: string) => {
  if (!userInfo.buttons.includes('activation-code:delete')) {
    toastMessage('您没有删除权限', 'error');
    return;
  }

  await delActivationCode({ id }).then(({ error }) => {
    if (!error) {
      onDeleted();
      toastMessage('删除成功');
    }
  });
};

/** @description: 激活码激活/取消激活 */
const handleActivate = async (record: Api.ActivationCode.ActivationCode) => {
  if (!userInfo.buttons.includes('activation-code:activate')) {
    toastMessage('您没有激活权限', 'error');
    return;
  }

  await activateActivationCode(record.id).then(({ error }) => {
    if (!error) {
      getData();
      toastMessage(record.activated ? '已取消激活' : '激活成功');
    }
  });
};

/** @description: 激活码退款/取消退款 */
const handleRefund = (record: Api.ActivationCode.ActivationCode) => {
  if (!userInfo.buttons.includes('activation-code:refund')) {
    toastMessage('您没有退款权限', 'error');
    return;
  }

  if (!record.activated) return;

  // 设置当前操作的记录
  refundingRecord.value = record;

  // 如果已退款，直接取消退款
  if (record.refunded) {
    confirmRefund('');
    return;
  }

  // 如果未退款，弹出退款原因输入框
  refundModalVisible.value = true;
};

/** @description: 确认退款/取消退款 */
const confirmRefund = async (refundNote: string) => {
  if (!userInfo.buttons.includes('activation-code:refund')) return;
  if (!refundingRecord.value) return;

  const isRefunded = refundingRecord.value.refunded;

  await refundActivationCode(refundingRecord.value.id, { refundNote }).then(({ error }) => {
    if (!error) {
      getData();
      refundModalVisible.value = false;
      refundingRecord.value = null;
      toastMessage(isRefunded ? '已取消退款' : '退款成功');
    }
  });
};

/** @description: 激活码收回/取消收回 */
const handleRevoke = async (record: Api.ActivationCode.ActivationCode) => {
  if (!userInfo.buttons.includes('activation-code:revoke')) {
    toastMessage('您没有收回权限', 'error');
    return;
  }

  if (!record.activated) return;

  await revokeActivationCode(record.id).then(({ error }) => {
    if (!error) {
      getData();
      toastMessage(record.revoked ? '已取消收回' : '收回成功');
    }
  });
};

/** @description: 数据导入 */
const handleImport = () => {
  importDrawerVisible.value = true;
};

/** @description: 数据导出 */
const handleExport = () => {
  exportModalVisible.value = true;
};

/** @description: 导入成功回调 */
const onImportSuccess = () => {
  importDrawerVisible.value = false;
  getData();
};

/** @description: 获取表格行CSS类名 */
const getRowClassName = (record: Api.ActivationCode.ActivationCode, _index: number): string => {
  // 已退款，已回收 → 灰底色
  if (record.refunded && record.revoked) {
    return 'row-refunded-revoked';
  }
  // 已退款，未回收 → 橙底色
  if (record.refunded && !record.revoked) {
    return 'row-refunded-only';
  }
  // 默认样式
  return '';
};

// 组件挂载时获取激活码类型
onMounted(() => {
  getCodeTypeOptions();
});
</script>

<template>
  <PageContainer>
    <template #header>
      <!-- 顶部搜索 -->
      <HeaderSearch
        v-model:model="searchParams"
        :update-search-params="updateSearchParams"
        :activation-code-type-options="activationCodeTypeOptions"
        @reset="resetSearchParams"
        @search="getDataByPage"
      />
    </template>
    <template #extra>
      <div class="flex gap-12px">
        <Button
          :disabled="!userInfo.buttons.includes('activation-code:import')"
          type="primary"
          class="flex flex-center"
          @click="handleImport"
        >
          <template #icon>
            <SvgIcon icon="carbon:cloud-upload" class="mr-4px" />
          </template>
          数据导入
        </Button>
        <Button
          :disabled="!userInfo.buttons.includes('activation-code:export')"
          class="flex flex-center"
          @click="handleExport"
        >
          <template #icon>
            <SvgIcon icon="carbon:cloud-download" class="mr-4px" />
          </template>
          数据导出
        </Button>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :add-btn="false"
          @refresh="getData"
        />
      </div>
    </template>
    <!-- 表格 -->
    <ATable
      ref="tableWrapperRef"
      :columns="columns"
      :data-source="data"
      size="small"
      :scroll="scrollConfig"
      :loading="loading"
      row-key="id"
      :row-class-name="getRowClassName"
      :pagination="{
        ...mobilePagination,
        showTotal: total => `共 ${total} 条数据`,
      }"
      class="h-full"
    />

    <!-- 导入抽屉 -->
    <ImportDrawer v-model:visible="importDrawerVisible" @success="onImportSuccess" />

    <!-- 导出弹窗 -->
    <ExportModal v-model:visible="exportModalVisible" />

    <!-- 退款弹窗 -->
    <RefundModal v-model:visible="refundModalVisible" :record="refundingRecord" @confirm="confirmRefund" />
    <!-- 统计信息显示 - 精简模式 -->
    <div v-if="stats.totalCount > 0" class="stats-container mt-4 p-3 bg-blue-50 rounded-lg border border-blue-200" style="position: absolute;bottom: 10px;">
      <!-- 第一行：基础统计 + 展开按钮 -->
      <div class="flex items-center justify-between">
        <div class="flex items-center flex-wrap gap-3">
          <span class="text-blue-700 font-medium">搜索结果统计：</span>

          <span class="px-2 py-1 bg-white rounded shadow-sm border">
            总数 <strong class="ml-1 text-lg">{{ stats.totalCount }}</strong>
          </span>

          <span class="px-2 py-1 bg-green-100 text-green-800 rounded shadow-sm">
            已激活 <strong class="ml-1">{{ stats.activeCount }}</strong>
          </span>

          <span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded shadow-sm">
            已退款 <strong class="ml-1">{{ stats.refundCount }}</strong>
          </span>

          <span class="px-2 py-1 bg-red-100 text-red-800 rounded shadow-sm">
            已收回 <strong class="ml-1">{{ stats.revokedCount }}</strong>
          </span>

          <span class="px-2 py-1 bg-gray-100 text-gray-800 rounded shadow-sm">
            未激活 <strong class="ml-1">{{ stats.inactiveCount }}</strong>
          </span>
        </div>

        <!-- 展开/收起按钮 -->
        <Button
          type="link"
          size="small"
          class="flex items-center text-blue-600 hover:text-blue-800"
          @click="expandStats = !expandStats"
        >
          <template #icon>
            <SvgIcon
              :icon="expandStats ? 'carbon:chevron-up' : 'carbon:chevron-down'"
              class="mr-1"
            />
          </template>
          {{ expandStats ? '收起详情' : '展开详情' }}
        </Button>
      </div>

      <!-- 展开的详细统计信息 -->
      <div v-if="expandStats" class="mt-4 pt-4 border-t border-blue-300">
        <!-- 按类型统计 -->
        <div v-if="Object.keys(stats.typeStats).length > 0" class="mb-4">
          <h4 class="text-blue-700 font-medium mb-3">按类型统计：</h4>
          <div class="flex flex-wrap gap-3">
            <div
              v-for="(count, typeName) in stats.typeStats"
              :key="typeName"
              class="px-3 py-2 bg-blue-100 text-blue-800 rounded shadow-sm border border-blue-300 flex items-center"
            >
              <div class="w-2 h-2 bg-blue-500 rounded-full mr-2"></div>
              {{ typeName }} <strong class="ml-2 text-lg">{{ count }}</strong>
            </div>
          </div>
        </div>

        <!-- 详细统计表格 -->
        <div v-if="Object.keys(stats.detailedStats).length > 0">
          <h4 class="text-blue-700 font-medium mb-3">详细统计：</h4>
          <div class="overflow-x-auto rounded-lg border border-blue-200 bg-white">
            <table class="min-w-full">
              <thead>
                <tr class="bg-blue-50">
                  <th class="px-4 py-3 border-b text-left font-medium text-blue-700">类型</th>
                  <th class="px-4 py-3 border-b text-center font-medium text-blue-700">总数</th>
                  <th class="px-4 py-3 border-b text-center font-medium text-blue-700">已激活</th>
                  <th class="px-4 py-3 border-b text-center font-medium text-blue-700">未激活</th>
                  <th class="px-4 py-3 border-b text-center font-medium text-blue-700">已退款</th>
                  <th class="px-4 py-3 border-b text-center font-medium text-blue-700">已收回</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(typeStats, typeName) in stats.detailedStats"
                  :key="typeName"
                  class="hover:bg-blue-50 transition-colors"
                >
                  <td class="px-4 py-3 border-b">
                    <div class="flex items-center">
                      <div class="w-3 h-3 bg-blue-500 rounded mr-2"></div>
                      <span class="font-medium">{{ typeName }}</span>
                    </div>
                  </td>
                  <td class="px-4 py-3 border-b text-center font-bold">{{ typeStats.total }}</td>
                  <td class="px-4 py-3 border-b text-center">
                    <span v-if="typeStats.active > 0" class="px-2 py-1 bg-green-100 text-green-700 rounded text-sm">
                      {{ typeStats.active }}
                    </span>
                    <span v-else class="text-gray-400">0</span>
                  </td>
                  <td class="px-4 py-3 border-b text-center">
                    <span v-if="typeStats.inactive > 0" class="px-2 py-1 bg-gray-100 text-gray-700 rounded text-sm">
                      {{ typeStats.inactive }}
                    </span>
                    <span v-else class="text-gray-400">0</span>
                  </td>
                  <td class="px-4 py-3 border-b text-center">
                    <span v-if="typeStats.refunded > 0" class="px-2 py-1 bg-yellow-100 text-yellow-700 rounded text-sm">
                      {{ typeStats.refunded }}
                    </span>
                    <span v-else class="text-gray-400">0</span>
                  </td>
                  <td class="px-4 py-3 border-b text-center">
                    <span v-if="typeStats.revoked > 0" class="px-2 py-1 bg-red-100 text-red-700 rounded text-sm">
                      {{ typeStats.revoked }}
                    </span>
                    <span v-else class="text-gray-400">0</span>
                  </td>
                </tr>
              </tbody>
              <!-- 总计行 -->
              <tfoot>
                <tr class="bg-blue-50 font-bold">
                  <td class="px-4 py-3">总计</td>
                  <td class="px-4 py-3 text-center text-blue-700">{{ stats.totalCount }}</td>
                  <td class="px-4 py-3 text-center text-green-700">{{ stats.activeCount }}</td>
                  <td class="px-4 py-3 text-center text-gray-700">{{ stats.inactiveCount }}</td>
                  <td class="px-4 py-3 text-center text-yellow-700">{{ stats.refundCount }}</td>
                  <td class="px-4 py-3 text-center text-red-700">{{ stats.revokedCount }}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>
      </div>
    </div>
  </PageContainer>
</template>

<style scoped>
/* 保持原来的行样式 */
:deep(.row-refunded-only) {
  background-color: #fff7e6 !important;
}

:deep(.row-refunded-only:hover) {
  background-color: #ffe7ba !important;
}

:deep(.row-refunded-revoked) {
  background-color: #f5f5f5 !important;
}

:deep(.row-refunded-revoked:hover) {
  background-color: #e8e8e8 !important;
}

/* 统计信息展开动画 */
.stats-container {
  transition: all 0.3s ease;
}

/* 展开内容动画 */
.stats-container > div:last-child {
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-container {
    padding: 12px;
  }

  .flex-wrap > span {
    flex: 1 0 calc(50% - 0.5rem);
    margin-bottom: 0.5rem;
  }

  .stats-container > div:first-child {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .stats-container > div:first-child > div:first-child {
    width: 100%;
  }
}
</style>
