import http from '@/utils/http'

const BASE_URL = '/project/budget'

/** 预算记录响应类型 */
export interface BudgetRecordResp {
  id: string
  projectId: string
  projectName: string
  projectCode: string
  projectAmount: number
  projectManager: string
  establishDate: string
  deliveryDate: string
  client: string
  remark: string
  applyBudgetAmount: number
  applicant: string
  applyTime: string
  auditStatus: string // 'pending' | 'approved' | 'rejected'
  auditStatusLabel: string
  auditRemark: string
  auditor: string
  auditTime: string
  budgetProgress: number
  usedBudgetAmount: number
  remainingBudgetAmount: number
}

/** 预算项类型 */
export interface BudgetItemResp {
  id?: string
  budgetName: string
  budgetType: string
  budgetAmount: number
  budgetDescription: string
  attachments?: Array<{
    id: string
    name: string
    url: string
  }>
}

/** 预算申请请求类型 */
export interface BudgetApplyReq {
  projectId: string
  budgetItems: BudgetItemResp[]
  totalAmount: number
  applyReason?: string
}

/** 预算审核请求类型 */
export interface BudgetAuditReq {
  auditStatus: 'approved' | 'rejected'
  auditRemark: string
}

/** 预算查询参数 */
export interface BudgetQuery {
  projectName?: string
  projectCode?: string
  auditStatus?: string
  applicant?: string
  applyTimeStart?: string
  applyTimeEnd?: string
}

export interface BudgetPageQuery extends BudgetQuery, PageQuery {}

/** @desc 查询预算记录列表 */
export function listBudgetRecord(query: BudgetPageQuery) {
  return http.get<PageRes<BudgetRecordResp[]>>(`${BASE_URL}/record`, query)
}

/** @desc 获取预算记录详情 */
export function getBudgetRecord(id: string) {
  return http.get<BudgetRecordResp>(`${BASE_URL}/record/${id}`)
}

/** @desc 申请预算 */
export function applyBudget(data: BudgetApplyReq) {
  return http.post<boolean>(`${BASE_URL}/apply`, data)
}

/** @desc 审核预算 */
export function auditBudget(id: string, data: BudgetAuditReq) {
  return http.put<boolean>(`${BASE_URL}/audit/${id}`, data)
}

/** @desc 获取预算类型选项 */
export function getBudgetTypes() {
  return http.get<Array<{ label: string; value: string }>>(`${BASE_URL}/types`)
}

/** @desc 上传预算附件 */
export function uploadBudgetAttachment(file: File) {
  const formData = new FormData()
  formData.append('file', file)
  return http.post<{ id: string; name: string; url: string }>(`${BASE_URL}/upload`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/** @desc 删除预算附件 */
export function deleteBudgetAttachment(id: string) {
  return http.del(`${BASE_URL}/attachment/${id}`)
}

/** @desc 导出预算记录 */
export function exportBudgetRecord(query: BudgetQuery) {
  return http.get(`${BASE_URL}/export`, query, {
    responseType: 'blob'
  })
} 