package com.ruoyi.system.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.domain.CouponUser;
import com.ruoyi.system.mapper.CouponsMapper;
import com.ruoyi.system.domain.Coupons;
import com.ruoyi.system.service.ICouponsService;

/**
 * 优惠券Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-16
 */
@Service
public class CouponsServiceImpl implements ICouponsService
{
    @Autowired
    private CouponsMapper couponsMapper;

    /**
     * 查询优惠券
     *
     * @param id 优惠券主键
     * @return 优惠券
     */
    @Override
    public Coupons selectCouponsById(Long id)
    {
        return couponsMapper.selectCouponsById(id);
    }

    /**
     * 查询优惠券列表
     *
     * @param coupons 优惠券
     * @return 优惠券
     */
    @Override
    public List<Coupons> selectCouponsList(Coupons coupons)
    {
        return couponsMapper.selectCouponsList(coupons);
    }

    /**
     * 新增优惠券
     *
     * @param coupons 优惠券
     * @return 结果
     */
    @Transactional
    @Override
    public int insertCoupons(Coupons coupons)
    {
        int rows = couponsMapper.insertCoupons(coupons);
        insertCouponUser(coupons);
        return rows;
    }

    /**
     * 修改优惠券
     *
     * @param coupons 优惠券
     * @return 结果
     */
    @Transactional
    @Override
    public int updateCoupons(Coupons coupons)
    {
        couponsMapper.deleteCouponUserByCouponId(coupons.getId());
        insertCouponUser(coupons);
        return couponsMapper.updateCoupons(coupons);
    }

    /**
     * 批量删除优惠券
     *
     * @param ids 需要删除的优惠券主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteCouponsByIds(Long[] ids)
    {
        couponsMapper.deleteCouponUserByCouponIds(ids);
        return couponsMapper.deleteCouponsByIds(ids);
    }

    /**
     * 删除优惠券信息
     *
     * @param id 优惠券主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteCouponsById(Long id)
    {
        couponsMapper.deleteCouponUserByCouponId(id);
        return couponsMapper.deleteCouponsById(id);
    }

    /**
     * 新增优惠券领取记录信息
     *
     * @param coupons 优惠券对象
     */
    public void insertCouponUser(Coupons coupons)
    {
        List<CouponUser> couponUserList = coupons.getCouponUserList();
        Long id = coupons.getId();
        if (StringUtils.isNotNull(couponUserList))
        {
            List<CouponUser> list = new ArrayList<CouponUser>();
            for (CouponUser couponUser : couponUserList)
            {
                couponUser.setCouponId(id);
                list.add(couponUser);
            }
            if (list.size() > 0)
            {
                couponsMapper.batchCouponUser(list);
            }
        }
    }
}
