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

import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.account.facade.IMemberFacade;
import com.ruoyi.web.modules.category.constant.CategoryConstants;
import com.ruoyi.web.modules.category.domain.BizGoodsCategory;
import com.ruoyi.web.modules.category.facade.ICategoryFacade;
import com.ruoyi.web.modules.category.mapper.BizGoodsCategoryMapper;
import com.ruoyi.web.modules.category.vo.CategoryVisibleChildVO;
import com.ruoyi.web.modules.category.vo.CategoryVisibleVO;
import com.ruoyi.web.modules.home.constant.CategoryAppConstants;
import com.ruoyi.web.modules.home.constant.ShopAppConstants;
import com.ruoyi.web.modules.home.dto.ShopGoodsQuery;
import com.ruoyi.web.modules.home.dto.ShopProfileRowDTO;
import com.ruoyi.web.modules.home.mapper.ShopAppMapper;
import com.ruoyi.web.modules.home.service.IShopAppService;
import com.ruoyi.web.modules.home.vo.HomeHotGoodsVO;
import com.ruoyi.web.modules.home.vo.ShopProfileAppVO;

/**
 * C 端店铺主页 Service 实现
 */
@Service
public class ShopAppServiceImpl implements IShopAppService
{
    @Autowired
    private ShopAppMapper shopAppMapper;

    @Autowired
    private ICategoryFacade categoryFacade;

    @Autowired
    private BizGoodsCategoryMapper categoryMapper;

    @Autowired
    private IMemberFacade memberFacade;

    @Override
    public ShopProfileAppVO getProfile(Long shopId, Long memberId)
    {
        ShopProfileRowDTO row = shopAppMapper.selectProfileByShopId(shopId);
        if (row == null)
        {
            throw new ServiceException(ShopAppConstants.MSG_SHOP_NOT_FOUND);
        }
        ShopProfileAppVO vo = new ShopProfileAppVO();
        vo.setShopId(row.getShopId());
        vo.setShopName(row.getShopName());
        vo.setShopAvatar(row.getShopAvatar());
        vo.setShopDesc(StringUtils.isNotEmpty(row.getShopDesc()) ? row.getShopDesc() : null);
        vo.setShopStatus(row.getShopStatus());
        vo.setShopPhone(StringUtils.isNotEmpty(row.getShopPhone()) ? row.getShopPhone() : null);
        vo.setRating(row.getRating());
        vo.setFansCount(row.getFansCount() != null ? row.getFansCount() : 0);
        vo.setFollowed(resolveFollowed(shopId, memberId));
        return vo;
    }

    @Override
    public List<CategoryVisibleVO> listCategories(Long shopId)
    {
        assertShopAccessible(shopId);
        List<CategoryVisibleVO> list = categoryFacade.listVisibleByShopId(shopId);
        return list != null ? list : Collections.emptyList();
    }

    @Override
    public List<CategoryVisibleChildVO> listLevel2Tabs(Long shopId, Long level1Id)
    {
        assertShopAccessible(shopId);
        assertShopLevel1Visible(shopId, level1Id);
        List<CategoryVisibleChildVO> list = shopAppMapper.selectShopLevel2Tabs(shopId, level1Id);
        return list != null ? list : Collections.emptyList();
    }

    @Override
    public List<HomeHotGoodsVO> listGoods(Long shopId, ShopGoodsQuery query)
    {
        assertShopAccessible(shopId);
        String keyword = resolveKeyword(query);
        Long shopCategoryId = query != null ? query.getShopCategoryId() : null;
        if (StringUtils.isNotEmpty(keyword))
        {
            List<HomeHotGoodsVO> list = shopAppMapper.selectShopGoods(shopId, null, keyword);
            return list != null ? list : Collections.emptyList();
        }
        if (shopCategoryId != null)
        {
            assertShopCategoryVisible(shopId, shopCategoryId);
        }
        List<HomeHotGoodsVO> list = shopAppMapper.selectShopGoods(shopId, shopCategoryId, null);
        return list != null ? list : Collections.emptyList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void follow(Long shopId, Long memberId)
    {
        assertShopAccessible(shopId);
        assertMemberEnabled(memberId);
        if (shopAppMapper.countFollow(memberId, shopId) > 0)
        {
            return;
        }
        shopAppMapper.insertFollow(memberId, shopId);
        if (shopAppMapper.incrementFansCount(shopId) == 0)
        {
            shopAppMapper.insertShopStats(shopId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unfollow(Long shopId, Long memberId)
    {
        assertShopAccessible(shopId);
        if (shopAppMapper.deleteFollow(memberId, shopId) > 0)
        {
            shopAppMapper.decrementFansCount(shopId);
        }
    }

    private Boolean resolveFollowed(Long shopId, Long memberId)
    {
        if (memberId == null)
        {
            return false;
        }
        return shopAppMapper.countFollow(memberId, shopId) > 0;
    }

    private String resolveKeyword(ShopGoodsQuery query)
    {
        if (query == null || query.getKeyword() == null)
        {
            return null;
        }
        String trimmed = query.getKeyword().trim();
        if (StringUtils.isEmpty(trimmed))
        {
            throw new ServiceException(ShopAppConstants.MSG_KEYWORD_REQUIRED);
        }
        return trimmed;
    }

    private void assertShopAccessible(Long shopId)
    {
        if (shopId == null)
        {
            throw new ServiceException(ShopAppConstants.MSG_SHOP_NOT_FOUND);
        }
        ShopProfileRowDTO row = shopAppMapper.selectProfileByShopId(shopId);
        if (row == null)
        {
            throw new ServiceException(ShopAppConstants.MSG_SHOP_NOT_FOUND);
        }
    }

    private void assertShopLevel1Visible(Long shopId, Long level1Id)
    {
        if (level1Id == null)
        {
            throw new ServiceException(CategoryAppConstants.MSG_CATEGORY_INVISIBLE);
        }
        BizGoodsCategory level1 = categoryMapper.selectByIdIgnoreShop(level1Id);
        if (level1 == null
                || !shopId.equals(level1.getShopId())
                || !CategoryConstants.LEVEL_ONE.equals(level1.getCategoryLevel())
                || !CategoryConstants.SHOW_YES.equals(level1.getShowFlag())
                || !CategoryConstants.DEL_FLAG_NORMAL.equals(level1.getDelFlag()))
        {
            throw new ServiceException(CategoryAppConstants.MSG_CATEGORY_INVISIBLE);
        }
    }

    private void assertShopCategoryVisible(Long shopId, Long shopCategoryId)
    {
        BizGoodsCategory category = categoryMapper.selectByIdIgnoreShop(shopCategoryId);
        if (category == null
                || !shopId.equals(category.getShopId())
                || !CategoryConstants.LEVEL_TWO.equals(category.getCategoryLevel()))
        {
            throw new ServiceException(CategoryAppConstants.MSG_CATEGORY_INVISIBLE);
        }
        if (!categoryFacade.isCategoryVisible(shopCategoryId))
        {
            throw new ServiceException(CategoryAppConstants.MSG_CATEGORY_INVISIBLE);
        }
    }

    private void assertMemberEnabled(Long memberId)
    {
        if (!memberFacade.isMemberEnabled(memberId))
        {
            throw new ServiceException(ShopAppConstants.MSG_MEMBER_DISABLED);
        }
    }
}
