<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="orderNo" label="订单号">
                  <a-input
                    v-model="formModel.orderNo"
                    placeholder="请输入订单号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="merchantOrderId" label="商户订单号">
                  <a-input
                    v-model="formModel.merchantOrderId"
                    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-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="payStatus" label="支付状态">
                  <a-select
                    v-model="formModel.payStatus"
                    placeholder="请选择支付状态"
                    allow-clear
                  >
                    <a-option :value="0">未支付</a-option>
                    <a-option :value="1">已支付</a-option>
                    <a-option :value="2">支付失败</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"
                    style="width: 100%"
                    :shortcut="dateShortcuts"
                  />
                </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-row style="margin-bottom: 16px">
        <a-space>
          <a-button @click="download">
            <template #icon>
              <icon-download />
            </template>
            导出
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据表格区域 -->
      <a-table
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          pageSizeOptions: [10, 20, 50, 100],
          showPageSize: true,
          showTotal: true
        }"
        :columns="columns"
        :data="renderData"
        :scroll="{ x: 1400 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 订单状态模板 -->
        <template #status="{ record }">
          <a-tag :color="statusMapper(record.status).color">
            {{ statusMapper(record.status).text }}
          </a-tag>
        </template>

        <!-- 支付状态模板 -->
        <template #payStatus="{ record }">
          <a-tag :color="payStatusMapper(record.payStatus).color">
            {{ payStatusMapper(record.payStatus).text }}
          </a-tag>
        </template>

        <!-- 回调状态模板 -->
        <template #callbackStatus="{ record }">
          <a-tag :color="callbackStatusMapper(record.notifyStatus).color">
            {{ callbackStatusMapper(record.notifyStatus).text }}
          </a-tag>
        </template>

        <!-- 订单金额模板 -->
        <template #amount="{ record }">
          <span class="amount-text">¥{{ record.amount }}</span>
        </template>

        <!-- 操作列模板 -->
        <template #operations="{ record }">
          <a-space size="small">
            <a-tooltip content="订单详情">
              <a-button size="small" @click="showOrderDetail(record)">
                <template #icon>
                  <icon-eye />
                </template>
              </a-button>
            </a-tooltip>
            <a-tooltip content="订单历史">
              <a-button size="small" @click="showOrderHistory(record)">
                <template #icon>
                  <icon-history />
                </template>
              </a-button>
            </a-tooltip>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 订单详情弹窗 -->
    <order-detail-modal
      v-model:visible="state.detailModalVisible"
      :order="selectedOrder"
    />

    <!-- 订单历史弹窗 -->
    <order-history-modal
      v-model:visible="state.historyModalVisible"
      :order-no="selectedOrderNo"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { Message, Notification, TableColumnData } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { jdV2OrderClient } from '@/api/index.ts';
import type { KamiApiCamelOilV1OrderListItem } from '@/api/generated/models/index.ts';
import type {
  ApiJdV2OrderListGetPageSizeEnum,
  ApiJdV2OrderListGetStatusEnum,
  ApiJdV2OrderListGetPayStatusEnum
} from '@/api/generated/apis/jdv2-order-api';
import type {
  KamiApiCamelOilV1OrderListItemStatusEnum,
  KamiApiCamelOilV1OrderListItemPayStatusEnum,
  KamiApiCamelOilV1OrderListItemNotifyStatusEnum
} from '@/api/generated/models/index.ts';
import OrderDetailModal from './components/order-detail-modal.vue';
import OrderHistoryModal from './components/order-history-modal.vue';

// 基础分页配置
const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};

// 状态管理
const pagination = reactive({ ...basePagination });
const { loading, setLoading } = useLoading(true);
const renderData = ref<KamiApiCamelOilV1OrderListItem[]>([]);
const selectedOrder = ref<any>(null);
const selectedOrderNo = ref('');

// 时间快捷选项
const dateShortcuts = [
  {
    label: '今天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      return [start, end];
    }
  },
  {
    label: '昨天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24);
      end.setTime(end.getTime() - 3600 * 1000 * 24);
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    label: '最近7天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    label: '最近30天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  }
];

// 表格列配置
const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    fixed: 'left'
  },
  {
    title: '订单号',
    dataIndex: 'orderNo',
    width: 180,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '商户订单号',
    dataIndex: 'merchantOrderNo',
    width: 180,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '账号名称',
    dataIndex: 'accountName',
    width: 150
  },
  {
    title: '订单金额',
    dataIndex: 'amount',
    slotName: 'amount',
    width: 120
  },
  {
    title: '订单状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100
  },
  {
    title: '支付状态',
    dataIndex: 'payStatus',
    slotName: 'payStatus',
    width: 100
  },
  {
    title: '回调状态',
    dataIndex: 'notifyStatus',
    slotName: 'callbackStatus',
    width: 100
  },
  {
    title: '支付完成时间',
    dataIndex: 'paidAt',
    width: 180,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '失败原因',
    dataIndex: 'failureReason',
    width: 150,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    fixed: 'right',
    width: 120
  }
];

