package com.hzs.bonus.achieve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.bonus.achieve.mapper.CuMemberMonthPeriodMapper;
import com.hzs.bonus.achieve.service.ICuMemberMonthPeriodService;
import com.hzs.bonus.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.member.achieve.CuMemberMonthPeriod;
import com.hzs.common.domain.member.achieve.CuMemberSettlePeriod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * <p>
 * 会员月结算期间 服务实现类
 * </p>
 *
 * @author hzs
 * @since 2023-10-11
 */
@Service
public class CuMemberMonthPeriodServiceImpl extends ServiceImpl<CuMemberMonthPeriodMapper, CuMemberMonthPeriod> implements ICuMemberMonthPeriodService {

    @Autowired
    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;

    @Override
    public CuMemberMonthPeriod queryMemberMonthPeriod(Integer period) {
        QueryWrapper<CuMemberMonthPeriod> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("START_PERIOD", period);
        queryWrapper.ge("END_PERIOD", period);
        CuMemberMonthPeriod cuMemberMonthPeriod = baseMapper.selectOne(queryWrapper);
        if(cuMemberMonthPeriod == null){
            queryWrapper = new QueryWrapper<>();
            queryWrapper.select("max(END_PERIOD) END_PERIOD");
            CuMemberMonthPeriod maxMonthPeriod = baseMapper.selectOne(queryWrapper);
            CuMemberSettlePeriod cuMemberSettlePkPeriod = cuMemberSettlePeriodService.getCuMemberSettlePkPeriod(maxMonthPeriod.getEndPeriod());
            Date startDate = DateUtils.afterDate(1, ChronoUnit.DAYS, cuMemberSettlePkPeriod.getSettleDate());
            Date endDate = DateUtils.afterDate(28, ChronoUnit.DAYS, cuMemberSettlePkPeriod.getSettleDate());
            CuMemberSettlePeriod startPeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD, startDate));
            CuMemberSettlePeriod endPeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD, endDate));
            cuMemberMonthPeriod = CuMemberMonthPeriod.builder()
                    .startPeriod(startPeriod.getPkId())
                    .endPeriod(endPeriod.getPkId())
                    .build();
            cuMemberMonthPeriod.setPkCreator(MagicNumberConstants.PK_ADMIN);
            save(cuMemberMonthPeriod);
        }
        return cuMemberMonthPeriod;
    }
}
