import type { PageParam, PageResult } from '@vben/request';

import type { SystemStorageApi } from '#/api/system/storage';

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

export namespace FinVoucherApi {
  /** 凭证分录 */
  export interface VoucherEntry {
    id?: number; // 分录编号
    rowNo?: number; // 行号
    subjectCode?: string; // 科目编码
    subjectName?: string; // 科目名称
    summary?: string; // 摘要
    debit?: number; // 借方金额
    credit?: number; // 贷方金额
    auxiliaryType?: number; // 辅助核算类型
    auxiliaryId?: string; // 辅助核算对象编号
    auxiliaryName?: string; // 辅助核算对象名称
  }

  /** 记账凭证 */
  export interface Voucher {
    id?: number; // 凭证编号
    voucherNo?: string; // 凭证字号，留空时后端自动生成
    voucherDate: string; // 凭证日期
    summary?: string; // 摘要
    debit?: number; // 借方合计
    credit?: number; // 贷方合计
    status?: number; // 凭证状态：0未过账 10已过账 20已作废
    creator?: string; // 制单人（用户编号，仅用于搜索条件）
    creatorName?: string; // 制单人昵称（列表、导出展示用）
    attachmentCount?: number; // 附件张数
    remark?: string; // 备注
    createTime?: Date; // 创建时间
    entries?: VoucherEntry[]; // 凭证分录
    attachmentList?: SystemStorageApi.StorageBlob[]; // 附件列表
    hasAttachment?: boolean; // 是否有附件
    blobIds?: number[]; // 附件 blobId 列表（提交用）
  }
}

/** 查询记账凭证分页 */
export function getVoucherPage(params: PageParam) {
  return requestClient.get<PageResult<FinVoucherApi.Voucher>>(
    '/finance/voucher/page',
    { params },
  );
}

/** 查询记账凭证分页（含分录，用于凭证列表展开与打印） */
export function getVoucherPageWithEntry(params: PageParam) {
  return requestClient.get<PageResult<FinVoucherApi.Voucher>>(
    '/finance/voucher/page-with-entry',
    { params },
  );
}

/** 查询记账凭证详情（含分录与附件） */
export function getVoucher(id: number) {
  return requestClient.get<FinVoucherApi.Voucher>(
    `/finance/voucher/get?id=${id}`,
  );
}

/** 新增记账凭证 */
export function createVoucher(data: FinVoucherApi.Voucher) {
  return requestClient.post('/finance/voucher/create', data);
}

/** 修改记账凭证 */
export function updateVoucher(data: FinVoucherApi.Voucher) {
  return requestClient.put('/finance/voucher/update', data);
}

/** 删除记账凭证 */
export function deleteVoucher(id: number) {
  return requestClient.delete(`/finance/voucher/delete?id=${id}`);
}

/** 批量删除记账凭证 */
export function deleteVoucherList(ids: number[]) {
  return requestClient.delete(
    `/finance/voucher/delete-list?ids=${ids.join(',')}`,
  );
}

/** 凭证过账 */
export function postVoucher(id: number) {
  return requestClient.put('/finance/voucher/post', null, { params: { id } });
}

/** 凭证作废 */
export function cancelVoucher(id: number) {
  return requestClient.put('/finance/voucher/cancel', null, { params: { id } });
}

/** 导出记账凭证 Excel */
export function exportVoucher(params: any) {
  return requestClient.download('/finance/voucher/export-excel', { params });
}
