import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { CmsContactLead, CmsContactLeadParam, ContactLeadSubmitForm } from './model';
import { MODULES_API_URL } from '@/config/setting';

// 公开 CMS 接口路径（无需登录，走 /api/cms/* 代理）
const CMS_PUBLIC_URL = '/api/cms';

/**
 * 提交联系表单（公开接口，无需登录）
 */
export async function submitContactLead(data: ContactLeadSubmitForm) {
  const res = await request.post<ApiResult<unknown>>(
    CMS_PUBLIC_URL + '/cms-contact-lead/submit',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 分页查询销售线索（后台管理）
 */
export async function pageCmsContactLead(params: CmsContactLeadParam) {
  const res = await request.get<ApiResult<PageResult<CmsContactLead>>>(
    MODULES_API_URL + '/cms/cms-contact-lead/page',
    { params }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询销售线索列表（后台管理）
 */
export async function listCmsContactLead(params?: CmsContactLeadParam) {
  const res = await request.get<ApiResult<CmsContactLead[]>>(
    MODULES_API_URL + '/cms/cms-contact-lead',
    { params }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询销售线索
 */
export async function getCmsContactLead(id: number) {
  const res = await request.get<ApiResult<CmsContactLead>>(
    MODULES_API_URL + '/cms/cms-contact-lead/' + id
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改销售线索（跟进状态等）
 */
export async function updateCmsContactLead(data: CmsContactLead) {
  const res = await request.put<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-contact-lead',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除销售线索
 */
export async function removeCmsContactLead(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-contact-lead/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除销售线索
 */
export async function removeBatchCmsContactLead(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-contact-lead/batch',
    { data }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
