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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.bonus.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.bonus.achieve.service.ICuMemberTreeService;
import com.hzs.bonus.base.service.ICuMemberService;
import com.hzs.bonus.detail.mapper.CuMemberLevelMapper;
import com.hzs.bonus.detail.service.ICuMemberLevelService;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.enums.EGrade;
import com.hzs.common.core.enums.EUpgradeType;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.member.detail.CuMemberLevel;
import com.hzs.common.domain.member.ext.CuMemberSettleExt;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员信息-等级升级记录 服务实现类
 *
 * @author hzs
 * @since 2022-10-11
 */
@Service
public class CuMemberLevelServiceImpl extends ServiceImpl<CuMemberLevelMapper, CuMemberLevel> implements ICuMemberLevelService {

//    @Autowired
//    private ICuMemberTreeService iCuMemberTreeService;
//    @Autowired
//    private ICuMemberService iCuMemberService;
//    @Autowired
//    private ICuMemberSettlePeriodService iCuMemberSettlePeriodService;
//
//    @DubboReference
//    IGradeServiceApi iGradeServiceApi;
//
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void calculateCuMemberGrade(String settleDateStr, String settleTableName) {
//        List<GradeDTO> gradeList = iGradeServiceApi.queryGradeList(CountryConstants.CHINA_COUNTRY).getData();
//        // 等级列表（V3，V4）
//        gradeList = gradeList.stream()
//                .filter(tmp -> EGrade.VIP.getValue() == tmp.getGradeValue() || EGrade.S_VIP.getValue() == tmp.getGradeValue())
////                .sorted(Comparator.comparingInt(GradeDTO::getGradeValue).reversed())
//                .collect(Collectors.toList());
//
//        // 查询结算日当天奖衔发生过变动的会员，本期
//        Date settleDate = DateUtils.parseStringToDate(settleDateStr);
//        Integer period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(settleDateStr).getPkId();
//
//        // 查询出需要升级的会员信息
//        List<CuMemberLevel> cuMemberLevelList = queryCuMemberGradeByPeriod(period);
//        // 回退会员等级（日结表）
//        iCuMemberTreeService.updateBackCuMemberSettleGrade(settleTableName, period);
//        // 更新会员等级根据临时表（会员表）
//        iCuMemberService.updateBackCuMemberGrade(cuMemberLevelList, period);
//        // 删除会员等级升级记录
//        baseMapper.deleteCuMemberGrade(period);
//
//        // 会员升级记录
//        List<CuMemberLevel> memberLevelList = new ArrayList<>();
//        for (GradeDTO gradeDTO : gradeList) {
//            // 处理可以升级V3、V4会员
//            List<CuMemberLevel> tmpCuMemberLevelList = this.calculateGrade(gradeDTO, settleTableName, settleDate, period);
//            if (null != tmpCuMemberLevelList) {
//                memberLevelList.addAll(tmpCuMemberLevelList);
//            }
//        }
//        if (CollectionUtil.isNotEmpty(memberLevelList)) {
//            // 更新会员表（会员等级、注册权限）
//            iCuMemberService.updateCuMemberLevelByPeriod(period);
//            // 更新结算网体表 -- 结算日期到当前日期的所有日结算表
//            updateMemberLevelPeriod(settleDate);
//        }
//    }
//
//    private void updateMemberLevelPeriod(Date settleDate) {
//        Date currentDate = DateUtils.currentDate();
//        List<Integer> periodList = new ArrayList<>();
//        while (DateUtils.compareDateBefore(settleDate, currentDate)) {
//            String settleDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, settleDate);
//            periodList.add(iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(settleDateStr).getPkId());
//            settleDate = DateUtils.afterDate(1, ChronoUnit.DAYS, settleDate);
//        }
//        iCuMemberTreeService.updateCuMemberSettleGradeByPeriod(periodList);
//    }
//
//    /**
//     * 查询某一期变动的等级
//     */
//    private List<CuMemberLevel> queryCuMemberGradeByPeriod(Integer period) {
//        LambdaQueryWrapper<CuMemberLevel> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(CuMemberLevel::getPeriod, period);
//        queryWrapper.eq(CuMemberLevel::getUpType, EUpgradeType.AUTO_UPGRADE.getValue());
//        queryWrapper.orderByDesc(CuMemberLevel::getPkId);
//        return baseMapper.selectList(queryWrapper);
//    }
//
//    private void getCuMemberLevel(CuMemberSettleExt cuMemberSettleExt, Integer period, Date settleDate,
//                                  List<CuMemberLevel> cuMemberLevelList, GradeDTO gradeDTO) {
//        CuMemberLevel cuMemberLevel = CuMemberLevel.builder()
//                .pkMember(cuMemberSettleExt.getPkMember())
//                .period(period)
//                .upType(EUpgradeType.AUTO_UPGRADE.getValue())
//                // 原等级
//                .oldLevel(cuMemberSettleExt.getPkGrade())
//                // 新等级
//                .newLevel(gradeDTO.getPkId())
//                .upgradeTime(settleDate)
//                .build();
//        cuMemberLevel.setPkCreator(MagicNumberConstants.PK_ADMIN);
//        cuMemberLevel.setPkCountry(cuMemberSettleExt.getPkSettleCountry());
//        cuMemberLevelList.add(cuMemberLevel);
//    }

}
