import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type { AppArticle, AppArticleParam, AppArticleCount } from './model'
import { APP_API_URL } from '@/config/setting'

const BASE = APP_API_URL + '/article'

function isSuccess(code?: number) {
  return code === 0 || code === 200
}

export async function pageAppArticle(params: AppArticleParam) {
  const res = await request.get<ApiResult<PageResult<AppArticle>>>(BASE + '/page', { params })
  if (isSuccess(res.data.code)) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

export async function listAppArticle(params?: AppArticleParam) {
  const res = await request.get<ApiResult<AppArticle[]>>(BASE, { params })
  if (isSuccess(res.data.code) && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

export async function addAppArticle(data: AppArticle) {
  const res = await request.post<ApiResult<unknown>>(BASE, data)
  if (isSuccess(res.data.code)) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

export async function updateAppArticle(data: AppArticle) {
  const res = await request.put<ApiResult<unknown>>(BASE, data)
  if (isSuccess(res.data.code)) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

export async function removeAppArticle(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/' + id)
  if (isSuccess(res.data.code)) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

export async function getAppArticle(id: number) {
  const res = await request.get<ApiResult<AppArticle>>(BASE + '/' + id)
  if (isSuccess(res.data.code) && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

export async function getAppArticleByCode(code: string) {
  const res = await request.get<ApiResult<AppArticle>>(BASE + '/getByCode/' + code)
  if (isSuccess(res.data.code) && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

export async function getAppArticleCount(params: AppArticleParam) {
  const res = await request.get<ApiResult<AppArticleCount>>(BASE + '/data', { params })
  if (isSuccess(res.data.code)) return res.data.data
  return Promise.reject(new Error(res.data.message))
}
