import type { AxiosResponse } from 'axios'
import type { PageInfo, Result } from '@cacp/ui'
import request from '@/utils/request'
import download from 'js-file-download'

import type {CustomMStatF,CustomMStatFQuery}  from '@/types/statReport/CustomMStatF'
import dayjs from 'dayjs'

const contextPath = '/statReport/CustomMStatF'

// 查询按业务现场关区分类列表
export async function getList(query: CustomMStatFQuery): Promise<Result<PageInfo<CustomMStatF>>> {
  const res: AxiosResponse<Result<PageInfo<CustomMStatF>>> = await request.post(`${contextPath}/get-list`, query)
  return res.data
}

// 获取采购入库单详情
export async function getDetail(ID: string): Promise<Result<CustomMStatF>> {
  const res: AxiosResponse<Result<CustomMStatF>> = await request.get(`${contextPath}/get-detail?ID=${ID}`)
  return res.data
}

// 新增采购入库单
export async function insert(row: CustomMStatF): Promise<Result<number>> {
  const res: AxiosResponse<Result<number>> = await request.post(`${contextPath}/insert-customMStatF`, row)
  return res.data
}

// 更新采购入库单
export async function update(row: CustomMStatF): Promise<Result<number>> {
  const res: AxiosResponse<Result<number>> = await request.post(`${contextPath}/update-customMStatF`, row)
  return res.data
}

// 删除采购入库单
export async function remove(customMStatFs: string | string[]): Promise<Result<number>> {
  // 统一转换为数组格式
  const ids = Array.isArray(customMStatFs) ? customMStatFs : [customMStatFs];
  const res: AxiosResponse<Result<number>> = await request.post(
          `${contextPath}/delete-customMStatF?ids`,ids
  )
  return res.data
}

// 导出
export async function dataExport(query: CustomMStatFQuery): Promise<void> {
  try {
    const res = await request.post(`${contextPath}/get-customMStatF-export`,query, {
      responseType: 'arraybuffer'
    })
    if (res.status === 200) {
      // 使用js-file-download下载
      download(res.data, '按业务现场关区分类数据_'+query.beginDate+'.xlsx', 'application/octet-stream')
    }
  } catch (error) {
    console.error('导出失败:', error)
    throw error
  }
}
