package com.hfkj.service.discount.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.dao.BsDiscountUseMerMapper;
import com.hfkj.entity.BsDiscount;
import com.hfkj.entity.BsDiscountUseMer;
import com.hfkj.entity.BsDiscountUseMerExample;
import com.hfkj.service.discount.BsDiscountService;
import com.hfkj.service.discount.BsDiscountUseMerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @className: BsDiscountUseMerServiceImpl
 * @author: HuRui
 * @date: 2024/8/30
 **/
@Service("discountUseMerService")
public class BsDiscountUseMerServiceImpl implements BsDiscountUseMerService {
    @Resource
    private BsDiscountUseMerMapper discountUseMerMapper;
    @Resource
    private BsDiscountService discountService;
    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void configUseMer(String discountNo, List<String> merNoList) {
        BsDiscount discount = discountService.getDetail(discountNo);
        if (discount == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知优惠券");
        }
        // 删除
        BsDiscountUseMerExample example = new BsDiscountUseMerExample();
        example.createCriteria().andDiscountNoEqualTo(discountNo);
        discountUseMerMapper.deleteByExample(example);
        // 重新添加数据
        discountUseMerMapper.insertUseMer(discount.getId(), discountNo, merNoList);
    }

    @Override
    public BsDiscountUseMer getDetail(String discountNo, String merNo) {
        BsDiscountUseMerExample example = new BsDiscountUseMerExample();
        example.createCriteria().andDiscountNoEqualTo(discountNo).andMerNoEqualTo(merNo);
        List<BsDiscountUseMer> list = discountUseMerMapper.selectByExample(example);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<BsDiscountUseMer> getList(String discountNo) {
        BsDiscountUseMerExample example = new BsDiscountUseMerExample();
        example.createCriteria().andDiscountNoEqualTo(discountNo);
        return discountUseMerMapper.selectByExample(example);
    }
}
