package com.xinelu.quartz.service.impl;

import com.xinelu.common.enums.CouponUseStatusEnum;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.manage.domain.patientcouponreceive.PatientCouponReceive;
import com.xinelu.manage.mapper.patientcouponreceive.PatientCouponReceiveMapper;
import com.xinelu.quartz.service.CouponTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author 纪寒
 * @Date 2023-02-28 14:59:01
 * @Version 1.0
 */
@Service
@Slf4j
public class CouponTaskServiceImpl implements CouponTaskService {

    @Resource(name = "transactionManager")
    private DataSourceTransactionManager transactionManager;
    @Resource
    private PatientCouponReceiveMapper patientCouponReceiveMapper;

    /**
     * 自动修改会员领取已过期的优惠券状态，第二天凌晨12点半执行一次
     */
    @Override
    public void patientCouponReceiveStatusTask() {
        log.info("开始执行修改会员领取已过期的优惠券状态定时任务......");
        LocalDateTime timePrevious = LocalDateTime.now();
        List<PatientCouponReceive> patientCouponReceiveList = patientCouponReceiveMapper.getPatientCouponExpirationEndTime(timePrevious, CouponUseStatusEnum.EXPIRED.getInfo());
        if (CollectionUtils.isEmpty(patientCouponReceiveList)) {
            return;
        }
        TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            List<Long> idList = patientCouponReceiveList.stream().filter(item -> Objects.nonNull(item.getId())).map(PatientCouponReceive::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(idList)) {
                int insertCount = patientCouponReceiveMapper.updateCouponReceiveStatus(CouponUseStatusEnum.EXPIRED.getInfo(), idList);
                if (insertCount <= 0) {
                    throw new ServiceException("更新修改券状态失败！");
                }
            }
            transactionManager.commit(transactionStatus);
            log.info("完成修改会员领取已过期的优惠券状态定时任务......");
        } catch (Exception e) {
            log.error("修改会员领取已过期的优惠券状态定时任务失败，失败原因为 =====> {}", e.getMessage());
            transactionManager.rollback(transactionStatus);
            throw e;
        }
    }
}
