<template>
  <a-modal
    v-model:visible="modalVisible"
    :title="`Token绑卡记录 - ${tokenName}`"
    width="90%"
    :footer="false"
    @cancel="handleCancel"
  >
    <!-- 视图切换和统计信息 -->
    <div class="modal-header">
      <div class="view-controls">
        <a-radio-group v-model="viewMode" type="button" size="small">
          <a-radio value="table">
            <template #radio="{ checked }">
              <a-button :type="checked ? 'primary' : 'secondary'" size="small">
                <template #icon>
                  <icon-list />
                </template>
                表格视图
              </a-button>
            </template>
          </a-radio>
          <a-radio value="card">
            <template #radio="{ checked }">
              <a-button :type="checked ? 'primary' : 'secondary'" size="small">
                <template #icon>
                  <icon-apps />
                </template>
                卡片视图
              </a-button>
            </template>
          </a-radio>
        </a-radio-group>
      </div>

      <div class="stats-info">
        <a-space size="large">
          <a-statistic title="总记录数" :value="pagination.total" />
          <a-statistic
            title="总金额"
            :value="totalAmount"
            :precision="2"
            prefix="¥"
          />
        </a-space>
      </div>
    </div>

    <!-- 表格视图 -->
    <div v-if="viewMode === 'table'" class="table-view">
      <a-table
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          pageSizeOptions: [10, 20, 50, 100],
          showPageSize: true,
          showTotal: true
        }"
        :columns="columns"
        :data="renderData"
        :scroll="{ x: 1200 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #createdAt="{ record }">
          {{ formatDateTime(record.createdAt) }}
        </template>

        <template #amount="{ record }">
          <a-tag :color="getAmountColor(record.amount)">
            ¥{{ formatAmount(record.amount) }}
          </a-tag>
        </template>

        <template #cardNumber="{ record }">
          <a-typography-text
            :copyable="{ text: record.cardNumber }"
            :ellipsis="{ rows: 1, showTooltip: true }"
          >
            {{ record.cardNumber }}
          </a-typography-text>
        </template>

        <template #cardPassword="{ record }">
          <a-typography-text
            :copyable="{ text: record.cardPassword }"
            :ellipsis="{ rows: 1, showTooltip: true }"
          >
            {{ record.cardPassword }}
          </a-typography-text>
        </template>
      </a-table>
    </div>

    <!-- 卡片视图 -->
    <div v-else class="card-view">
      <a-spin :loading="loading" style="width: 100%">
        <div class="card-grid">
          <a-card
            v-for="record in renderData"
            :key="record.id"
            class="binding-card"
            :hoverable="true"
          >
            <template #header>
              <div class="card-header">
                <div class="card-title">
                  <a-tag color="blue" size="small">ID: {{ record.id }}</a-tag>
                  <a-tag v-if="record.orderId" color="green" size="small">
                    订单: {{ record.orderId }}
                  </a-tag>
                </div>
                <div class="card-amount">
                  <a-statistic
                    :value="record.amount"
                    :precision="2"
                    prefix="¥"
                    :value-style="{ color: '#00b42a', fontSize: '16px' }"
                  />
                </div>
              </div>
            </template>

            <div class="card-content">
              <a-descriptions :column="1" size="small">
                <a-descriptions-item label="卡号">
                  <a-typography-text
                    :copyable="{ text: record.cardNumber }"
                    :ellipsis="{ rows: 1, showTooltip: true }"
                    class="copy-text"
                  >
                    {{ record.cardNumber }}
                  </a-typography-text>
                </a-descriptions-item>

                <a-descriptions-item label="卡密">
                  <a-typography-text
                    :copyable="{ text: record.cardPassword }"
                    :ellipsis="{ rows: 1, showTooltip: true }"
                    class="copy-text"
                  >
                    {{ record.cardPassword }}
                  </a-typography-text>
                </a-descriptions-item>

                <a-descriptions-item label="创建时间">
                  <a-typography-text type="secondary">
                    {{ formatDateTime(record.createdAt) }}
                  </a-typography-text>
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </a-card>
        </div>

        <!-- 分页控制 -->
        <div v-if="pagination.total > 0" class="card-pagination">
          <a-pagination
            :current="pagination.current"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :page-size-options="[10, 20, 50, 100]"
            show-page-size
            show-total
            @change="onPageChange"
            @page-size-change="onPageSizeChange"
          />
        </div>

        <!-- 空状态 -->
        <a-empty
          v-if="!loading && renderData.length === 0"
          description="暂无绑卡记录"
        />
      </a-spin>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue';
