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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.MemberFieldConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.domain.member.detail.CuMemberAwards;
import com.hzs.common.domain.member.detail.ext.CuMemberAwardsExt;
import com.hzs.common.domain.member.ext.CuMemberSettleExt;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.member.achieve.service.ICuMemberTreeService;
import com.hzs.member.detail.mapper.CuMemberAwardsMapper;
import com.hzs.member.detail.service.ICuMemberAwardsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 会员信息-奖衔升级记录 服务实现类
 */
@Service
public class CuMemberAwardsServiceImpl extends ServiceImpl<CuMemberAwardsMapper, CuMemberAwards> implements ICuMemberAwardsService {

    @Autowired
    private ICuMemberTreeService iCuMemberTreeService;

    @Override
    public void deleteCuMemberAwards(Long pkOrder, Long pkApprove, Date currentDateTime) {
        LambdaUpdateWrapper<CuMemberAwards> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CuMemberAwards::getDelFlag, EYesNo.NO.getIntValue());
        updateWrapper.set(CuMemberAwards::getPkModified, pkApprove);
        updateWrapper.set(CuMemberAwards::getModifiedTime, currentDateTime);
        updateWrapper.eq(CuMemberAwards::getPkOrder, pkOrder);
        update(updateWrapper);
    }

    /**
     * 更新奖衔记录
     *
     * @param enoughAwardsMemberList    满足业绩
     * @param originalCuMemberSettleMap 原来的map
     * @param period                    期间
     */
    private List<CuMemberAwards> updateAwardsRecord(List<CuMemberSettleExt> enoughAwardsMemberList, Map<Long, CuMemberSettleExt> originalCuMemberSettleMap,
                                                    Integer period) {
        if (enoughAwardsMemberList.size() == 0) {
            return null;
        }
        // 更新奖衔记录变动
        // 增加奖衔记录表
        // 更新升奖衔的会员，插入升衔记录
        return upgradeCuMemberAwards(enoughAwardsMemberList, originalCuMemberSettleMap, period);

    }

    /**
     * 插入升级记录
     *
     * @param enoughAwardsMemberList    足够升级的
     * @param originalCuMemberSettleMap 记录会员原等级的map
     * @param period                    期间
     */
    private List<CuMemberAwards> upgradeCuMemberAwards(List<CuMemberSettleExt> enoughAwardsMemberList, Map<Long, CuMemberSettleExt> originalCuMemberSettleMap,
                                                       Integer period) {
        List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
        if (enoughAwardsMemberList.size() > 0) {
            // 记录要入库的，为了验证是否首次晋升
            enoughAwardsMemberList.forEach(enoughAwardsMember -> getCuMemberAwards(originalCuMemberSettleMap, period, cuMemberAwardsList, enoughAwardsMember));
            // 验证满足的这群人是否是首次晋升，查询出值的不是首次晋升
            List<CuMemberAwards> originalCuMemberAwardsList = baseMapper.queryLastCuMemberAwards(cuMemberAwardsList);
            // 是首次晋升的数据
            Map<Long, CuMemberAwards> cuMemberAwardsMap = new HashMap<>(ComputeUtil.mapInitCapacity(originalCuMemberAwardsList.size()));
            originalCuMemberAwardsList.forEach(cuMemberAwards -> cuMemberAwardsMap.put(cuMemberAwards.getPkMember(), cuMemberAwards));
            cuMemberAwardsList.forEach(cuMemberAwards -> {
                CuMemberAwards memberAwards = cuMemberAwardsMap.get(cuMemberAwards.getPkMember());
                // 没有奖衔升级记录或者奖衔升级记录是会员的 算首次晋升
                if (memberAwards == null || memberAwards.getNewLevel() == EAwards.MEMBER.getValue()) {
                    cuMemberAwards.setPurchaseStatus(EYesNo.YES.getIntValue());
                }
            });
            // 插入记录
            baseMapper.saveBatchCuMemberAwards(cuMemberAwardsList);
        }
        return cuMemberAwardsList;
    }

    private void getCuMemberAwards(Map<Long, CuMemberSettleExt> originalCuMemberSettleMap, Integer period, List<CuMemberAwards> cuMemberAwardsList, CuMemberSettleExt enoughAwardsMember) {
        CuMemberAwards cuMemberAwards = CuMemberAwards.builder()
                .pkMember(enoughAwardsMember.getPkMember())
                .period(period)
                .upType(EUpgradeType.AUTO_UPGRADE.getValue())
                // 原等级
                .oldLevel(originalCuMemberSettleMap.get(enoughAwardsMember.getPkMember()).getPkOriAwards())
                .newLevel(enoughAwardsMember.getPkAwards())
                // 默认不免考
                .purchaseStatus(EYesNo.NO.getIntValue())
                .build();
        cuMemberAwards.setPkCreator(MagicNumberConstants.PK_ADMIN);
        cuMemberAwards.setPkCountry(enoughAwardsMember.getPkSettleCountry());
        cuMemberAwardsList.add(cuMemberAwards);
    }

    /**
     * 更新降衔的会员，把升衔记录删除
     *
     * @param period             期间
     * @param changeAwardsList   降低奖衔的人
     * @param cuMemberAwardsList 所有变动记录的数据
     */
    private void reduceCuMemberAwards(List<CuMemberAwards> changeAwardsList, Integer period, List<CuMemberAwards> cuMemberAwardsList) {
        // 验证是否有降奖衔的，降奖衔的也要更新
        if (changeAwardsList.size() > 0) {
            // 更新奖衔表，将奖衔升级记录修改为删除状态
            QueryWrapper<CuMemberAwards> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(MemberFieldConstants.PERIOD, period);
            baseMapper.updateBatchCuMemberAwards(changeAwardsList, period);
            // 根据 changeAwardsList 查找到这群人的历史奖衔升级记录
            List<CuMemberAwards> hisCuMemberAwardsList = baseMapper.queryLastCuMemberAwards(changeAwardsList);
            Map<Long, CuMemberAwards> cuMemberAwardsMap = new HashMap<>();
            hisCuMemberAwardsList.forEach(cuMemberAwards -> cuMemberAwardsMap.put(cuMemberAwards.getPkMember(), cuMemberAwards));
            // 用于更新网体，将原有奖衔还原
            changeAwardsList.forEach(cuMemberAwards -> {
                if (cuMemberAwardsMap.containsKey(cuMemberAwards.getPkMember())) {
                    // 原有奖衔
                    cuMemberAwards.setNewLevel(cuMemberAwardsMap.get(cuMemberAwards.getPkMember()).getNewLevel());
                } else {
                    // 没有值的变为会员
                    cuMemberAwards.setNewLevel(EAwards.MEMBER.getValue());
                }
            });
            cuMemberAwardsList.addAll(changeAwardsList);
        }
    }

    /**
     * 查询某一期变动的奖衔
     *
     * @param period 奖金期
     */
    private List<CuMemberAwards> queryCuMemberAwardsByPeriod(Integer period) {
        QueryWrapper<CuMemberAwards> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(MemberFieldConstants.PERIOD, period);
        queryWrapper.eq(MemberFieldConstants.UP_TYPE, EUpgradeType.AUTO_UPGRADE.getValue());
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 验证血缘关系
     *
     * @param settleTableName   结算表
     * @param cuMemberSettleExt 会员结算表
     * @param bdAwards          等级
     */
    private Boolean validateBloodRelation(String settleTableName, CuMemberSettleExt cuMemberSettleExt, BdAwards bdAwards) {
        // 左区满足，且满足血缘
        if (iCuMemberTreeService.queryCuMemberSettlePlaceUnderUmbrella(settleTableName, bdAwards.getPkCheckAwardsLeft(), EPlaceDept.LEFT_DEPT.getValue(), cuMemberSettleExt.getPkMember()) &&
                iCuMemberTreeService.queryCuMemberSettleBloodUnderUmbrella(settleTableName, bdAwards.getPkCheckAwardsLeft(), EPlaceDept.LEFT_DEPT.getValue(), cuMemberSettleExt.getPkMember())) {
            // 验证血缘，左区存在血缘关系的
            // 右区满足，且满足血缘
            // 进行验证血缘验证
            return iCuMemberTreeService.queryCuMemberSettlePlaceUnderUmbrella(settleTableName, bdAwards.getPkCheckAwardsRight(), EPlaceDept.RIGHT_DEPT.getValue(), cuMemberSettleExt.getPkMember()) &&
                    iCuMemberTreeService.queryCuMemberSettleBloodUnderUmbrella(settleTableName, bdAwards.getPkCheckAwardsRight(), EPlaceDept.RIGHT_DEPT.getValue(), cuMemberSettleExt.getPkMember());
        }
        return false;
    }

    /**
     * 验证左右区安置关系
     *
     * @param settleTableName 结算表
     * @param bdAwards        等级
     * @param pkMember        会员
     */
    private Boolean validateCuMemberPlaceRelation(String settleTableName, BdAwards bdAwards, Long pkMember) {
        // 验证左区
        if (iCuMemberTreeService.queryCuMemberSettlePlaceUnderUmbrella(settleTableName, bdAwards.getPkCheckAwardsLeft(), EPlaceDept.LEFT_DEPT.getValue(), pkMember)) {
            // 在验证右区
            return iCuMemberTreeService.queryCuMemberSettlePlaceUnderUmbrella(settleTableName, bdAwards.getPkCheckAwardsRight(), EPlaceDept.RIGHT_DEPT.getValue(), pkMember);
        }
        return false;
    }

    @Override
    public CuMemberAwardsExt queryLastManualAwards(Long pkMember) {
        return baseMapper.queryLastManualAwards(pkMember);
    }

}
