package com.ruoyi.web.modules.home.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.category.facade.ICategoryFacade;
import com.ruoyi.web.modules.delivery.facade.IShopDeliveryFacade;
import com.ruoyi.web.modules.goods.constant.GoodsConstants;
import com.ruoyi.web.modules.goods.domain.BizGoodsAttr;
import com.ruoyi.web.modules.goods.facade.IGoodsPurchaseFacade;
import com.ruoyi.web.modules.goods.mapper.BizGoodsAttrMapper;
import com.ruoyi.web.modules.goods.mapper.BizGoodsPicMapper;
import com.ruoyi.web.modules.goods.mapper.BizGoodsServiceSnapshotMapper;
import com.ruoyi.web.modules.goods.support.GoodsAttrSupport;
import com.ruoyi.web.modules.goods.support.GoodsPicSupport;
import com.ruoyi.web.modules.goods.support.GoodsStatusUtils;
import com.ruoyi.web.modules.goods.vo.GoodsPurchaseVO;
import com.ruoyi.web.modules.goods.vo.GoodsServiceSnapshotVO;
import com.ruoyi.web.modules.home.constant.GoodsAppConstants;
import com.ruoyi.web.modules.home.dto.GoodsDetailBaseDTO;
import com.ruoyi.web.modules.home.mapper.GoodsAppMapper;
import com.ruoyi.web.modules.home.service.IGoodsAppService;
import com.ruoyi.web.modules.home.vo.GoodsDetailAppVO;
import com.ruoyi.web.modules.mall.facade.IMallConfigFacade;
import com.ruoyi.web.modules.home.vo.GoodsLogisticsAppVO;
import com.ruoyi.web.modules.home.vo.GoodsReviewAppVO;
import com.ruoyi.web.modules.home.vo.GoodsShopBriefAppVO;
import com.ruoyi.web.modules.order.domain.BizGoodsReview;
import com.ruoyi.web.modules.order.mapper.BizGoodsReviewMapper;
import com.ruoyi.web.modules.order.support.OrderAppSupport;
import com.ruoyi.web.modules.template.constant.AttrTemplateConstants;

/**
 * C 端商品详情 Service 实现
 */
@Service
public class GoodsAppServiceImpl implements IGoodsAppService
{
    @Autowired
    private GoodsAppMapper goodsAppMapper;

    @Autowired
    private BizGoodsPicMapper goodsPicMapper;

    @Autowired
    private BizGoodsServiceSnapshotMapper snapshotMapper;

    @Autowired
    private BizGoodsAttrMapper goodsAttrMapper;

    @Autowired
    private ICategoryFacade categoryFacade;

    @Autowired
    private IGoodsPurchaseFacade purchaseFacade;

    @Autowired
    private IShopDeliveryFacade shopDeliveryFacade;

    @Autowired
    private BizGoodsReviewMapper reviewMapper;

    @Autowired
    private OrderAppSupport orderAppSupport;

    @Autowired
    private IMallConfigFacade mallConfigFacade;

    @Override
    public GoodsDetailAppVO getDetail(Long goodsId)
    {
        GoodsDetailBaseDTO base = goodsAppMapper.selectDetailBase(goodsId);
        if (base == null)
        {
            throw new ServiceException(GoodsConstants.MSG_GOODS_NOT_FOUND);
        }

        GoodsDetailAppVO vo = new GoodsDetailAppVO();
        vo.setGoodsId(base.getGoodsId());
        vo.setGoodsSn(base.getGoodsSn());
        vo.setGoodsName(base.getGoodsName());
        vo.setGoodsBrief(null);
        vo.setSalePrice(base.getSalePrice());
        vo.setStock(base.getStock());
        if (mallConfigFacade.isShowSales())
        {
            vo.setSalesCount(base.getSalesCount());
        }
        vo.setGoodsStatus(base.getGoodsStatus());
        vo.setGoodsStatusLabel(GoodsStatusUtils.label(base.getGoodsStatus()));
        vo.setDetailContent(base.getDetailContent());

        List<String> subPics = goodsPicMapper.selectPicUrlsByGoodsId(goodsId);
        vo.setPics(GoodsPicSupport.buildGalleryPics(base.getMainPic(), subPics));

        if (base.getCategoryId() != null)
        {
            vo.setCategoryPath(categoryFacade.getCategoryPath(base.getCategoryId()));
        }

        List<GoodsServiceSnapshotVO> services = snapshotMapper.selectVisibleByGoodsId(goodsId);
        vo.setServices(services != null ? services : Collections.emptyList());

        List<BizGoodsAttr> attrRows = goodsAttrMapper.selectByGoodsId(goodsId);
        vo.setAttributes(GoodsAttrSupport.groupByItem(attrRows, AttrTemplateConstants.ITEM_TYPE_ATTR));
        vo.setSpecDisplay(GoodsAttrSupport.groupByItem(attrRows, AttrTemplateConstants.ITEM_TYPE_SPEC));

        vo.setLogistics(buildLogistics(base.getShopId(), services));
        vo.setShop(buildShop(base));
        vo.setAfterSalePhone(resolvePhone(base.getShopPhone()));
        vo.setPurchase(purchaseFacade.canPurchase(goodsId));
        return vo;
    }