import { TableColumnData } from '@arco-design/web-vue';
import IconList from '@arco-design/web-vue/es/icon/icon-list';
import IconApps from '@arco-design/web-vue/es/icon/icon-apps';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import {
  ApiCardBindingListByTokenGetPageSizeEnum,
  KamiApiCamelOilV1CardBindingInfo
} from '@/api/generated/index.ts';
import { jdV2TokenClient } from '@/api/index.ts';

interface Props {
  visible: boolean;
  tokenId: number;
  tokenName: string;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
}

const props = withDefaults(defineProps<Props>(), {
  tokenId: 0,
  tokenName: ''
});

const emit = defineEmits<Emits>();

const modalVisible = computed({
  get: () => props.visible,
  set: value => emit('update:visible', value)
});

const basePagination: Pagination = {
  current: 1,
  pageSize: 20
};
const pagination = reactive({
  ...basePagination
});

const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    render: ({ rowIndex }) => {
      return rowIndex + 1 + (pagination.current - 1) * pagination.pageSize;
    }
  },
  {
    title: '绑卡ID',
    dataIndex: 'id',
    width: 100
  },
  {
    title: 'Token ID',
    dataIndex: 'tokenId',
    width: 100
  },
  {
    title: 'Token名称',
    dataIndex: 'tokenName',
    width: 150,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '订单ID',
    dataIndex: 'orderId',
    width: 100
  },
  {
    title: '卡号',
    dataIndex: 'cardNumber',
    width: 200,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '卡密',
    dataIndex: 'cardPassword',
    width: 150,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '金额',
    dataIndex: 'amount',
    slotName: 'amount',
    width: 120,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    slotName: 'createdAt',
    width: 180
  }
];

const { loading, setLoading } = useLoading(true);
const renderData = ref<KamiApiCamelOilV1CardBindingInfo[]>([]);

// 视图模式
const viewMode = ref<'table' | 'card'>('table');

// 计算总金额
const totalAmount = computed(() => {
  return renderData.value.reduce((sum, record) => {
    return sum + (Number(record.amount) || 0);
  }, 0);
});

// 根据金额获取颜色
const getAmountColor = (amount: number | undefined): string => {
  if (!amount) return 'gray';
  if (amount < 100) return 'orange';
  if (amount < 500) return 'blue';
  return 'green';
};

const fetchData = async (params: any = { current: 1, pageSize: 20 }) => {
  if (!props.tokenId) {
    return;
  }

  setLoading(true);
  try {
    const { data } = await jdV2TokenClient.apiCardBindingListByTokenGet({
      current: params.current,
      pageSize:
        params.pageSize as unknown as ApiCardBindingListByTokenGetPageSizeEnum,
      tokenId: props.tokenId
    });

    renderData.value = data.list || [];
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = data.total || 0;
  } catch (err) {
    console.error('获取绑卡记录失败:', err);
    renderData.value = [];
    pagination.total = 0;
  } finally {
    setLoading(false);
  }
};

const onPageChange = (current: number) => {
  fetchData({ ...pagination, current });
};

const onPageSizeChange = (pageSize: number) => {
  fetchData({ ...pagination, pageSize });
};

const handleCancel = () => {
  emit('update:visible', false);
};

