<template>
  <a-drawer
    :visible="visible"
    :width="800"
    :title="`Cookie变更记录 - ${cookieId}`"
    :footer="false"
    unmount-on-close
    @cancel="handleCancel"
  >
    <a-spin :loading="loading" style="width: 100%">
      <div v-if="historyData.length > 0" class="history-container">
        <a-timeline>
          <a-timeline-item
            v-for="(item, index) in historyData"
            :key="item.historyUuid || index"
            :dot-color="getTimelineDotColor(item.changeType)"
            :dot-type="index === 0 ? 'filled' : 'hollow'"
          >
            <div class="timeline-content">
              <!-- 变更时间和类型 -->
              <div class="timeline-header">
                <div class="time-info">
                  <span class="change-time">
                    {{ formatTime(item.createdAt) }}
                  </span>
                  <a-tag
                    :color="getChangeTypeColor(item.changeType)"
                    size="small"
                  >
                    {{ getChangeTypeText(item.changeType) }}
                  </a-tag>
                </div>
              </div>

              <!-- 失败次数 -->
              <div
                v-if="item.failureCount && item.failureCount > 0"
                class="failure-info"
              >
                <span class="label">失败次数：</span>
                <a-tag color="red" size="small">
                  {{ item.failureCount }} 次
                </a-tag>
              </div>

              <!-- 关联订单 -->
              <div v-if="item.userOrderId" class="order-info">
                <span class="label">关联用户订单：</span>
                <a-typography-text copyable class="order-id">
                  {{ item.userOrderId }}
                </a-typography-text>
              </div>

              <!-- 关联订单 -->
              <div v-if="item.orderId" class="order-info">
                <span class="label">关联订单：</span>
                <a-typography-text copyable class="order-id">
                  {{ item.orderId }}
                </a-typography-text>
              </div>

              <!-- 备注信息 -->
              <div v-if="item.remark" class="remark-info">
                <span class="label">备注信息：</span>
                <a-typography-text class="remark-content">
                  {{ item.remark }}
                </a-typography-text>
              </div>
            </div>
          </a-timeline-item>
        </a-timeline>

        <!-- 加载更多 -->
        <div v-if="hasMore" class="load-more">
          <a-button :loading="loadingMore" type="outline" @click="loadMore">
            加载更多
          </a-button>
        </div>
      </div>

      <a-empty v-else description="暂无变更记录" />
    </a-spin>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import { jdHistoryClient } from '@/api';
import type { KamiApiJdCookieV1CookieHistoryInfo } from '@/api/generated';
import { KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum } from '@/api/generated';

interface Props {
  visible: boolean;
  cookieId: string;
}

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

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 状态管理
const loading = ref(false);
const loadingMore = ref(false);
const historyData = ref<KamiApiJdCookieV1CookieHistoryInfo[]>([]);
const hasMore = ref(false);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
});

// 处理取消
const handleCancel = (): void => {
  emit('update:visible', false);
};

// 格式化时间
const formatTime = (timeStr?: string): string => {
  if (!timeStr) return '-';
  try {
    const date = new Date(timeStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch {
    return timeStr;
  }
};

// 获取时间线节点颜色
const getTimelineDotColor = (
  changeType?: KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum
): string => {
  switch (changeType) {
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Update:
      return '#165DFF';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Use:
      return '#FF7D00';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Suspend:
      return '#F53F3F';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Resume:
      return '#00B42A';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Fail:
      return '#F53F3F';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.RefreshFail:
      return '#FF7D00';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Create:
      return '#00B42A';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Delete:
      return '#F53F3F';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Replaced:
      return '#722ED1';
    default:
      return '#86909C';
  }
};

// 获取变更类型颜色
const getChangeTypeColor = (
  changeType?: KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum
): string => {
  switch (changeType) {
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Update:
      return 'blue';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Use:
      return 'orange';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Suspend:
      return 'red';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Resume:
      return 'green';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Fail:
      return 'red';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.RefreshFail:
      return 'orange';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Create:
      return 'green';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Delete:
      return 'red';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Replaced:
      return 'purple';
    default:
      return 'gray';
  }
};

// 获取变更类型文本
const getChangeTypeText = (
  changeType?: KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum
): string => {
  switch (changeType) {
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Update:
      return '更新';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Use:
      return '使用';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Suspend:
      return '暂停';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Resume:
      return '恢复';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Fail:
      return '失败';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.RefreshFail:
      return '刷新失败';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Create:
      return '创建';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Delete:
      return '删除';
    case KamiApiJdCookieV1CookieHistoryInfoChangeTypeEnum.Replaced:
      return '换绑';
    default:
      return changeType || '未知';
  }
};

// 获取变更记录数据
const fetchHistoryData = async (isLoadMore = false): Promise<void> => {
  if (!props.cookieId) return;

  if (isLoadMore) {
    loadingMore.value = true;
  } else {
    loading.value = true;
    pagination.current = 1;
  }

  try {
    const response = await jdHistoryClient.apiJdCookieHistoryCookieGet({
      cookieId: props.cookieId,
      page: pagination.current,
      size: pagination.pageSize
    });

    const newData = response.data.list || [];

    if (isLoadMore) {
      historyData.value = [...historyData.value, ...newData];
    } else {
      historyData.value = newData;
    }

    pagination.total = response.data.total || 0;
    hasMore.value = historyData.value.length < pagination.total;
  } catch (error) {
    Message.error('获取变更记录失败');
    if (!isLoadMore) {
      historyData.value = [];
      pagination.total = 0;
    }
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 加载更多
const loadMore = (): void => {
  pagination.current += 1;
  fetchHistoryData(true);
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  newVal => {
    if (newVal && props.cookieId) {
      pagination.current = 1;
      historyData.value = [];
      fetchHistoryData();
    } else {
      historyData.value = [];
      pagination.total = 0;
      hasMore.value = false;
    }
  }
);
</script>

<style scoped>
.history-container {
  max-height: calc(100vh - 120px);
  overflow-y: auto;
  padding-right: 8px;
}

.timeline-content {
  padding: 12px 0;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.time-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.change-time {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-1);
}

.failure-info,
.order-info,
.remark-info {
  margin: 4px 0;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.label {
  font-size: 13px;
  color: var(--color-text-3);
  min-width: 70px;
}

.order-id {
  font-family: Monaco, Menlo, 'Ubuntu Mono', monospace;
  font-size: 13px;
}

.remark-content {
  font-size: 13px;
  color: var(--color-text-2);
  word-break: break-all;
  flex: 1;
}

.load-more {
  text-align: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border-2);
}

:deep(.arco-timeline-item-content) {
  padding-bottom: 16px;
}

:deep(.arco-timeline-item:last-child .arco-timeline-item-content) {
  padding-bottom: 0;
}

/* 滚动条样式 */
.history-container::-webkit-scrollbar {
  width: 6px;
}

.history-container::-webkit-scrollbar-track {
  background: var(--color-fill-1);
  border-radius: 3px;
}

.history-container::-webkit-scrollbar-thumb {
  background: var(--color-border-3);
  border-radius: 3px;
}

.history-container::-webkit-scrollbar-thumb:hover {
  background: var(--color-border-4);
}
</style>
