<template>
  <div class="container">
    <Breadcrumb :items="['京东订单管理', '京东订单']" />
    <a-card class="general-card" title="京东订单查询">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="keyword" label="订单号">
                  <a-input
                    v-model="formModel.keyword"
                    placeholder="请输入订单号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" label="订单状态">
                  <a-select
                    v-model="formModel.status"
                    placeholder="请选择订单状态"
                    allow-clear
                  >
                    <a-option :value="1">待支付</a-option>
                    <a-option :value="2">已支付</a-option>
                    <a-option :value="3">已发货</a-option>
                    <a-option :value="4">已过期</a-option>
                    <a-option :value="5">已取消</a-option>
                    <a-option :value="6">Ck失败</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="dateRange" label="时间范围">
                  <a-range-picker
                    v-model="formModel.dateRange"
                    :shortcuts="dateRangeShortcuts"
                    format="YYYY-MM-DD"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 42px" direction="vertical" />
        <a-col flex="172px" style="text-align: right">
          <a-space direction="horizontal" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
            <a-button type="outline" @click="handleExport">
              <template #icon>
                <icon-download />
              </template>
              导出
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />

      <a-table
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          pageSizeOptions: [10, 20, 50, 100],
          showPageSize: true
        }"
        :columns="columns"
        :data="renderData"
        :scroll="{ x: 1800 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #status="{ record }">
          <a-tag v-if="record.status === 1" color="orange">待支付</a-tag>
          <a-tag v-else-if="record.status === 2" color="green">已支付</a-tag>
          <a-tag v-else-if="record.status === 3" color="blue">已发货</a-tag>
          <a-tag v-else-if="record.status === 4" color="red">已过期</a-tag>
          <a-tag v-else-if="record.status === 5" color="gray">已取消</a-tag>
          <a-tag v-else-if="record.status === 6" color="purple">Ck失败</a-tag>
          <a-tag v-else color="gray">未知</a-tag>
        </template>
        <template #amount="{ record }">
          <span class="arco-text-primary">
            ¥{{ record.amount?.toFixed(2) || '0.00' }}
          </span>
        </template>
        <template #wxPayUrl="{ record }">
          <a-space>
            <a-link
              v-if="record.wxPayUrl"
              :href="record.wxPayUrl"
              target="_blank"
              type="primary"
            >
              <template #icon>
                <icon-link />
              </template>
              打开支付链接
            </a-link>
            <a-typography-text v-else type="secondary">无</a-typography-text>
          </a-space>
        </template>
        <template #operations="{ record }">
          <a-space size="small">
            <a-tooltip content="查看详情">
              <a-button size="small" @click="showDetail(record)">
                <template #icon>
                  <icon-eye />
                </template>
              </a-button>
            </a-tooltip>
            <a-tooltip content="变更记录">
              <a-button size="small" @click="showHistory(record)">
                <template #icon>
                  <icon-history />
                </template>
              </a-button>
            </a-tooltip>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 订单详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      title="京东订单详情"
      width="800px"
      :footer="false"
    >
      <div v-if="currentOrder" class="order-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="京东订单号">
            <a-typography-text v-if="currentOrder.jdOrderId" copyable>
              {{ currentOrder.jdOrderId }}
            </a-typography-text>
            <a-typography-text v-else type="secondary">无</a-typography-text>
          </a-descriptions-item>
          <a-descriptions-item label="内部订单号">
            <a-typography-text v-if="currentOrder.orderId" copyable>
              {{ currentOrder.orderId }}
            </a-typography-text>
            <a-typography-text v-else type="secondary">无</a-typography-text>
          </a-descriptions-item>
          <a-descriptions-item label="支付ID">
            <a-typography-text v-if="currentOrder.payId" copyable>
              {{ currentOrder.payId }}
            </a-typography-text>
            <a-typography-text v-else type="secondary">无</a-typography-text>
          </a-descriptions-item>
          <a-descriptions-item label="Cookie ID">
            <a-typography-text v-if="currentOrder.cookieId" copyable>
              {{ currentOrder.cookieId }}
            </a-typography-text>
            <a-typography-text v-else type="secondary">无</a-typography-text>
          </a-descriptions-item>
          <a-descriptions-item label="商品品类">
            {{ getCategoryChineseName(currentOrder.category) }}
          </a-descriptions-item>
          <a-descriptions-item label="订单金额">
            <span class="arco-text-primary">
              ¥{{ currentOrder.amount?.toFixed(2) || '0.00' }}
            </span>
          </a-descriptions-item>
          <a-descriptions-item label="订单状态">
            <a-tag :color="getStatusColor(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="支付链接">
            <a-space v-if="currentOrder.wxPayUrl">
              <a-link
                :href="currentOrder.wxPayUrl"
                target="_blank"
                type="primary"
              >
                <template #icon>
                  <icon-link />
                </template>
                打开支付链接
              </a-link>
            </a-space>
            <a-typography-text v-else type="secondary">无</a-typography-text>
          </a-descriptions-item>
          <a-descriptions-item label="支付链接过期时间">
            {{ currentOrder.wxPayExpireAt || '-' }}
          </a-descriptions-item>
          <!-- <a-descriptions-item label="关联订单ID">
            {{ currentOrder.orderId || '-' }}
          </a-descriptions-item> -->
          <a-descriptions-item label="卡号">
            <a-typography-text v-if="currentOrder.cardNo" copyable>
              {{ currentOrder.cardNo }}
            </a-typography-text>
            <a-typography-text v-else type="secondary">无</a-typography-text>
          </a-descriptions-item>
          <a-descriptions-item label="卡密">
            <a-typography-text v-if="currentOrder.cardPassword" copyable>
              {{ currentOrder.cardPassword }}
            </a-typography-text>
            <a-typography-text v-else type="secondary">无</a-typography-text>
          </a-descriptions-item>
          <a-descriptions-item label="支付完成时间">
            {{ currentOrder.paidAt || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="订单过期时间">
            {{ currentOrder.orderExpireAt || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="卡密提取时间">
            {{ currentOrder.cardExtractedAt || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ currentOrder.createdAt || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ currentOrder.updatedAt || '-' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 变更记录侧边栏 -->
    <order-history-drawer
      v-model:visible="historyVisible"
      :jd-order-id="currentOrderId"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { TableColumnData } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { jdOrderClient } from '@/api';
import type { KamiApiJdCookieV1JdOrderInfo } from '@/api/generated';
import { getCategoryChineseName } from '@/utils/categoryMapping';
import { JDOrderManagementApiFactory } from '@/api/generated';
import OrderHistoryDrawer from './components/jd-order-history-drawer.vue';
import { render } from 'nprogress';

const { loading, setLoading } = useLoading(true);

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

// 日期范围快捷选项
const dateRangeShortcuts = [
  {
    label: '今天',
    value: () => {
      const today = new Date();
      return [today, today];
    }
  },
  {
    label: '最近7天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 6);
      return [start, end];
    }
  },
  {
    label: '最近30天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 29);
      return [start, end];
    }
  }
];

// 表格列配置
const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    render: ({ rowIndex }) => {
      return rowIndex + 1 + (pagination.current - 1) * pagination.pageSize;
    }
  },
  {
    title: '京东订单号',
    dataIndex: 'jdOrderId',
    width: 180,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '内部订单号',
    dataIndex: 'orderId',
    width: 160,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '支付ID',
    dataIndex: 'payId',
    width: 140,
    ellipsis: true,
    tooltip: true
  },
  {
    title: 'Cookie名称',
    dataIndex: 'cookie',
    width: 120,
    ellipsis: true,
    tooltip: true,
    render: ({ record }) => {
      return record.cookie?.accountName || '-';
    }
  },
  {
    title: '商品品类',
    dataIndex: 'category',
    width: 120,
    ellipsis: true,
    tooltip: true,
    render: ({ record }) => {
      return getCategoryChineseName(record.category) || '-';
    }
  },
  {
    title: '订单金额',
    dataIndex: 'amount',
    slotName: 'amount',
    width: 100
  },
  {
    title: '订单状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100
  },
  // {
  //   title: '关联订单ID',
  //   dataIndex: 'orderId',
  //   width: 140,
  //   ellipsis: true,
  //   tooltip: true,
  //   render: ({ record }) => {
  //     return record.orderId || '-';
  //   }
  // },
  {
    title: '卡号',
    dataIndex: 'cardNo',
    width: 160,
    ellipsis: true,
    tooltip: true,
    render: ({ record }) => {
      return record.cardNo || '-';
    }
  },
  {
    title: '卡密',
    dataIndex: 'cardPassword',
    width: 160,
    ellipsis: true,
    tooltip: true,
    render: ({ record }) => {
      return record.cardPassword || '-';
    }
  },
  {
    title: '支付链接',
    dataIndex: 'wxPayUrl',
    slotName: 'wxPayUrl',
    width: 140
  },
  {
    title: '支付完成时间',
    dataIndex: 'paidAt',
    width: 160
  },
  {
    title: '订单过期时间',
    dataIndex: 'orderExpireAt',
    width: 160
  },
  {
    title: '卡密提取时间',
    dataIndex: 'cardExtractedAt',
    width: 160
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 160
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    width: 160
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    width: 120,
    fixed: 'right'
  }
];

// 类型定义
interface FormModel {
  keyword: string;
  status: number | undefined;
  dateRange: (Date | undefined)[] | undefined;
}

interface QueryParams {
  current?: number;
  pageSize?: number;
  keyword?: string;
  status?: number;
  startTime?: string;
  endTime?: string;
}

// 数据状态
const renderData = ref<KamiApiJdCookieV1JdOrderInfo[]>([]);
const formModel = reactive<FormModel>({
  keyword: '',
  status: undefined,
  dateRange: undefined
});

// 弹窗状态
const detailVisible = ref(false);
const currentOrder = ref<KamiApiJdCookieV1JdOrderInfo | null>(null);
const historyVisible = ref(false);
const currentOrderId = ref<string>('');

// 获取订单列表
const fetchData = async (params: QueryParams = {}) => {
  setLoading(true);
  try {
    const response = await jdOrderClient.apiJdCookieOrderJdListGet({
      page: params.current || pagination.current,
      size: params.pageSize || pagination.pageSize,
      orderId: params.keyword,
      status: params.status,
      startTime: params.startTime,
      endTime: params.endTime
    });

    renderData.value = response.data.list || [];
    pagination.total = response.data.total || 0;
  } catch (error) {
    Message.error('获取订单列表失败');
  } finally {
    setLoading(false);
  }
};

// 搜索
const search = (): void => {
  const params: QueryParams = {
    current: 1,
    keyword: formModel.keyword,
    status: formModel.status
  };

  if (formModel.dateRange && formModel.dateRange.length === 2) {
    params.startTime = formModel.dateRange[0]?.toISOString().split('T')[0];
    params.endTime = formModel.dateRange[1]?.toISOString().split('T')[0];
  }

  fetchData(params);
};

// 重置
const reset = (): void => {
  formModel.keyword = '';
  formModel.status = undefined;
  formModel.dateRange = undefined;
  search();
};

// 分页变化
const onPageChange = (current: number): void => {
  pagination.current = current;
  const params: QueryParams = {
    keyword: formModel.keyword,
    status: formModel.status
  };

  if (formModel.dateRange && formModel.dateRange.length === 2) {
    params.startTime = formModel.dateRange[0]?.toISOString().split('T')[0];
    params.endTime = formModel.dateRange[1]?.toISOString().split('T')[0];
  }

  fetchData(params);
};

const onPageSizeChange = (pageSize: number): void => {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  const params: QueryParams = {
    keyword: formModel.keyword,
    status: formModel.status
  };

  if (formModel.dateRange && formModel.dateRange.length === 2) {
    params.startTime = formModel.dateRange[0]?.toISOString().split('T')[0];
    params.endTime = formModel.dateRange[1]?.toISOString().split('T')[0];
  }

  fetchData(params);
};

// 获取状态颜色
const getStatusColor = (status: number): string => {
  const colors: Record<number, string> = {
    1: 'orange', // 待支付
    2: 'green', // 已支付
    3: 'blue', // 已发货
    4: 'red', // 已过期
    5: 'gray', // 已取消
    6: 'purple' // Cookie账号Ck失败
  };
  return colors[status] || 'gray';
};

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    1: '待支付',
    2: '已支付',
    3: '已发货',
    4: '已过期',
    5: '已取消',
    6: 'Ck失败'
  };
  return statusMap[status] || '未知';
};