const formatAmount = (amount: any): string => {
  if (!amount) return '-';
  if (typeof amount === 'object') {
    return JSON.stringify(amount);
  }
  return String(amount);
};

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  visible => {
    if (visible && props.tokenId) {
      // 重置分页并获取数据
      Object.assign(pagination, basePagination);
      fetchData();
    }
  }
);
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .card-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .modal-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .view-controls {
    justify-content: center;
  }

  .stats-info {
    justify-content: center;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}

@media (width <= 480px) {
  .card-grid {
    grid-template-columns: 1fr;
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: var(--color-bg-2);
  border-radius: 6px;
  border: 1px solid var(--color-border-2);
}

.view-controls {
  display: flex;
  align-items: center;
}

.stats-info {
  display: flex;
  align-items: center;
}

/* 表格视图样式 */
.table-view {
  margin-top: 16px;
}

/* 卡片视图样式 */
.card-view {
  margin-top: 16px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
  min-height: 200px;
}

.binding-card {
  transition: all 0.2s ease;
  border: 1px solid var(--color-border-2);
}

.binding-card:hover {
  border-color: var(--color-primary-light-4);
  box-shadow: 0 4px 12px rgb(0 0 0 / 8%);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.card-title {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.card-amount {
  display: flex;
  align-items: center;
}

.card-content {
  padding: 0;
}

.copy-text {
  font-family: Monaco, Menlo, 'Ubuntu Mono', monospace;
  font-size: 13px;
  background: var(--color-fill-2);
  padding: 2px 6px;
  border-radius: 4px;
  word-break: break-all;
}

.card-pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 16px 0;
}

/* 模态框样式优化 */
:deep(.arco-modal-body) {
  max-height: 80vh;
  overflow-y: auto;
  padding: 20px 24px;

  /* 确保滚动条样式跟随主题 */
  scrollbar-width: thin;
  scrollbar-color: var(--color-border-3) transparent;
}

:deep(.arco-modal-body::-webkit-scrollbar) {
  width: 8px;
}

:deep(.arco-modal-body::-webkit-scrollbar-thumb) {
  background-color: var(--color-border-3);
  border-radius: 4px;
}

:deep(.arco-modal-body::-webkit-scrollbar-track) {
  background-color: transparent;
}

/* 表格优化 */
:deep(.arco-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.arco-table-th) {
  background: var(--color-bg-2);
  font-weight: 600;
}

:deep(.arco-table-container) {
  border: 1px solid var(--color-border-2);
}

/* 单选按钮组样式 */
:deep(.arco-radio-group) {
  background: transparent;
}

:deep(.arco-radio-button) {
  background: var(--color-bg-2);
  border-color: var(--color-border-2);
}

:deep(.arco-radio-button:hover) {
  border-color: var(--color-primary-light-4);
}

/* 统计信息样式 */
:deep(.arco-statistic) {
  text-align: center;
}

:deep(.arco-statistic-title) {
  font-size: 14px;
  color: var(--color-text-3);
  margin-bottom: 4px;
}

:deep(.arco-statistic-value) {
  font-size: 20px;
  font-weight: 600;
}

/* 卡片描述列表样式 */
:deep(.arco-descriptions-item-label) {
  font-weight: 500;
  color: var(--color-text-2);
  min-width: 60px;
}

:deep(.arco-descriptions-item-value) {
  color: var(--color-text-1);
}

/* 加载状态优化 */
:deep(.arco-spin-container) {
  min-height: 300px;
  display: flex;
  flex-direction: column;
}

/* 空状态样式 */
:deep(.arco-empty) {
  margin: 40px 0;
}

/* 标签样式优化 */
:deep(.arco-tag) {
  border-radius: 4px;
  font-weight: 500;
}

/* 按钮图标样式 */
:deep(.arco-btn .arco-icon) {
  margin-right: 4px;
}

/* 模态框头部样式 */
</style>
