import Taro from '@tarojs/taro'

const PREVIEW_TITLE = '品牌画册'
const BROCHURE_API_BASE = 'https://cms-api.websoft.top/api'

interface BrochureGoods {
  goodsId?: number
  name?: string
  goodsName?: string
  files?: string
}

export interface BrochurePayload {
  title: string
  images: string[]
}

const parseFiles = (files?: string): string[] => {
  if (!files) {
    return []
  }

  try {
    const parsed = JSON.parse(files)

    if (Array.isArray(parsed)) {
      return parsed.reduce<string[]>((result, item: any) => {
        if (typeof item === 'string') {
          result.push(item)
          return result
        }

        if (item && typeof item.url === 'string') {
          result.push(item.url)
        }

        return result
      }, [])
    }

    if (typeof parsed === 'string') {
      return [parsed]
    }

    if (parsed && typeof parsed.url === 'string') {
      return [parsed.url]
    }
  } catch (error) {
    if (/^https?:\/\//.test(files) || files.startsWith('/')) {
      return [files]
    }

    console.error('解析画册图片失败:', error)
    return []
  }

  return []
}

export const getBrochurePayload = async (): Promise<BrochurePayload> => {
  const response = await Taro.request<BrochureGoods[]>({
    url: `${BROCHURE_API_BASE}/shop/shop-goods`,
    method: 'GET',
    header: {
      'Content-Type': 'application/json',
      Tenantid: '10582'
    }
  })

  const responseData: any = response.data
  const goodsList: BrochureGoods[] = Array.isArray(responseData)
    ? responseData
    : (Array.isArray(responseData?.data) ? responseData.data : [])

  if (!goodsList.length) {
    throw new Error('画册加载失败，请稍后重试')
  }

  const title = goodsList[0]?.goodsName || goodsList[0]?.name || PREVIEW_TITLE
  const images: string[] = []

  goodsList.forEach((item) => {
    const parsedImages = parseFiles(item.files)
    if (parsedImages.length) {
      images.push(...parsedImages)
    }
  })

  if (!images.length) {
    throw new Error('当前商品未配置画册图片')
  }

  return {
    title,
    images
  }
}
