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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.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.support.SellerShopContext;
import com.ruoyi.web.modules.goodsservice.domain.BizGoodsService;
import com.ruoyi.web.modules.goodsservice.facade.IGoodsServiceFacade;
import com.ruoyi.web.modules.goodsservice.mapper.BizGoodsServiceMapper;
import com.ruoyi.web.modules.goods.constant.GoodsConstants;
import com.ruoyi.web.modules.goods.domain.BizGoods;
import com.ruoyi.web.modules.goods.domain.BizGoodsAttr;
import com.ruoyi.web.modules.goods.domain.BizGoodsServiceSnapshot;
import com.ruoyi.web.modules.goods.dto.GoodsAuditDTO;
import com.ruoyi.web.modules.goods.dto.GoodsAttrItemDTO;
import com.ruoyi.web.modules.goods.dto.GoodsBatchIdsDTO;
import com.ruoyi.web.modules.goods.dto.GoodsOffShelfDTO;
import com.ruoyi.web.modules.goods.dto.GoodsSaveDTO;
import com.ruoyi.web.modules.goods.exception.GoodsBatchOperationException;
import com.ruoyi.web.modules.goods.facade.IGoodsOrderFacade;
import com.ruoyi.web.modules.goods.mapper.BizGoodsAttrMapper;
import com.ruoyi.web.modules.goods.mapper.BizGoodsMapper;
import com.ruoyi.web.modules.goods.mapper.BizGoodsServiceSnapshotMapper;
import com.ruoyi.web.modules.goods.service.IGoodsService;
import com.ruoyi.web.modules.goods.support.GoodsAttrSupport;
import com.ruoyi.web.modules.goods.support.GoodsSnGenerator;
import com.ruoyi.web.modules.goods.support.GoodsStatusUtils;
import com.ruoyi.web.modules.goods.vo.GoodsDetailVO;
import com.ruoyi.web.modules.goods.vo.GoodsListVO;
import com.ruoyi.web.modules.goods.vo.GoodsServiceSnapshotVO;
import com.ruoyi.web.modules.merchant.domain.BizMerchant;
import com.ruoyi.web.modules.merchant.mapper.BizMerchantMapper;
import com.ruoyi.web.modules.merchant.support.MerchantDisplayUtils;
import com.ruoyi.web.modules.store.constant.ShopConstants;
import com.ruoyi.web.modules.store.domain.BizShop;
import com.ruoyi.web.modules.store.facade.IShopGlobalConfigFacade;
import com.ruoyi.web.modules.store.mapper.BizShopMapper;
import com.ruoyi.web.modules.template.constant.AttrTemplateConstants;
import com.ruoyi.web.modules.template.domain.BizGoodsAttrTemplate;
import com.ruoyi.web.modules.template.mapper.BizGoodsAttrTemplateMapper;

@Service
public class GoodsServiceImpl implements IGoodsService
{
    @Autowired
    private BizGoodsMapper goodsMapper;

    @Autowired
    private BizGoodsServiceSnapshotMapper snapshotMapper;

    @Autowired
    private BizGoodsCategoryMapper categoryMapper;

    @Autowired
    private BizShopMapper shopMapper;

    @Autowired
    private BizGoodsServiceMapper goodsServiceMapper;

    @Autowired
    private ICategoryFacade categoryFacade;

    @Autowired
    private IGoodsServiceFacade goodsServiceFacade;

    @Autowired
    private GoodsSnGenerator goodsSnGenerator;

    @Autowired
    private BizMerchantMapper merchantMapper;

    @Autowired
    private IShopGlobalConfigFacade shopGlobalConfigFacade;

    @Autowired
    private IGoodsOrderFacade goodsOrderFacade;

    @Autowired
    private BizGoodsAttrTemplateMapper attrTemplateMapper;

    @Autowired
    private BizGoodsAttrMapper goodsAttrMapper;

    @Override
    public List<GoodsListVO> selectPlatformList(BizGoods query)
    {
        normalizePlatformQuery(query);
        List<GoodsListVO> rows = goodsMapper.selectPlatformList(query);
        fillStatusLabel(rows);
        return rows;
    }

    @Override
    public int countPlatformPending()
    {
        return goodsMapper.countPlatformPending();
    }

    @Override
    public List<GoodsListVO> selectSellerList(Long shopId, BizGoods query)
    {
        requireShopId(shopId);
        query.setShopId(shopId);
        List<GoodsListVO> rows = goodsMapper.selectSellerList(query);
        fillStatusLabel(rows);
        return rows;
    }

