package com.ruoyi.ss.vip.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ss.vip.service.VipValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ss.vip.mapper.VipMapper;
import com.ruoyi.ss.vip.domain.Vip;
import com.ruoyi.ss.vip.domain.VipVO;
import com.ruoyi.ss.vip.domain.VipQuery;
import com.ruoyi.ss.vip.service.VipService;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 会员Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-09
 */
@Service
public class VipServiceImpl implements VipService
{
    @Autowired
    private VipMapper vipMapper;

    @Autowired
    private VipValidator vipValidator;
    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 查询会员
     *
     * @param id 会员主键
     * @return 会员
     */
    @Override
    public VipVO selectVipById(Long id)
    {
        return vipMapper.selectVipById(id);
    }

    /**
     * 查询会员列表
     *
     * @param vip 会员
     * @return 会员
     */
    @Override
    public List<VipVO> selectVipList(VipQuery vip)
    {
        return vipMapper.selectVipList(vip);
    }

    /**
     * 新增会员
     *
     * @param vip 会员
     * @return 结果
     */
    @Override
    public int insertVip(Vip vip) {
        vipValidator.beforeCheck(vip);

        vip.setCreateTime(DateUtils.getNowDate());

        Integer result = transactionTemplate.execute(status -> {
            int insert = vipMapper.insertVip(vip);

            if (insert == 1) {
                VipVO vo = this.selectVipById(vip.getId());
                vipValidator.afterCheck(vo);
            }

            return insert;
        });

        return result == null ? 0 : result;
    }

    /**
     * 修改会员
     *
     * @param vip 会员
     * @return 结果
     */
    @Override
    public int updateVip(Vip vip) {
        vipValidator.beforeCheck(vip);

        Integer result = transactionTemplate.execute(status -> {
            int update = vipMapper.updateVip(vip);

            if (update == 1) {
                VipVO vo = this.selectVipById(vip.getId());
                vipValidator.afterCheck(vo);
            }

            return update;
        });

        return result == null ? 0 : result;
    }

    /**
     * 批量删除会员
     *
     * @param ids 需要删除的会员主键
     * @return 结果
     */
    @Override
    public int deleteVipByIds(Long[] ids) {
        return vipMapper.deleteVipByIds(ids);
    }

    /**
     * 删除会员信息
     *
     * @param id 会员主键
     * @return 结果
     */
    @Override
    public int deleteVipById(Long id)
    {
        return vipMapper.deleteVipById(id);
    }

    @Override
    public int selectCount(VipQuery query) {
        return vipMapper.selectCount(query);
    }
}
