<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="0">初始化</a-option>
                    <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">cookie失效</a-option>
                    <a-option :value="6">下单京东订单失败</a-option>
                    <a-option :value="7">库存问题</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-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: 1000 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #status="{ record }">
          <a-tag v-if="record.status === 0" color="blue">初始化</a-tag>
          <a-tag v-else-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="red">已过期</a-tag>
          <a-tag v-else-if="record.status === 4" color="gray">已取消</a-tag>
          <a-tag v-else-if="record.status === 5" color="orange">
            cookie失效
          </a-tag>
          <a-tag v-else-if="record.status === 6" color="red">
            下单京东订单失败
          </a-tag>
          <a-tag v-else-if="record.status === 7" color="red">库存问题</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 #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>

    <!-- 订单详情弹窗 -->
    <order-detail v-model:visible="detailVisible" :order-data="currentOrder" />

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

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } 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, jdHistoryClient } from '@/api';
import type {
  KamiApiJdCookieV1ListOrderRes,
  KamiApiJdCookieV1OrderInfo
} from '@/api/generated';
import { getCategoryChineseName } from '@/utils/categoryMapping';
import OrderDetail from './components/order-detail.vue';
import OrderHistoryDrawer from './components/order-history-drawer.vue';

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: 'userOrderId',
    width: 180,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '订单号',
    dataIndex: 'orderId',
    width: 180,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '京东订单号',
    dataIndex: 'jdOrderId',
    width: 180,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '商品品类',
    dataIndex: 'category',
    width: 120,
    render: ({ record }) => {
      return getCategoryChineseName(record.category);
    }
  },
  {
    title: '订单金额',
    dataIndex: 'amount',
    slotName: 'amount',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100
  },
  {
    title: '最后请求时间',
    dataIndex: 'lastRequestAt',
    width: 180
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    width: 160,
    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<KamiApiJdCookieV1OrderInfo[]>([]);
const formModel = reactive<FormModel>({
  keyword: '',
  status: undefined,
  dateRange: undefined
});

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

// 获取订单列表
const fetchData = async (params: QueryParams = {}) => {
  setLoading(true);
  try {
    const response = await jdOrderClient.apiJdCookieOrderListGet({
      page: params.current || pagination.current,
      size: params.pageSize || pagination.pageSize,
      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 showDetail = (record: KamiApiJdCookieV1OrderInfo): void => {
  currentOrder.value = record;
  detailVisible.value = true;
};

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

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