    @Override
    public GoodsPurchaseVO canPurchase(Long goodsId)
    {
        return purchaseFacade.canPurchase(goodsId);
    }

    @Override
    public List<GoodsReviewAppVO> listReviews(Long goodsId)
    {
        List<BizGoodsReview> rows = reviewMapper.selectByGoodsId(goodsId);
        if (rows == null || rows.isEmpty())
        {
            return Collections.emptyList();
        }
        List<GoodsReviewAppVO> list = new ArrayList<>(rows.size());
        for (BizGoodsReview row : rows)
        {
            list.add(toReviewVo(row));
        }
        return list;
    }

    private GoodsReviewAppVO toReviewVo(BizGoodsReview row)
    {
        GoodsReviewAppVO vo = new GoodsReviewAppVO();
        vo.setReviewId(row.getReviewId());
        vo.setMemberAvatar(row.getMemberAvatar());
        vo.setMemberNickName(row.getMemberNickName());
        vo.setContent(row.getContent());
        vo.setPics(orderAppSupport.splitPics(row.getReviewPics()));
        vo.setScore(row.getScore());
        vo.setGoodsMainPic(row.getGoodsMainPic());
        vo.setGoodsSpec(row.getGoodsSpec());
        vo.setReplyContent(row.getReplyContent());
        vo.setReplyTime(row.getReplyTime());
        vo.setCreateTime(row.getCreateTime());
        return vo;
    }

    private GoodsShopBriefAppVO buildShop(GoodsDetailBaseDTO base)
    {
        GoodsShopBriefAppVO shop = new GoodsShopBriefAppVO();
        shop.setShopId(base.getShopId());
        shop.setShopName(base.getShopName());
        shop.setShopAvatar(base.getShopAvatar());
        shop.setShopStatus(base.getShopStatus());
        shop.setShopPhone(resolvePhone(base.getShopPhone()));
        if (base.getShopRating() != null)
        {
            shop.setRating(base.getShopRating().toPlainString());
        }
        shop.setFansCount(base.getShopFansCount());
        return shop;
    }

    private GoodsLogisticsAppVO buildLogistics(Long shopId, List<GoodsServiceSnapshotVO> services)
    {
        GoodsLogisticsAppVO logistics = new GoodsLogisticsAppVO();
        logistics.setShipPromise(resolveShipPromise(services));
        logistics.setFreightDesc(null);
        logistics.setShipCity(shopDeliveryFacade.getShipCity(shopId));
        return logistics;
    }

    private String resolveShipPromise(List<GoodsServiceSnapshotVO> services)
    {
        if (services == null)
        {
            return null;
        }
        for (GoodsServiceSnapshotVO service : services)
        {
            if (service.getServiceName() != null
                    && service.getServiceName().contains(GoodsAppConstants.SHIP_PROMISE_KEYWORD))
            {
                return service.getServiceName();
            }
        }
        return null;
    }

    private String resolvePhone(String shopPhone)
    {
        return StringUtils.isNotEmpty(shopPhone) ? shopPhone : null;
    }
}
