package co.yixiang.yshop.module.product.service.campaigninfo;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.module.product.controller.app.campaigninfo.vo.CampaignNumberJudgeVO;
import co.yixiang.yshop.module.product.controller.app.campaigninfo.vo.CampaignProductReqVO;
import co.yixiang.yshop.module.product.controller.app.campaigninfo.vo.CampaignProductRespVO;
import co.yixiang.yshop.module.product.controller.app.campaigninfo.vo.CampaignSkuVO;
import co.yixiang.yshop.module.product.dal.mysql.campaigninfo.CampaignInfoMapper;
import co.yixiang.yshop.module.product.enums.common.PageTypeEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.product.enums.ErrorCodeConstants.CAMPAIGN_NUMBER_ERROR;
import static co.yixiang.yshop.module.product.enums.ErrorCodeConstants.CAMPAIGN_OUT_OF_STOCK_ERROR;


/**
 * 活动信息 APP Service 实现类
 *
 * @author moxiangrong
 */
@Service
@Validated
@Slf4j
public class AppCampaignInfoServiceImpl implements AppCampaignInfoService {

    @Resource
    private CampaignInfoMapper campaignInfoMapper;


    @Override
    public PageResult<CampaignProductRespVO> getCampaignProductPage(CampaignProductReqVO reqVO) {
        // 判断是否分页
        if (PageTypeEnum.NOT_PAGE.getValue().equals(reqVO.getIsPage())) reqVO.setPageSize(Integer.MAX_VALUE);
        Page<CampaignProductRespVO> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
        List<CampaignProductRespVO> list = campaignInfoMapper.getCampaignProductPage(page, reqVO);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<CampaignSkuVO> getCampaignsByProductAttrUniques(List<String> productAttrUniques) {
        return campaignInfoMapper.getCampaignsByProductAttrUniques(productAttrUniques);
    }

    @Override
    public void numberJudge(CampaignNumberJudgeVO vo) {
        if (campaignInfoMapper.stockJudge(vo) < 0) throw exception(CAMPAIGN_OUT_OF_STOCK_ERROR);
        Integer number = campaignInfoMapper.numberJudge(vo);
        if (ObjectUtil.isNotNull(number) && number - vo.getNumber() < 0) {
            throw exception(CAMPAIGN_NUMBER_ERROR);
        }
    }

    @Override
    public void deStock(String productAttrUnique, Integer number) {
        campaignInfoMapper.deStock(productAttrUnique, number);
    }

    @Override
    public void backStock(String productAttrUnique, Integer number) {
        campaignInfoMapper.deStock(productAttrUnique, -number);
    }

}
