import { requestClient } from '#/api/request';

const prefix = 'order/';
/**
 * 分页查询用户列表
 * @param data
 */
export async function getOrderList(data: any) {
  return requestClient.get<any>(`${prefix}list`, { params: data });
}
/**
 * 订单状态下拉
 * @param data
 */
export async function getOrderStatusOption(data: any) {
  return requestClient.get<any>(`${prefix}status-option`, { params: data });
}

/**
 * 订单/处方类型筛选项（与后端 ProductTypeEnum 开方类型对齐）
 */
export async function getOrderPrescriptionTypeOption(data?: any) {
  return requestClient.get<Array<{ id: number; name: string }>>(
    `${prefix}prescription-type-option`,
    { params: data },
  );
}
/**
 * 统计金额
 * @param data
 */
export async function saleAmountApi(data: any) {
  return requestClient.get<any>(`${prefix}sale-amount`, { params: data });
}

/**
 * 获取订单详情
 * @param id
 */
export async function getOrderInfo(id: number) {
  return requestClient.get<any>(`${prefix}detail`, { params: { id } });
}

/**
 * 新增订单
 * @param data
 */
export async function createOrder(data: Record<string, any>) {
  return requestClient.post<any>(`${prefix}create`, data);
}

/**
 * 退款
 * @param data
 */
export async function refundApi(data: Record<string, any>) {
  return requestClient.post<any>(`${prefix}refund`, data);
}

/**
 * 编辑订单
 * @param data
 */
export async function updateOrder(data: Record<string, any>) {
  return requestClient.post<any>(`${prefix}update`, data);
}

/**
 * 删除订单
 * @param data
 */
export async function deleteOrder(data: Record<string, any>) {
  return requestClient.post<any>(`${prefix}delete`, data);
}

/**
 * 订单发货
 * @param data
 */
export async function sendOrder(data: Record<string, any>) {
  return requestClient.post<any>(`${prefix}ware-send`, data);
}

/**
 * 订单物流追踪
 * @param data
 */
export async function expressDetailByOrderId(data: Record<string, any>) {
  return requestClient.post<any>(`express-detail/detail-by-order`, data);
}

/**
 * 修改已发货运单：快递单号 / 查件手机号 / 快递公司
 */
export async function updateExpressNosApi(data: {
  express_no_id: number;
  express_no?: string;
  mobile?: string;
  express_company_code?: string;
}) {
  return requestClient.post<any>(`express-detail/update-express-nos`, data);
}

/**
 * 超管：将历史订单级运单同步到分包裹 shipment
 */
export async function syncLegacyShipmentApi(orderId: number) {
  return requestClient.post<any>(`${prefix}sync-legacy-shipment`, {
    order_id: orderId,
  });
}

/**
 * 订单页改仓：将 from 仓名下未出库明细切到 to 仓（0=萧康医药本仓库）
 */
export async function changeDeliveryWarehouseApi(data: {
  order_id: number;
  from_warehouse_id?: number;
  to_warehouse_id?: number;
  items?: Array<{ order_item_id: number; to_warehouse_id: number }>;
}) {
  return requestClient.post<any>(`${prefix}change-delivery-warehouse`, data);
}

/**
 * 导出订单数据（后端 Excel，旧接口保留）
 */
export async function exportOrderApi() {
  return requestClient.download(`${prefix}export`);
}

export interface OrderExportDataParams {
  search_time: [string, string];
  granularity: 'order' | 'item';
  order_no?: string;
  store_id?: number;
  status?: number;
  delivery_method?: number;
  prescription_type?: number;
  drug_keyword?: string;
  /** 就诊人姓名/手机号模糊（后端 whereHas userPatient） */
  patient_keyword?: string;
  /** 医生姓名/手机号模糊（后端 whereHas doctorInfo） */
  doctor_keyword?: string;
}

export interface OrderExportDataResult {
  total: number;
  rows: Record<string, unknown>[];
  granularity: 'order' | 'item';
}

/**
 * 导出订单 JSON 数据（供前端 ExcelJS）
 */
export async function getOrderExportDataApi(params: OrderExportDataParams) {
  return requestClient.get<OrderExportDataResult>(`${prefix}export-data`, { params });
}

export interface OrderExportSchemePayload {
  name: string;
  is_default?: boolean | number;
  granularity: 'order' | 'item';
  config: {
    order_no?: string;
    store_id?: number | null;
    status?: number | null;
    delivery_method?: number | null;
    prescription_type?: number | null;
    selected_fields: string[];
  };
}

export interface OrderExportSchemeUpdatePayload {
  id: number;
  name?: string;
  is_default?: boolean | number;
  granularity?: 'order' | 'item';
  config?: OrderExportSchemePayload['config'];
}

export interface OrderExportSchemeItem {
  id: number;
  name: string;
  is_default: number;
  granularity: 'order' | 'item';
  config: OrderExportSchemePayload['config'];
  created_at?: string;
  updated_at?: string;
}

export async function getOrderExportSchemeList() {
  return requestClient.get<OrderExportSchemeItem[]>(`${prefix}export-scheme-list`);
}

export async function createOrderExportScheme(data: OrderExportSchemePayload) {
  return requestClient.post<OrderExportSchemeItem>(`${prefix}export-scheme-create`, data);
}

export async function updateOrderExportScheme(data: OrderExportSchemeUpdatePayload) {
  return requestClient.post<OrderExportSchemeItem>(`${prefix}export-scheme-update`, data);
}

export async function deleteOrderExportScheme(data: { id: number }) {
  return requestClient.post<boolean>(`${prefix}export-scheme-delete`, data);
}

/**
 * 取消待支付订单
 */
export async function cancelOrderApi(data: { order_id: number; remark?: string }) {
  return requestClient.post<any>(`${prefix}cancel`, data);
}

/**
 * 更新包邮状态
 * @param data
 */
export async function updateFreeShipping(data: { id: number; is_free_shipping: number }) {
  return requestClient.post<any>(`${prefix}update-free-shipping`, data);
}

/**
 * 近 N 分钟订单：表内金额与按 OrderItems 重算是否一致（调价/分账同口径）
 */
export async function getVerifyRecentOrderAmounts(params?: {
  minutes?: number;
  mismatch_only?: number;
}) {
  return requestClient.get<{
    count: number;
    minutes: number;
    orders: Array<{
      expected_items_price: number;
      expected_total_pay_price: number;
      items_diff: number;
      items_match: boolean;
      items_price: number;
      ok: boolean;
      order_id: number;
      order_no: string;
      total_diff: number;
      total_match: boolean;
      total_pay_price: number;
    }>;
    since: number;
  }>(`${prefix}verify-recent-order-amounts`, { params });
}