// 显示详情
const showDetail = (record: KamiApiJdCookieV1JdOrderInfo): void => {
  currentOrder.value = record;
  detailVisible.value = true;
};

// 显示变更记录
const showHistory = (record: KamiApiJdCookieV1JdOrderInfo): void => {
  currentOrderId.value = record.jdOrderId;
  historyVisible.value = true;
};

// 下载功能
const handleExport = async () => {
  try {
    setLoading(true);

    // 构建导出参数，复用查询参数
    const exportParams: any = {};

    // 处理状态筛选
    if (formModel.status) {
      exportParams.status = formModel.status;
    }

    // 处理时间筛选
    if (formModel.dateRange && formModel.dateRange.length === 2) {
      const startDate = formModel.dateRange[0];
      const endDate = formModel.dateRange[1];
      if (startDate && endDate) {
        exportParams.startTime =
          startDate.toISOString().split('T')[0] + ' 00:00:00';
        exportParams.endTime =
          endDate.toISOString().split('T')[0] + ' 23:59:59';
      }
    }

    // 处理订单ID筛选
    if (formModel.keyword) {
      exportParams.orderId = formModel.keyword;
    }

    // 调用导出API
    const response =
      await jdOrderClient.apiJdCookieOrderExportGet(exportParams);

    // 创建下载链接
    const responseData = response.data as any;
    const blob =
      responseData instanceof Blob
        ? responseData
        : new Blob([responseData], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute(
      'download',
      `jd-orders-${new Date().toISOString().slice(0, 19).replace(/[:.]/g, '-')}.xlsx`
    );
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    Message.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    Message.error('导出失败');
  } finally {
    setLoading(false);
  }
};

onMounted(() => {
  search();
});
</script>

<style scoped>
.order-detail {
  padding: 16px 0;
}
</style>
