package com.sqx.modules.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.modules.member.dao.VipPromoRecordDao;
import com.sqx.modules.member.dto.VipPromoRecordDTO;
import com.sqx.modules.member.entity.VipPromoCode;
import com.sqx.modules.member.entity.VipPromoRecord;
import com.sqx.modules.member.query.VipPromoRecordQuery;
import com.sqx.modules.member.service.VipPromoCodeService;
import com.sqx.modules.member.service.VipPromoRecordService;
import com.sqx.modules.member.vo.VipPromoRecordVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class VipPromoRecordServiceImpl extends ServiceImpl<VipPromoRecordDao, VipPromoRecord> implements VipPromoRecordService {

    private final VipPromoCodeService vipPromoCodeService;

    @Override
    public PageUtils pages(VipPromoRecordQuery query) {
        IPage<VipPromoRecordVO> pages = baseMapper.pages(new Page<>(query.getPage(), query.getLimit()), query);

        return new PageUtils(pages);
    }

    @Override
    @Transactional
    public void add(VipPromoRecordDTO recordDTO) {
        VipPromoRecord record = new VipPromoRecord();
        BeanUtil.copyProperties(recordDTO, record);

        record.setCreateTime(new Date());
        if (StrUtil.isNotBlank(recordDTO.getPromoCode())) {
            VipPromoCode promoCode = vipPromoCodeService.getByCode(recordDTO.getPromoCode());
            if (ObjectUtil.isNotNull(promoCode)) {
                record.setPromoCodeId(promoCode.getId());

                vipPromoCodeService.increasePromoCount(promoCode.getId());
            }
        }

        save(record);
    }
}
