import { resolveFileUrl } from '@/utils/image'
import { formatPrice } from '@/utils/format'
import { PAGE_GOODS_DETAIL } from '@/utils/pageRoute'
import { joinCartSpecParts } from '@/utils/cartSpec'

const GOODS_PLACEHOLDER = '/static/logo.png'
const SHOP_AVATAR_PLACEHOLDER = '/static/logo.png'

/** 跳转商品详情 */
export function goGoodsDetail(goodsId) {
  if (!goodsId) return
  uni.navigateTo({
    url: `${PAGE_GOODS_DETAIL}?goodsId=${goodsId}`
  })
}

export function mapDetailPics(pics) {
  if (!Array.isArray(pics) || !pics.length) {
    return [GOODS_PLACEHOLDER]
  }
  return pics.map((p) => resolveFileUrl(p) || GOODS_PLACEHOLDER).filter(Boolean)
}

/** 详情接口 data → 页面模型 */
export function mapGoodsDetail(data) {
  if (!data) return null
  const logistics = data.logistics || {}
  const shop = data.shop || {}
  const purchase = data.purchase || {}
  return {
    goodsId: data.goodsId,
    goodsSn: data.goodsSn,
    goodsName: data.goodsName,
    goodsBrief: data.goodsBrief,
    pics: mapDetailPics(data.pics),
    salePrice: data.salePrice,
    priceText: formatPrice(data.salePrice),
    stock: Number(data.stock) || 0,
    salesCount: data.salesCount,
    goodsStatus: data.goodsStatus,
    goodsStatusLabel: data.goodsStatusLabel,
    categoryPath: data.categoryPath,
    detailContent: data.detailContent || '',
    attributes: data.attributes || [],
    specDisplay: data.specDisplay || [],
    services: (data.services || []).map(mapService),
    logistics: {
      shipPromise: logistics.shipPromise,
      freightDesc: logistics.freightDesc,
      shipCity: logistics.shipCity
    },
    shop: {
      shopId: shop.shopId,
      shopName: shop.shopName,
      shopAvatar: resolveFileUrl(shop.shopAvatar) || SHOP_AVATAR_PLACEHOLDER,
      shopStatus: shop.shopStatus,
      shopPhone: shop.shopPhone,
      rating: shop.rating,
      fansCount: shop.fansCount
    },
    purchase: {
      allowed: !!purchase.allowed,
      reason: purchase.reason || ''
    },
    afterSalePhone: data.afterSalePhone || shop.shopPhone || '',
    isOnSale: String(data.goodsStatus) === '2',
    isOffShelf: String(data.goodsStatus) === '4'
  }
}

/**
 * 详情 specDisplay（{ itemName, values[] }）→ 加购 specText
 * 多条规格用 CART_SPEC_SEPARATOR（§）拼接，购物车再拆开展示
 */
export function formatSpecDisplayText(specDisplay) {
  if (!Array.isArray(specDisplay) || !specDisplay.length) {
    return '默认'
  }
  const parts = specDisplay
    .map((spec) => {
      if (!spec || typeof spec !== 'object') {
        return spec != null && spec !== '' ? String(spec) : ''
      }
      const name = spec.itemName || spec.name || ''
      const vals = spec.values
      const valText = Array.isArray(vals)
        ? vals.filter((v) => v != null && v !== '').join('、')
        : vals != null && vals !== ''
          ? String(vals)
          : ''
      if (name && valText) return `${name}：${valText}`
      return name || valText
    })
    .filter(Boolean)
  return joinCartSpecParts(parts)
}

function mapService(row) {
  return {
    serviceId: row.serviceId,
    serviceName: row.serviceName,
    serviceIntro: row.serviceIntro,
    serviceIcon: resolveFileUrl(row.serviceIcon)
  }
}

export function mapReviewRow(row) {
  if (!row) return null
  let pics = row.pics
  if (typeof pics === 'string' && pics) {
    pics = pics.split(',').map((s) => s.trim()).filter(Boolean)
  }
  if (!Array.isArray(pics)) {
    pics = []
  }
  return {
    reviewId: row.reviewId,
    memberNickName: row.memberNickName || '匿名用户',
    memberAvatar: resolveFileUrl(row.memberAvatar),
    content: row.content,
    pics: pics.map((p) => resolveFileUrl(p)).filter(Boolean),
    score: row.score,
    goodsMainPic: resolveFileUrl(row.goodsMainPic),
    goodsSpec: row.goodsSpec,
    replyContent: row.replyContent,
    replyTime: row.replyTime,
    createTime: row.createTime
  }
}

export function mapReviewList(list) {
  if (!Array.isArray(list)) return []
  return list.map(mapReviewRow).filter(Boolean)
}

/** 售后服务说明文案 */
export function buildAfterSaleText(phone) {
  const contact = phone ? `【${phone}】` : '【平台客服】'
  return `售后无忧有保障，让您购物更放心！签收后若遇任何问题，随时联系我们${contact}，专业售后团队为您妥善处理！`
}
