package cn.ysk.cashier.mybatis.service.impl;

import cn.ysk.cashier.mybatis.entity.TbActivate;
import cn.ysk.cashier.mybatis.entity.TbShopCoupon;
import cn.ysk.cashier.mybatis.mapper.TbActivateMapper;
import cn.ysk.cashier.mybatis.service.TbActivateService;
import cn.ysk.cashier.mybatis.service.TbShopCouponService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 * @description 针对表【tb_activate】的数据库操作Service实现
 * @createDate 2024-09-03 14:08:30
 */
@Service
public class TbActivateServiceImpl extends ServiceImpl<TbActivateMapper, TbActivate> implements TbActivateService {

    @Autowired
    private TbActivateMapper activateMapper;
    @Autowired
    private TbShopCouponService tbShopCouponService;

    @Override
    public Object findActivate(String shopId) {
        QueryWrapper<TbActivate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", shopId);
        queryWrapper.orderByDesc("id");
        List<TbActivate> list = activateMapper.selectList(queryWrapper);
        for (TbActivate tbActivate : list) {
            if (tbActivate.getCouponId() != null) {
                TbShopCoupon coupon = tbShopCouponService.findById(tbActivate.getCouponId());
                tbActivate.setCouponName(coupon != null ? coupon.getTitle() : "");
            }
        }
        return list;
    }

    @Override
    public void modifyActivate(TbActivate activate) {
        if (Objects.nonNull(activate.getId()) && activate.getId() > 0) {
            if(activate.getIsUseCoupon()==0){
                activate.setCouponId(null);
            } else if (activate.getIsUseCoupon()==1) {
                if (activate.getCouponId() == null) {
                    throw new RuntimeException("优惠券不能为空");
                }
            }
            activateMapper.updateById(activate);
        } else {
            if(activate.getIsUseCoupon()==0){
                activate.setCouponId(null);
            } else if (activate.getIsUseCoupon()==1) {
                if (activate.getCouponId() == null) {
                    throw new RuntimeException("优惠券不能为空");
                }
            }
            activateMapper.insert(activate);
        }
    }
}




