<template>
  <a-drawer
    v-model:visible="visible"
    :title="drawerTitle"
    width="600px"
    :footer="false"
    unmount-on-close
  >
    <div v-loading="loading" class="order-history-drawer">
      <div v-if="!loading && historyList.length === 0" class="empty-state">
        <a-empty description="暂无变更记录" />
      </div>

      <a-timeline v-else class="history-timeline">
        <a-timeline-item
          v-for="(item, index) in historyList"
          :key="item.historyUuid || index"
          :dot-color="getTimelineDotColor(item.changeType)"
          :line-type="index === historyList.length - 1 ? 'dashed' : 'solid'"
        >
          <template #dot>
            <icon-plus
              v-if="item.changeType === 'create'"
              :style="{ color: '#00b42a', fontSize: '16px' }"
            />
            <icon-link
              v-else-if="item.changeType === 'bind'"
              :style="{ color: '#165dff', fontSize: '16px' }"
            />
            <icon-check-circle
              v-else-if="item.changeType === 'pay'"
              :style="{ color: '#00b42a', fontSize: '16px' }"
            />
            <icon-clock-circle
              v-else-if="item.changeType === 'expire'"
              :style="{ color: '#f53f3f', fontSize: '16px' }"
            />
            <icon-close-circle
              v-else-if="item.changeType === 'ck_failed'"
              :style="{ color: '#ff7d00', fontSize: '16px' }"
            />
            <icon-exclamation-circle
              v-else-if="item.changeType === 'jd_order_failed'"
              :style="{ color: '#f53f3f', fontSize: '16px' }"
            />
            <icon-minus-circle
              v-else-if="item.changeType === 'stock_failed'"
              :style="{ color: '#f53f3f', fontSize: '16px' }"
            />
            <icon-more v-else :style="{ color: '#86909c', fontSize: '16px' }" />
          </template>

          <div class="timeline-content">
            <div class="timeline-header">
              <a-tag :color="getStatusColor(item.changeType)" size="small">
                {{ getStatusText(item.changeType) }}
              </a-tag>
              <span class="timeline-time">
                {{ formatTime(item.createdAt) }}
              </span>
            </div>

            <div class="timeline-details">
              <div v-if="item.orderId" class="detail-item">
                <span class="detail-label">订单号:</span>
                <a-typography-text copyable>
                  {{ item.orderId }}
                </a-typography-text>
              </div>

              <div v-if="item.jdOrderId" class="detail-item">
                <span class="detail-label">京东订单号:</span>
                <a-typography-text copyable>
                  {{ item.jdOrderId }}
                </a-typography-text>
              </div>

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

      <!-- 分页 -->
      <div v-if="total > pageSize" class="pagination-wrapper">
        <a-pagination
          :current="currentPage"
          :page-size="pageSize"
          :total="total"
          :show-total="true"
          :show-jumper="true"
          :show-page-size="true"
          @change="onPageChange"
          @page-size-change="onPageSizeChange"
        />
      </div>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import {
  IconPlus,
  IconLink,
  IconClose,
  IconCheckCircle,
  IconClockCircle,
  IconCloseCircle,
  IconExclamationCircle,
  IconMinusCircle,
  IconSync,
  IconMore
} from '@arco-design/web-vue/es/icon';
import { jdHistoryClient } from '@/api';
import type { KamiApiJdCookieV1OrderHistoryInfo } from '@/api/generated';

interface Props {
  visible: boolean;
  orderId?: string;
}

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

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  orderId: ''
});

const emit = defineEmits<Emits>();

// 数据状态
const loading = ref(false);
const historyList = ref<KamiApiJdCookieV1OrderHistoryInfo[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit('update:visible', value)
});

const drawerTitle = computed(() => {
  return props.orderId ? `订单变更记录 - ${props.orderId}` : '订单变更记录';
});

// 获取变更记录
const fetchHistory = async () => {
  if (!props.orderId) return;

  loading.value = true;
  try {
    const response = await jdHistoryClient.apiJdCookieHistoryOrderGet({
      orderId: props.orderId,
      page: currentPage.value,
      size: pageSize.value
    });

    historyList.value = response.data.list || [];
    total.value = response.data.total || 0;
  } catch (error) {
    Message.error('获取变更记录失败');
    historyList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 分页处理
const onPageChange = (page: number) => {
  currentPage.value = page;
  fetchHistory();
};

const onPageSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchHistory();
};

// 获取状态颜色
const getStatusColor = (changeType?: string): string => {
  const colorMap: Record<string, string> = {
    create: 'green', // 创建
    pay: 'green', // 支付
    expire: 'red', // 过期
    bind: 'blue', // 绑定
    ck_failed: 'orange', // Ck失败
    jd_order_failed: 'red', // 下单京东订单失败
    stock_failed: 'red' // 库存问题
  };
  return colorMap[changeType || ''] || 'gray';
};

// 获取状态文本
const getStatusText = (changeType?: string): string => {
  const textMap: Record<string, string> = {
    create: '创建',
    pay: '支付',
    expire: '过期',
    bind: '绑定',
    ck_failed: 'Ck失败',
    jd_order_failed: '下单京东订单失败',
    stock_failed: '库存问题'
  };
  return textMap[changeType || ''] || '未知状态';
};

// 获取时间线点颜色
const getTimelineDotColor = (changeType?: string): string => {
  const colorMap: Record<string, string> = {
    create: '#00b42a', // 创建
    pay: '#00b42a', // 支付
    expire: '#f53f3f', // 过期
    bind: '#165dff', // 绑定
    ck_failed: '#ff7d00', // Ck失败
    jd_order_failed: '#f53f3f', // 下单京东订单失败
    stock_failed: '#f53f3f' // 库存问题
  };
  return colorMap[changeType || ''] || '#86909c';
};

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

// 监听visible变化，自动重置分页并获取数据
watch(
  () => props.visible,
  newVal => {
    if (newVal && props.orderId) {
      currentPage.value = 1;
      pageSize.value = 20;
      fetchHistory();
    }
  }
);
</script>

<style scoped>
.order-history-drawer {
  min-height: 400px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.history-timeline {
  margin-top: 16px;
}

.timeline-content {
  padding-left: 8px;
}

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

.timeline-time {
  font-size: 12px;
  color: var(--color-text-3);
}

.timeline-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 14px;
}

.remark-item {
  align-items: flex-start;
}

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

.detail-label {
  color: var(--color-text-3);
  min-width: 80px;
}

.pagination-wrapper {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
</style>
