import { resolveFileUrl } from '@/utils/image'
import { SHOP_STATUS_CLOSED } from '@/constants/shop'
import { mapCategoryTree, mapLevel2Tabs } from '@/utils/categoryDisplay'

const SHOP_PLACEHOLDER = '/static/logo.png'

/** 店铺主页介绍区 */
export function mapShopProfile(row) {
  if (!row) return null
  const rating = row.rating
  const fansCount = row.fansCount != null ? Number(row.fansCount) : 0
  return {
    shopId: row.shopId,
    shopName: row.shopName || '',
    shopAvatar: resolveFileUrl(row.shopAvatar) || SHOP_PLACEHOLDER,
    shopDesc: (row.shopDesc || '').trim(),
    shopStatus: row.shopStatus,
    shopPhone: row.shopPhone || '',
    rating,
    fansCount,
    followed: !!row.followed,
    isClosed: String(row.shopStatus) === SHOP_STATUS_CLOSED,
    showRating: rating != null && rating !== '',
    showFans: true,
    ratingText: rating != null && rating !== '' ? String(rating) : ''
  }
}

/** 店铺分类树 / 二级 Tab（字段同平台分类 VO） */
export function mapShopCategoryTree(list) {
  return mapCategoryTree(list)
}

export function mapShopLevel2Tabs(list) {
  return mapLevel2Tabs(list)
}

/** 热门分类靠前（同序保持 sortNo） */
export function sortShopTabsWithHot(list) {
  if (!Array.isArray(list) || !list.length) return []
  return [...list].sort((a, b) => {
    if (!!a.isHot !== !!b.isHot) return a.isHot ? -1 : 1
    const sa = Number(a.sortNo) || 0
    const sb = Number(b.sortNo) || 0
    return sa - sb
  })
}

/** 搜索店铺卡片 */
export function mapShopCard(row) {
  if (!row) return null
  return {
    shopId: row.shopId,
    shopName: row.shopName,
    shopAvatar: row.shopAvatar,
    displayAvatar: resolveFileUrl(row.shopAvatar) || SHOP_PLACEHOLDER,
    shopStatus: row.shopStatus,
    rating: row.rating,
    fansCount: row.fansCount,
    showRating: row.rating != null && row.rating !== '',
    showFans: row.fansCount != null && row.fansCount !== ''
  }
}

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

/** 我的店铺关注列表行 */
export function mapShopFollowItem(row) {
  if (!row) return null
  const rating = row.rating
  const fansCount = row.fansCount != null ? Number(row.fansCount) : 0
  return {
    shopId: row.shopId,
    shopName: row.shopName || '',
    shopAvatar: row.shopAvatar,
    displayAvatar: resolveFileUrl(row.shopAvatar) || SHOP_PLACEHOLDER,
    shopStatus: row.shopStatus,
    isClosed: String(row.shopStatus) === SHOP_STATUS_CLOSED,
    rating,
    fansCount,
    showRating: rating != null && rating !== '',
    ratingText: rating != null && rating !== '' ? String(rating) : '',
    followTime: row.followTime
  }
}

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