// 表单模型
const generateFormModel = () => ({
  orderNo: '',
  merchantOrderId: '',
  status: undefined as ApiJdV2OrderListGetStatusEnum | undefined,
  payStatus: undefined as ApiJdV2OrderListGetPayStatusEnum | undefined,
  dateRange: [] as Date[]
});

const formModel = ref(generateFormModel());

// 弹窗状态管理
const state = reactive({
  detailModalVisible: false,
  historyModalVisible: false
});

/**
 * 获取订单列表数据
 * @param params 查询参数
 */
const fetchOrderData = async (
  params: {
    current: number;
    pageSize: ApiJdV2OrderListGetPageSizeEnum;
    orderNo?: string;
    merchantOrderNo?: string;
    accountPhone?: string;
    status?: ApiJdV2OrderListGetStatusEnum;
    payStatus?: ApiJdV2OrderListGetPayStatusEnum;
    dateRange?: Date[];
  } = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const { data } = await jdV2OrderClient.apiJdV2OrderListGet({
      current: params.current,
      pageSize: params.pageSize as ApiJdV2OrderListGetPageSizeEnum,
      orderNo: params.orderNo,
      merchantOrderId: params.merchantOrderNo,
      status: params.status,
      payStatus: params.payStatus,
      dateRange: params.dateRange as unknown as string[]
    });

    renderData.value = data.list || [];
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = data.total || 0;
  } catch (error) {
    console.error('获取订单列表失败:', error);
    Notification.error({
      content: '获取订单列表失败',
      closable: true
    });
  } finally {
    setLoading(false);
  }
};

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

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

/**
 * 搜索功能
 */
const search = () => {
  fetchOrderData({
    ...basePagination,
    ...formModel.value
  });
};

/**
 * 重置表单
 */
const reset = () => {
  formModel.value = generateFormModel();
  search();
};

/**
 * 显示订单详情
 * @param record 订单记录
 */
const showOrderDetail = (record: KamiApiCamelOilV1OrderListItem) => {
  selectedOrder.value = record;
  state.detailModalVisible = true;
};

/**
 * 显示订单历史
 * @param record 订单记录
 */
const showOrderHistory = (record: KamiApiCamelOilV1OrderListItem) => {
  selectedOrderNo.value = record.orderNo;
  state.historyModalVisible = true;
};

/**
 * 订单状态映射器
 * 基于后端Go定义的CamelOilOrderStatus
 * @param status 状态值
 * @returns 状态文本和颜色
 */
const statusMapper = (status: number): { text: string; color: string } => {
  switch (status) {
    case 0:
      return { text: '待处理', color: 'orange' }; // CamelOilOrderStatusPending
    case 1:
      return { text: '处理中', color: 'blue' }; // CamelOilOrderStatusProcessing
    case 2:
      return { text: '已完成', color: 'green' }; // CamelOilOrderStatusCompleted
    case 3:
      return { text: '已失败', color: 'red' }; // CamelOilOrderStatusFailed
    default:
      return { text: '未知状态', color: 'gray' };
  }
};

/**
 * 支付状态映射器
 * 基于后端Go定义的CamelOilPayStatus
 * @param status 支付状态
 * @returns 支付状态文本和颜色
 */
const payStatusMapper = (status: number): { text: string; color: string } => {
  switch (status) {
    case 0:
      return { text: '未支付', color: 'orange' }; // CamelOilPaymentStatusUnpaid
    case 1:
      return { text: '已支付', color: 'green' }; // CamelOilPaymentStatusPaid
    case 2:
      return { text: '已退款', color: 'blue' }; // CamelOilPaymentStatusRefunded
    case 3:
      return { text: '已超时', color: 'red' }; // CamelOilPaymentStatusTimeout
    default:
      return { text: '未知状态', color: 'gray' };
  }
};

/**
 * 回调状态映射器
 * 基于后端Go定义的CamelOilNotifyStatus
 * @param status 回调状态
 * @returns 回调状态文本和颜色
 */
const callbackStatusMapper = (
  status: number
): { text: string; color: string } => {
  switch (status) {
    case 0:
      return { text: '未回调', color: 'orange' }; // CamelOilCallbackStatusPending
    case 1:
      return { text: '回调成功', color: 'green' }; // CamelOilCallbackStatusSuccess
    case 2:
      return { text: '回调失败', color: 'red' }; // CamelOilCallbackStatusFailed
    default:
      return { text: '未知状态', color: 'gray' };
  }
};

/**
 * 导出功能
 */
const download = () => {
  // TODO: 实现导出功能
  Message.info('导出功能开发中');
};

// 组件挂载时获取数据
onMounted(() => {
  fetchOrderData();
});
</script>

<style scoped>
.container {
  padding: 0 20px 20px;
}

.general-card {
  min-height: calc(100vh - 170px);
}

.amount-text {
  color: rgb(var(--primary-6));
  font-weight: 600;
}
</style>
