import request from '@/utils/request';
import { AxiosPromise } from 'axios';
import { StatementOrderVO, StatementOrderForm, StatementOrderQuery } from '@/api/bill/statementOrder/types';

/**
 * 查询对账单主列表
 * @param query
 * @returns {*}
 */

export const listStatementOrder = (query?: StatementOrderQuery): AxiosPromise<StatementOrderVO[]> => {
  return request({
    url: '/bill/statementOrder/list',
    method: 'get',
    params: query
  });
};

/**
 * 查询对账单主详细
 * @param id
 */
export const getStatementOrder = (id: string | number): AxiosPromise<StatementOrderVO> => {
  return request({
    url: '/bill/statementOrder/' + id,
    method: 'get'
  });
};

/**
 * 新增对账单主
 * @param data
 */
export const addStatementOrder = (data: StatementOrderForm) => {
  return request({
    url: '/bill/statementOrder',
    method: 'post',
    data: data
  });
};

/**
 * 修改对账单主
 * @param data
 */
export const updateStatementOrder = (data: StatementOrderForm) => {
  return request({
    url: '/bill/statementOrder',
    method: 'put',
    data: data
  });
};

/**
 * 删除对账单主
 * @param id
 */
export const delStatementOrder = (id: string | number | Array<string | number>) => {
  return request({
    url: '/bill/statementOrder/' + id,
    method: 'delete'
  });
};

export function changeStatus(id: string | number, statementStatus: string) {
  const data = {
    id,
    statementStatus
  };
  return request({
    url: '/bill/statementOrder/changeStatus',
    method: 'put',
    data: data
  });
}

/**
 * 根据客户ID查询对账单明细（分页）
 * @param customerId 客户ID
 * @param pageQuery 分页参数
 */
export const getCustomerOrderDetails = (customerId: string | number, pageQuery?: { pageNum?: number; pageSize?: number }) => {
  return request({
    url: '/bill/statementOrder/getCustomerOrderDetails/' + customerId,
    method: 'get',
    params: pageQuery
  });
};

/**
 * 根据多个 (对账单ID + 订单ID) 查询对应的订单商品列表
 * @param items - 包含 statementOrderId 和 orderId 的数组
 */
export function getStatementProductList(items: { statementOrderId: number | string; orderId: number | string }[]) {
  if (!Array.isArray(items) || items.length === 0) {
    return Promise.reject(new Error('至少选择一个订单'));
  }

  // 可选：校验每项是否完整
  const invalidItem = items.find((item) => item.statementOrderId == null || item.orderId == null);
  if (invalidItem) {
    return Promise.reject(new Error('每项必须包含 statementOrderId 和 orderId'));
  }

  return request({
    url: '/bill/statementOrder/getStatementProductList',
    method: 'post',
    data: items // 发送 JSON 数组
  });
}