    @Override
    public GoodsDetailVO selectPlatformDetail(Long goodsId)
    {
        BizGoods goods = requireGoods(goodsId);
        if (GoodsConstants.STATUS_DRAFT.equals(goods.getGoodsStatus()))
        {
            throw new ServiceException(GoodsConstants.MSG_GOODS_NOT_FOUND);
        }
        return toDetailVo(goods, true);
    }

    @Override
    public GoodsDetailVO selectSellerDetail(Long shopId, Long goodsId)
    {
        requireShopId(shopId);
        BizGoods goods = requireGoodsOfShop(goodsId, shopId);
        return toDetailVo(goods, false);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertSellerGoods(Long shopId, GoodsSaveDTO dto, String operator)
    {
        requireShopId(shopId);
        rejectGoodsStatusInBody(dto);
        validateSaveFields(dto, true);
        assertPlatformCategoryLevel2(dto.getCategoryId());
        assertShopCategoryIfPresent(shopId, dto.getShopCategoryId());
        assertAttrTemplateIfPresent(shopId, dto.getAttrTemplateId());
        BizGoods goods = buildGoodsFromDto(dto);
        goods.setShopId(shopId);
        goods.setGoodsSn(goodsSnGenerator.nextSn());
        goods.setGoodsStatus(GoodsConstants.STATUS_DRAFT);
        goods.setSalesCount(0);
        goods.setDelFlag(GoodsConstants.DEL_NORMAL);
        goods.setCreateBy(operator);
        goodsMapper.insert(goods);
        saveServiceSnapshots(goods.getGoodsId(), dto.getServiceIds());
        saveGoodsAttrs(goods.getGoodsId(), dto.getAttributes(), dto.getSpecs());
        return goods.getGoodsId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSellerGoods(Long shopId, GoodsSaveDTO dto, String operator)
    {
        requireShopId(shopId);
        rejectGoodsStatusInBody(dto);
        if (dto.getGoodsId() == null)
        {
            throw new ServiceException("商品ID不能为空");
        }
        requireGoodsOfShop(dto.getGoodsId(), shopId);
        validateSaveFields(dto, false);
        if (dto.getCategoryId() != null)
        {
            assertPlatformCategoryLevel2(dto.getCategoryId());
        }
        assertShopCategoryIfPresent(shopId, dto.getShopCategoryId());
        assertAttrTemplateIfPresent(shopId, dto.getAttrTemplateId());
        BizGoods update = buildGoodsFromDto(dto);
        update.setGoodsId(dto.getGoodsId());
        update.setUpdateBy(operator);
        goodsMapper.updateSeller(update);
        saveServiceSnapshots(dto.getGoodsId(), dto.getServiceIds());
        saveGoodsAttrs(dto.getGoodsId(), dto.getAttributes(), dto.getSpecs());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> submitGoods(Long shopId, Long goodsId, String operator)
    {
        requireShopId(shopId);
        BizGoods goods = requireGoodsOfShop(goodsId, shopId);
        String current = goods.getGoodsStatus();
        if (!GoodsConstants.STATUS_DRAFT.equals(current)
                && !GoodsConstants.STATUS_REJECTED.equals(current)
                && !GoodsConstants.STATUS_OFF_SHELF.equals(current))
        {
            throw new ServiceException(GoodsConstants.MSG_SUBMIT_INVALID);
        }
        BizShop shop = shopMapper.selectById(shopId);
        if (shop == null)
        {
            throw new ServiceException("店铺不存在");
        }
        String targetStatus = ShopConstants.AUDIT_PASS_YES.equals(shopGlobalConfigFacade.getDefaultAuditPass())
                ? GoodsConstants.STATUS_ON_SALE : GoodsConstants.STATUS_PENDING;
        boolean firstSubmit = goods.getSubmitTime() == null;
        Date submitTime = firstSubmit ? new Date() : goods.getSubmitTime();
        goodsMapper.updateSubmitStatus(goodsId, targetStatus, submitTime, firstSubmit, operator);
        Map<String, Object> data = new HashMap<>();
        data.put("goodsId", goodsId);
        data.put("goodsStatus", targetStatus);
        data.put("goodsStatusLabel", GoodsStatusUtils.label(targetStatus));
        return data;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitGoodsBatch(Long shopId, GoodsBatchIdsDTO dto, String operator)
    {
        requireShopId(shopId);
        if (dto.getGoodsIds() == null || dto.getGoodsIds().isEmpty())
        {
            throw new ServiceException(GoodsConstants.MSG_SELECT_GOODS);
        }
        List<String> reasons = new ArrayList<>();
        for (Long goodsId : dto.getGoodsIds())
        {
            BizGoods goods = goodsMapper.selectByIdAndShop(goodsId, shopId);
            if (goods == null)
            {
                reasons.add(GoodsConstants.MSG_NOT_OWNER);
                continue;
            }
            if (!canSubmitStatus(goods.getGoodsStatus()))
            {
                reasons.add("商品不可提交上架：" + goods.getGoodsSn());
            }
        }
        if (!reasons.isEmpty())
        {
            throw new GoodsBatchOperationException(GoodsConstants.MSG_BATCH_FAIL, reasons);
        }
        for (Long goodsId : dto.getGoodsIds())
        {
            submitGoods(shopId, goodsId, operator);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditGoods(GoodsAuditDTO dto, String operator)
    {
        if (dto.getGoodsIds() == null || dto.getGoodsIds().isEmpty())
        {
            throw new ServiceException("请选择要审核的商品");
        }
        if (!dto.isPass() && StringUtils.isEmpty(dto.getRejectReason()))
        {
            throw new ServiceException(GoodsConstants.MSG_REJECT_REASON);
        }
        List<String> reasons = new ArrayList<>();
        for (Long goodsId : dto.getGoodsIds())
        {
            BizGoods goods = goodsMapper.selectById(goodsId);
            if (goods == null)
            {
                reasons.add("商品不存在：" + goodsId);
                continue;
            }
            if (!GoodsConstants.STATUS_PENDING.equals(goods.getGoodsStatus()))
            {
                reasons.add("商品非待审核状态：" + goods.getGoodsSn());
            }
        }
        if (!reasons.isEmpty())
        {
            throw new GoodsBatchOperationException(GoodsConstants.MSG_BATCH_FAIL, reasons);
        }
        for (Long goodsId : dto.getGoodsIds())
        {
            int rows;
            if (dto.isPass())
            {
                rows = goodsMapper.updateAuditPass(goodsId, operator);
            }
            else
            {
                rows = goodsMapper.updateAuditReject(goodsId, dto.getRejectReason(), operator);
            }
            if (rows == 0)
            {
                throw new ServiceException(GoodsConstants.MSG_AUDIT_INVALID);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void offShelfPlatform(GoodsOffShelfDTO dto, String operator)
    {
        offShelfBatch(dto, null, operator);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void offShelfSeller(Long shopId, Long goodsId, String operator)
    {
        requireShopId(shopId);
        GoodsOffShelfDTO dto = new GoodsOffShelfDTO();
        List<Long> ids = new ArrayList<>();
        ids.add(goodsId);
        dto.setGoodsIds(ids);
        offShelfBatch(dto, shopId, operator);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void offShelfSellerBatch(Long shopId, GoodsOffShelfDTO dto, String operator)
    {
        requireShopId(shopId);
        offShelfBatch(dto, shopId, operator);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSellerGoods(Long shopId, Long goodsId, String operator)
    {
        requireShopId(shopId);
        GoodsBatchIdsDTO dto = new GoodsBatchIdsDTO();
        dto.setGoodsIds(java.util.Collections.singletonList(goodsId));
        deleteSellerGoodsBatch(shopId, dto, operator);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSellerGoodsBatch(Long shopId, GoodsBatchIdsDTO dto, String operator)
    {
        requireShopId(shopId);
        if (dto.getGoodsIds() == null || dto.getGoodsIds().isEmpty())
        {
            throw new ServiceException(GoodsConstants.MSG_SELECT_GOODS);
        }
        List<String> reasons = new ArrayList<>();
        for (Long goodsId : dto.getGoodsIds())
        {
            BizGoods goods = goodsMapper.selectByIdAndShop(goodsId, shopId);
            if (goods == null)
            {
                reasons.add(GoodsConstants.MSG_NOT_OWNER);
                continue;
            }
            if (!canDeleteStatus(goods.getGoodsStatus()))
            {
                reasons.add(GoodsConstants.MSG_DELETE_INVALID + "：" + goods.getGoodsSn());
            }
        }
        if (!reasons.isEmpty())
        {
            throw new GoodsBatchOperationException(GoodsConstants.MSG_BATCH_FAIL, reasons);
        }
        goodsMapper.logicDeleteByIds(dto.getGoodsIds(), shopId, operator);
        for (Long goodsId : dto.getGoodsIds())
        {
            snapshotMapper.deleteByGoodsId(goodsId);
            goodsAttrMapper.deleteByGoodsId(goodsId);
        }
    }

    private void offShelfBatch(GoodsOffShelfDTO dto, Long shopId, String operator)
    {
        if (dto.getGoodsIds() == null || dto.getGoodsIds().isEmpty())
        {
            throw new ServiceException("请选择要下架的商品");
        }
        List<String> reasons = new ArrayList<>();
        for (Long goodsId : dto.getGoodsIds())
        {
            BizGoods goods = goodsMapper.selectById(goodsId);
            if (goods == null)
            {
                reasons.add("商品不存在");
                continue;
            }
            if (shopId != null && !shopId.equals(goods.getShopId()))
            {
                reasons.add(GoodsConstants.MSG_NOT_OWNER);
                continue;
            }
            if (!GoodsConstants.STATUS_ON_SALE.equals(goods.getGoodsStatus()))
            {
                reasons.add(GoodsConstants.MSG_OFF_SHELF_INVALID);
                continue;
            }
            if (goodsOrderFacade.hasUnfinishedOrderByGoodsId(goodsId))
            {
                reasons.add(GoodsConstants.MSG_UNFINISHED_ORDER + "：" + goods.getGoodsSn());
            }
        }
        if (!reasons.isEmpty())
        {
            throw new GoodsBatchOperationException(GoodsConstants.MSG_BATCH_FAIL, reasons);
        }
        for (Long goodsId : dto.getGoodsIds())
        {
            if (goodsMapper.updateOffShelf(goodsId, operator) == 0)
            {
                throw new ServiceException(GoodsConstants.MSG_OFF_SHELF_INVALID);
            }
        }
    }

    private GoodsDetailVO toDetailVo(BizGoods goods, boolean platform)
    {
        GoodsDetailVO vo = new GoodsDetailVO();
        vo.setGoodsId(goods.getGoodsId());
        vo.setShopId(goods.getShopId());
        vo.setCategoryId(goods.getCategoryId());
        vo.setShopCategoryId(goods.getShopCategoryId());
        vo.setAttrTemplateId(goods.getAttrTemplateId());
        vo.setGoodsSn(goods.getGoodsSn());
        vo.setGoodsName(goods.getGoodsName());
        vo.setMainPic(goods.getMainPic());
        vo.setDetailContent(goods.getDetailContent());
        vo.setSalePrice(goods.getSalePrice());
        vo.setStock(goods.getStock());
        vo.setSalesCount(goods.getSalesCount());
        vo.setGoodsStatus(goods.getGoodsStatus());
        vo.setGoodsStatusLabel(GoodsStatusUtils.label(goods.getGoodsStatus()));
        vo.setRejectReason(goods.getRejectReason());
        vo.setSubmitTime(goods.getSubmitTime());
        vo.setAuditTime(goods.getAuditTime());
        vo.setOffShelfTime(goods.getOffShelfTime());
        vo.setCategoryPath(categoryFacade.getCategoryPath(goods.getCategoryId()));
        if (goods.getShopCategoryId() != null)
        {
            vo.setShopCategoryPath(categoryFacade.getCategoryPath(goods.getShopCategoryId()));
        }
        if (goods.getAttrTemplateId() != null)
        {
            BizGoodsAttrTemplate template = attrTemplateMapper.selectById(goods.getAttrTemplateId(), goods.getShopId());
            if (template != null)
            {
                vo.setAttrTemplateName(template.getTemplateName());
            }
        }
        vo.setCanAudit(GoodsConstants.STATUS_PENDING.equals(goods.getGoodsStatus()));
        vo.setCanOffShelf(GoodsConstants.STATUS_ON_SALE.equals(goods.getGoodsStatus()));
        vo.setCanSubmit(canSubmitStatus(goods.getGoodsStatus()));
        vo.setCanDelete(canDeleteStatus(goods.getGoodsStatus()));
        vo.setCanEdit(true);
        List<GoodsServiceSnapshotVO> services = snapshotMapper.selectVisibleByGoodsId(goods.getGoodsId());
        vo.setServices(services);
        List<BizGoodsAttr> attrRows = goodsAttrMapper.selectByGoodsId(goods.getGoodsId());
        vo.setAttributes(GoodsAttrSupport.groupByItem(attrRows, AttrTemplateConstants.ITEM_TYPE_ATTR));
        vo.setSpecs(GoodsAttrSupport.groupByItem(attrRows, AttrTemplateConstants.ITEM_TYPE_SPEC));
        if (platform)
        {
            fillShopMerchantName(vo, goods.getShopId());
        }
        return vo;
    }

    private void fillShopMerchantName(GoodsDetailVO vo, Long shopId)
    {
        BizShop shop = shopMapper.selectById(shopId);
        if (shop == null)
        {
            return;
        }
        vo.setShopName(shop.getShopName());
        BizMerchant merchant = merchantMapper.selectById(shop.getMerchantId());
        if (merchant != null)
        {
            String name = StringUtils.isNotEmpty(merchant.getMerchantName())
                    ? merchant.getMerchantName() : MerchantDisplayUtils.unitName(merchant);
            vo.setMerchantName(name);
        }
    }

    private void fillStatusLabel(List<GoodsListVO> rows)
    {
        for (GoodsListVO row : rows)
        {
            row.setGoodsStatusLabel(GoodsStatusUtils.label(row.getGoodsStatus()));
        }
    }

    private void normalizePlatformQuery(BizGoods query)
    {
        if (query == null)
        {
            return;
        }
        if (StringUtils.isNotEmpty(query.getGoodsStatus()) && StringUtils.isEmpty(query.getGoodsStatusQuery()))
        {
            query.setGoodsStatusQuery(query.getGoodsStatus());
        }
    }

    private void saveServiceSnapshots(Long goodsId, List<Long> serviceIds)
    {
        snapshotMapper.deleteByGoodsId(goodsId);
        if (serviceIds == null || serviceIds.isEmpty())
        {
            return;
        }
        Set<Long> enabledIds = new HashSet<>();
        goodsServiceFacade.listAllEnabled().forEach(o -> enabledIds.add(o.getServiceId()));
        List<BizGoodsServiceSnapshot> list = new ArrayList<>();
        for (Long serviceId : serviceIds)
        {
            if (!enabledIds.contains(serviceId))
            {
                throw new ServiceException(GoodsConstants.MSG_SERVICE_INVALID);
            }
            BizGoodsService svc = goodsServiceMapper.selectById(serviceId);
            if (svc == null)
            {
                continue;
            }
            BizGoodsServiceSnapshot snap = new BizGoodsServiceSnapshot();
            snap.setGoodsId(goodsId);
            snap.setServiceId(serviceId);
            snap.setServiceName(svc.getServiceName());
            snap.setServiceIntro(svc.getServiceIntro());
            snap.setServiceIcon(svc.getServiceIcon());
            snap.setSortNo(svc.getSortNo());
            list.add(snap);
        }
        if (!list.isEmpty())
        {
            snapshotMapper.batchInsert(list);
        }
    }

    private void saveGoodsAttrs(Long goodsId, List<GoodsAttrItemDTO> attributes, List<GoodsAttrItemDTO> specs)
    {
        goodsAttrMapper.deleteByGoodsId(goodsId);
        if ((attributes == null || attributes.isEmpty()) && (specs == null || specs.isEmpty()))
        {
            return;
        }
        List<BizGoodsAttr> rows = GoodsAttrSupport.flatten(goodsId, attributes, specs);
        if (!rows.isEmpty())
        {
            goodsAttrMapper.batchInsert(rows);
        }
    }

    private BizGoods buildGoodsFromDto(GoodsSaveDTO dto)
    {
        BizGoods goods = new BizGoods();
        goods.setCategoryId(dto.getCategoryId());
        goods.setShopCategoryId(dto.getShopCategoryId());
        goods.setAttrTemplateId(dto.getAttrTemplateId());
        goods.setGoodsName(dto.getGoodsName());
        goods.setMainPic(dto.getMainPic());
        goods.setDetailContent(dto.getDetailContent());
        goods.setSalePrice(dto.getSalePrice());
        goods.setStock(dto.getStock());
        return goods;
    }

    private void validateSaveFields(GoodsSaveDTO dto, boolean insert)
    {
        if (insert)
        {
            if (dto.getCategoryId() == null)
            {
                throw new ServiceException("请选择分类");
            }
        }
        if (StringUtils.isNotEmpty(dto.getGoodsName()))
        {
            if (dto.getGoodsName().length() > 200)
            {
                throw new ServiceException("商品名称过长");
            }
        }
        else if (insert)
        {
            throw new ServiceException("请输入商品名称");
        }
        if (insert && StringUtils.isEmpty(dto.getMainPic()))
        {
            throw new ServiceException("请上传商品主图");
        }
        if (insert && StringUtils.isEmpty(dto.getDetailContent()))
        {
            throw new ServiceException("请填写商品详情");
        }
        if (dto.getSalePrice() != null && dto.getSalePrice().compareTo(BigDecimal.ZERO) < 0)
        {
            throw new ServiceException("销售价不能为负数");
        }
        if (insert && dto.getSalePrice() == null)
        {
            throw new ServiceException("请输入销售价");
        }
        if (dto.getStock() != null && dto.getStock() < 0)
        {
            throw new ServiceException("库存不能为负数");
        }
        if (insert && dto.getStock() == null)
        {
            throw new ServiceException("请输入库存");
        }
    }

    private void assertPlatformCategoryLevel2(Long categoryId)
    {
        BizGoodsCategory cat = categoryMapper.selectById(categoryId, null);
        if (cat == null || !CategoryConstants.LEVEL_TWO.equals(cat.getCategoryLevel()))
        {
            throw new ServiceException(GoodsConstants.MSG_CATEGORY_INVALID);
        }
    }

    private void assertShopCategoryIfPresent(Long shopId, Long shopCategoryId)
    {
        if (shopCategoryId == null)
        {
            return;
        }
        BizGoodsCategory cat = categoryMapper.selectById(shopCategoryId, shopId);
        if (cat == null || !CategoryConstants.LEVEL_TWO.equals(cat.getCategoryLevel()))
        {
            throw new ServiceException(GoodsConstants.MSG_SHOP_CATEGORY_INVALID);
        }
    }

    private void assertAttrTemplateIfPresent(Long shopId, Long attrTemplateId)
    {
        if (attrTemplateId == null)
        {
            return;
        }
        BizGoodsAttrTemplate template = attrTemplateMapper.selectById(attrTemplateId, shopId);
        if (template == null)
        {
            throw new ServiceException(GoodsConstants.MSG_ATTR_TEMPLATE_INVALID);
        }
    }

    private boolean canSubmitStatus(String status)
    {
        return GoodsConstants.STATUS_DRAFT.equals(status)
                || GoodsConstants.STATUS_REJECTED.equals(status)
                || GoodsConstants.STATUS_OFF_SHELF.equals(status);
    }

    private boolean canDeleteStatus(String status)
    {
        return GoodsConstants.STATUS_DRAFT.equals(status)
                || GoodsConstants.STATUS_REJECTED.equals(status)
                || GoodsConstants.STATUS_OFF_SHELF.equals(status);
    }

    private void rejectGoodsStatusInBody(GoodsSaveDTO dto)
    {
        if (StringUtils.isNotEmpty(dto.getGoodsStatus()))
        {
            if (GoodsConstants.STATUS_DRAFT.equals(dto.getGoodsStatus())
                    && dto.getGoodsId() != null)
            {
                BizGoods existing = goodsMapper.selectById(dto.getGoodsId());
                if (existing != null && !GoodsConstants.STATUS_DRAFT.equals(existing.getGoodsStatus()))
                {
                    throw new ServiceException(GoodsConstants.MSG_CANNOT_REVERT_DRAFT);
                }
            }
            throw new ServiceException(GoodsConstants.MSG_ILLEGAL_STATUS_CHANGE);
        }
    }

    private void requireShopId(Long shopId)
    {
        Long ctx = SellerShopContext.getShopId();
        if (shopId == null)
        {
            shopId = ctx;
        }
        if (shopId == null || shopId <= 0)
        {
            throw new ServiceException(GoodsConstants.MSG_NO_SHOP);
        }
    }

    private BizGoods requireGoods(Long goodsId)
    {
        BizGoods goods = goodsMapper.selectById(goodsId);
        if (goods == null)
        {
            throw new ServiceException(GoodsConstants.MSG_GOODS_NOT_FOUND);
        }
        return goods;
    }

    private BizGoods requireGoodsOfShop(Long goodsId, Long shopId)
    {
        BizGoods goods = goodsMapper.selectByIdAndShop(goodsId, shopId);
        if (goods == null)
        {
            throw new ServiceException(GoodsConstants.MSG_NOT_OWNER);
        }
        return goods;
    }
}
