import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { CmsWebsite, CmsWebsiteParam } from './model';
import { MODULES_API_URL, SERVER_API_URL } from '@/config/setting';

/**
 * 获取网站信息
 */
export async function getSiteInfo() {
  const res = await request.get<ApiResult<CmsWebsite>>(
    MODULES_API_URL + '/cms/cms-website/getSiteInfo',
    {
      params: {}
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 分页查询网站信息记录表
 */
export async function pageCmsWebsite(params: CmsWebsiteParam) {
  const res = await request.get<ApiResult<PageResult<CmsWebsite>>>(
    MODULES_API_URL + '/cms/cms-website/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询网站信息记录表列表
 */
export async function listCmsWebsite(params?: CmsWebsiteParam) {
  const res = await request.get<ApiResult<CmsWebsite[]>>(
    MODULES_API_URL + '/cms/cms-website',
    {
      params
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加网站信息记录表
 */
export async function addCmsWebsite(data: CmsWebsite): Promise<CmsWebsite> {
  const res = await request.post<ApiResult<CmsWebsite>>(
    MODULES_API_URL + '/cms/cms-website',
    data
  );
  
  console.log('addCmsWebsite 响应:', res);
  
  // 处理响应数据
  const responseData = res.data;
  
  // 检查是否为 ApiResult 格式
  if (responseData && typeof responseData === 'object' && 'code' in responseData) {
    // 是 ApiResult 格式
    if (responseData.code === 0) {
      // 确保返回的数据不为空
      if (!responseData.data) {
        console.warn('addCmsWebsite: 后端返回的data字段为空', responseData);
        // 返回一个包含websiteId的默认对象
        return {
          websiteName: data.websiteName,
          websiteCode: data.websiteCode,
          websiteType: data.websiteType,
          type: data.type,
          comments: data.comments
        } as CmsWebsite;
      }
      return responseData.data;
    }
    return Promise.reject(new Error(responseData.message || '创建失败'));
  } else {
    // 直接返回 CmsWebsite 对象
    console.log('addCmsWebsite: 后端直接返回CmsWebsite对象', responseData);
    return responseData as CmsWebsite;
  }
}

/**
 * 修改网站信息记录表
 */
export async function updateCmsWebsite(data: CmsWebsite) {
  const res = await request.put<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除网站信息记录表
 */
export async function removeCmsWebsite(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除网站信息记录表
 */
export async function removeBatchCmsWebsite(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website/batch',
    {
      data
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询网站信息记录表
 */
export async function getCmsWebsite(id: number) {
  const res = await request.get<ApiResult<CmsWebsite>>(
    MODULES_API_URL + '/cms/cms-website/' + id
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 清除缓存
 */
export async function removeSiteInfoCache(key?: string) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website/clearSiteInfo/' + key
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

export async function pageCmsWebsiteAll(params: CmsWebsiteParam) {
  const res = await request.get<ApiResult<PageResult<CmsWebsite>>>(
    MODULES_API_URL + '/cms/cms-website/pageAll',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询网站
 */
export async function getCmsWebsiteAll(id: number) {
    const res = await request.get<ApiResult<CmsWebsite>>(
        '/cms/cms-website/getAll/' + id
    );
    if (res.data.code === 0 && res.data) {
        return res.data;
    }
    return Promise.reject(new Error(res.data.message));
}

/**
 * 修改网站信息记录表
 */
export async function updateCmsWebsiteAll(data: CmsWebsite) {
    const res = await request.put<ApiResult<unknown>>(
        '/cms/cms-website/updateAll',
        data
    );
    if (res.data.code === 0) {
        return res.data.message;
    }
    return Promise.reject(new Error(res.data.message));
}

// ---- 发布管理 API ----

/**
 * 提交上架申请
 */
export async function submitPublishReview(data: {
  websiteId: number
  priceType: string
  price?: number
  subscriptionPeriod?: string
  appDescription?: string
  detailDescription?: string
  screenshots?: string
}) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website/submitReview',
    data
  )
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/**
 * 下架应用
 */
export async function unpublishCmsWebsite(websiteId: number) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website/unpublish/' + websiteId
  )
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/**
 * 撤回审核申请
 */
export async function withdrawPublishReview(websiteId: number) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website/withdrawReview/' + websiteId
  )
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/**
 * 管理员审核通过
 */
export async function approvePublishReview(websiteId: number) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website/approveReview/' + websiteId
  )
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/**
 * 管理员审核拒绝
 */
export async function rejectPublishReview(data: { websiteId: number; rejectReason: string }) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/cms/cms-website/rejectReview',
    data
  )
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/**
 * 获取发布审核记录列表（管理员用）
 */
export async function pagePublishReviews(params: {
  page?: number
  limit?: number
  publishStatus?: string
  keywords?: string
}) {
  const res = await request.get<ApiResult<PageResult<CmsWebsite>>>(
    MODULES_API_URL + '/cms/cms-website/pageReviews',
    { params }
  )
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/**
 * 分页查询应用产品（CmsWebsite 表，兼容 product 字段名）
 */
export async function pageAppProductAll(params: any) {
  const res = await request.get<ApiResult<PageResult<any>>>(
    SERVER_API_URL + '/cms/cms-website/pageAll',
    { params }
  )
  if (res.data.code === 0) {
    // 字段映射：website -> product 兼容
    const data = res.data.data
    if (data?.list) {
      data.list = data.list.map((item: any) => ({
        ...item,
        productId: item.websiteId,
        productName: item.websiteName,
        productCode: item.websiteCode,
        productSecret: item.websiteSecret,
        icon: item.websiteIcon,
        logo: item.websiteLogo,
        description: item.comments,
        userId: item.userId,
      }))
    }
    return data
  }
  return Promise.reject(new Error(res.data.message))
}
