<template>
  <a-modal
    v-model:visible="modalVisible"
    title="订单历史记录"
    width="900px"
    :footer="false"
  >
    <a-spin :loading="loading" style="width: 100%">
      <a-table
        :data="historyData"
        :columns="columns"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          pageSizeOptions: [10, 20, 50],
          showPageSize: true,
          showTotal: true
        }"
        :loading="tableLoading"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #action="{ record }">
          <a-tag :color="actionMapper(record.action).color">
            {{ actionMapper(record.action).text }}
          </a-tag>
        </template>

        <template #status="{ record }">
          <a-tag
            v-if="record.status"
            :color="statusMapper(record.status).color"
          >
            {{ statusMapper(record.status).text }}
          </a-tag>
          <span v-else>-</span>
        </template>

        <template #details="{ record }">
          <a-tooltip v-if="record.details" :content="record.details">
            <a-button size="small" type="text">
              <template #icon>
                <icon-eye />
              </template>
              查看详情
            </a-button>
          </a-tooltip>
          <span v-else>-</span>
        </template>
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { Message, TableColumnData } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { jdV2OrderClient } from '@/api/index.ts';
import type { KamiApiCamelOilV1OrderHistoryItem } from '@/api/generated/models/index.ts';
import type { ApiJdV2OrderHistoryGetPageSizeEnum } from '@/api/generated/apis/jdv2-order-api';

// Props 定义
interface Props {
  visible: boolean;
  orderNo: string;
}

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

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

const emit = defineEmits<Emits>();

// 响应式数据
const { loading, setLoading } = useLoading(false);
const tableLoading = ref(false);
const historyData = ref<KamiApiCamelOilV1OrderHistoryItem[]>([]);

// 基础分页配置
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: '操作类型',
    dataIndex: 'action',
    slotName: 'action',
    width: 120
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    width: 120
  },
  {
    title: '操作状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100
  },
  {
    title: '操作说明',
    dataIndex: 'description',
    width: 200,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '详细信息',
    dataIndex: 'details',
    slotName: 'details',
    width: 120
  },
  {
    title: '操作时间',
    dataIndex: 'createdAt',
    width: 180
  }
];

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

/**
 * 获取订单历史记录数据
 * @param params 查询参数
 */
const fetchHistoryData = async (
  params: {
    current: number;
    pageSize: ApiJdV2OrderHistoryGetPageSizeEnum;
  } = { current: 1, pageSize: 20 }
) => {
  if (!props.orderNo) return;

  tableLoading.value = true;
  try {
    const { data } = await jdV2OrderClient.apiJdV2OrderHistoryGet({
      current: params.current,
      pageSize: params.pageSize as ApiJdV2OrderHistoryGetPageSizeEnum,
      orderNo: props.orderNo
    });

    historyData.value = data.list || [];
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = data.total || 0;
  } catch (error) {
    console.error('获取订单历史记录失败:', error);
    Message.error('获取订单历史记录失败');
    historyData.value = [];
  } finally {
    tableLoading.value = false;
  }
};

/**
 * 页码变化处理
 * @param current 当前页码
 */
const onPageChange = (current: number) => {
  fetchHistoryData({
    ...pagination,
    current
  });
};

/**
 * 页面大小变化处理
 * @param pageSize 每页条数
 */
const onPageSizeChange = (pageSize: number) => {
  fetchHistoryData({
    ...pagination,
    pageSize,
    current: 1
  });
};

/**
 * 操作类型映射器
 * @param action 操作类型
 * @returns 操作类型文本和颜色
 */
const actionMapper = (action: string): { text: string; color: string } => {
  switch (action) {
    case 'create':
      return { text: '创建订单', color: 'blue' };
    case 'pay':
      return { text: '支付', color: 'green' };
    case 'callback':
      return { text: '回调', color: 'orange' };
    case 'retry':
      return { text: '重试', color: 'purple' };
    case 'cancel':
      return { text: '取消', color: 'red' };
    case 'complete':
      return { text: '完成', color: 'green' };
    case 'fail':
      return { text: '失败', color: 'red' };
    default:
      return { text: '未知', color: 'gray' };
  }
};

/**
 * 状态映射器
 * @param status 状态值
 * @returns 状态文本和颜色
 */
const statusMapper = (status: number): { text: string; color: string } => {
  switch (status) {
    case 1:
      return { text: '成功', color: 'green' };
    case 0:
      return { text: '失败', color: 'red' };
    default:
      return { text: '未知', color: 'gray' };
  }
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  visible => {
    if (visible && props.orderNo) {
      fetchHistoryData();
    }
  },
  { immediate: true }
);

// 监听订单号变化
watch(
  () => props.orderNo,
  orderNo => {
    if (orderNo && props.visible) {
      fetchHistoryData();
    }
  }
);
</script>

<style scoped>
:deep(.arco-modal-body) {
  max-height: 70vh;
  overflow-y: auto;
}
</style>
