package cn.wisenergy.service.app.impl;

import cn.wisenergy.mapper.RecommendUserMapper;
import cn.wisenergy.mapper.TeamUserInfoMapper;
import cn.wisenergy.mapper.UsersMapper;
import cn.wisenergy.model.app.RecommendUser;
import cn.wisenergy.model.app.TeamUserInfo;
import cn.wisenergy.model.app.User;
import cn.wisenergy.service.app.AerialDeliveryUserService;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.pqc.crypto.newhope.NHOtherInfoGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class AerialDeliveryUserServiceImpl implements AerialDeliveryUserService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RecommendUserMapper recommendUserMapper;

    @Autowired
    private TeamUserInfoMapper teamUserInfoMapper;

    @Autowired
    UserLevelServiceImpl userLevelService;

    /**
     * 空投池中用户随机分配任意邀请人
     * 定时任务（日任务）
     * 随机分配条件（ 1：当前用户的推荐人邀请码是 “1”
     *              2： 且当前用户的注册时间是一个月前）
     * 随机邀请人要求 1:注册时间早于当前用户
     *
     */
//    @XxlJob()
    @Override
    public void aerialDeliveryUserRand(){
        log.info("shop-mall[]UserServiceImpl[]aerialDeliveryUserRand[]");
        log.info("--------------------------空投池用户随机分派开始执行---------------------------------");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH,-1);
        Date time = calendar.getTime();
        String before = sdf.format(time);
        String now = sdf.format(date);
        log.info("当前时间："+now+"-----"+"向前一个月的具体时间:"+before);
        //1、查询空头池中注册时间是一个月以前的所有用户（即推荐人邀请码为 “1” 的用户）
        List<User> aerialDeliveryUserList = usersMapper.getAerialDeliveryUserBeforOneMonth(before,now);
        if (aerialDeliveryUserList.size()>0){
            for (User user : aerialDeliveryUserList) {
                Integer id = user.getId();
                String userId = user.getUserId();
                log.info("当前用户id--------------"+userId);
                //2、随机获取比当前用户早注册的用户
                User randUser = usersMapper.randOneGetUserByUserId(id);
                String randUserId = randUser.getUserId();
                //2.1、随机用户的邀请码
                String inviteCode = randUser.getInviteCode();
                //2.2、设置当前用户的推荐人邀请码为 随机用户的inviteCode
                user.setBeInvitedCode(inviteCode);
                usersMapper.edit(user);
                userSetBeinviteCode(userId,randUserId);
            }
        }

        log.info("--------------------------空投池用户随机分派开始执行完成---------------------------------");
    }

    @Override
    public void userSetBeinviteCode(String userId, String userInvitedId){
        //3、上级用户的直推表数据维护
        recommendInfoDataPreserve(userId,userInvitedId);
        //4、用户的团队表数据维护
        Map<String, Integer> teamDataMap = teamUserInfoByAerialDelivery(userInvitedId, userId);
        //4.1获取当前团队中最上级的用户对象
        User highUser = highUser(userId);
        if (null != highUser){
            //4.2 最上级用户id
            String highUserId = highUser.getUserId();
            //4.1整体团队数据维护
            teamData(teamDataMap, highUserId);
        }
        //5、查看当前用户是否要进行升级
        userLevelService.userLevelUpgrade(userInvitedId);
    }

    /**
     * 直推数据维护
     * @param userId  当前用户id
     * @param beInvitedCodeUserId  推荐人id
     */
    public void recommendInfoDataPreserve(String userId,String beInvitedCodeUserId){
        User byUserId = usersMapper.getByUserId(userId);
        int userLevel = byUserId.getUserLevel();
        RecommendUser recommendUserMapperByRandUser = recommendUserMapper.getByUserId(beInvitedCodeUserId);
        if (userLevel == 0){
            //普通用户数量 + 1
            Integer normalUserNum = recommendUserMapperByRandUser.getNormalUserNum();
            recommendUserMapperByRandUser.setNormalUserNum(normalUserNum +1);
            recommendUserMapper.updateById(recommendUserMapperByRandUser);
        }else if (userLevel == 1){
            //幼苗用户数量  + 1
            Integer seedlingNum = recommendUserMapperByRandUser.getSeedlingNum();
            recommendUserMapperByRandUser.setSeedlingNum(seedlingNum + 1);
            recommendUserMapper.updateById(recommendUserMapperByRandUser);
        }else if (userLevel == 2){
            //青铜用户数量  + 1
            Integer bronzeTreeNum = recommendUserMapperByRandUser.getBronzeTreeNum();
            recommendUserMapperByRandUser.setBronzeTreeNum(bronzeTreeNum + 1 );
            recommendUserMapper.updateById(recommendUserMapperByRandUser);
        }else if (userLevel == 3){
            //白银用户数量  + 1
            Integer silverTreeNum = recommendUserMapperByRandUser.getSilverTreeNum();
            recommendUserMapperByRandUser.setSilverTreeNum(silverTreeNum + 1 );
            recommendUserMapper.updateById(recommendUserMapperByRandUser);
        }else if (userLevel == 4){
            //黄金用户数量  + 1
            Integer goldTreeNum = recommendUserMapperByRandUser.getGoldTreeNum();
            recommendUserMapperByRandUser.setGoldTreeNum(goldTreeNum + 1);
            recommendUserMapper.updateById(recommendUserMapperByRandUser);
        }else if (userLevel == 5){
            //农场主用户数量  + 1
            Integer farmerNum = recommendUserMapperByRandUser.getFarmerNum();
            recommendUserMapperByRandUser.setFarmerNum(farmerNum + 1);
            recommendUserMapper.updateById(recommendUserMapperByRandUser);
        }else if (userLevel == 6){
            //森林之星用户数量  + 1
            Integer forestStartNum = recommendUserMapperByRandUser.getForestStartNum();
            recommendUserMapperByRandUser.setForestStartNum(forestStartNum + 1);
            recommendUserMapper.updateById(recommendUserMapperByRandUser);
        }else if (userLevel == 7){
            //西田森合伙人用户数量  + 1
            Integer partnerNum = recommendUserMapperByRandUser.getPartnerNum();
            recommendUserMapperByRandUser.setFarmerNum(partnerNum + 1);
            recommendUserMapper.updateById(recommendUserMapperByRandUser);
        }
    }

    /**
     * 团队数据维护
     * @param beInvitedUserId 推荐人userId
     * @param userId 当前用户的userId
     */
    public Map<String, Integer> teamUserInfoByAerialDelivery(String beInvitedUserId, String userId) {
        TeamUserInfo teamUserInfoByIntvitedUser = teamUserInfoMapper.getByUserId(beInvitedUserId);
        TeamUserInfo teamUserInfoByUserId = teamUserInfoMapper.getByUserId(userId);
        Map<String, Integer> teamDataMap = new ConcurrentHashMap<String, Integer>();
        if (null != teamUserInfoByUserId){

            //1、当前用户团队中各等级的用户数量
            Integer normalUserNumUser = teamUserInfoByUserId.getNormalUserNum();
            Integer seedlingNumUser = teamUserInfoByUserId.getSeedlingNum();
            Integer bronzeTreeNumUser = teamUserInfoByUserId.getBronzeTreeNum();
            Integer silverTreeNumUser = teamUserInfoByUserId.getSilverTreeNum();
            Integer goldTreeNumUser = teamUserInfoByUserId.getGoldTreeNum();
            Integer farmerNumUser = teamUserInfoByUserId.getFarmerNum();
            Integer forestStartNumUser = teamUserInfoByUserId.getForestStartNum();
            Integer partnerNumUser = teamUserInfoByUserId.getPartnerNum();

            //2、推荐人的团队中各等级的用户数量
            Integer normalUserNumTeamIntvitedUser = teamUserInfoByIntvitedUser.getNormalUserNum();
            Integer seedlingNumIntvitedUser = teamUserInfoByIntvitedUser.getSeedlingNum();
            Integer bronzeTreeNumIntvitedUser = teamUserInfoByIntvitedUser.getBronzeTreeNum();
            Integer silverTreeNumIntvitedUser = teamUserInfoByIntvitedUser.getSilverTreeNum();
            Integer goldTreeNumIntvitedUser = teamUserInfoByIntvitedUser.getGoldTreeNum();
            Integer farmerNumIntvitedUser = teamUserInfoByIntvitedUser.getFarmerNum();
            Integer forestStartNumIntvitedUser = teamUserInfoByIntvitedUser.getForestStartNum();
            Integer partnerNumIntvitedUser = teamUserInfoByIntvitedUser.getPartnerNum();

            //3、最终团队各个等级的人数 推荐人用户本身的数量 + 当前用户的数量
            Integer resultTeamNormalNum = normalUserNumTeamIntvitedUser + normalUserNumUser;
            Integer resultTeamSeedlingNum = seedlingNumIntvitedUser + seedlingNumUser;
            Integer resultTeamBronzeTreeNum = bronzeTreeNumIntvitedUser + bronzeTreeNumUser;
            Integer resultTeamSilverTreeNum = silverTreeNumIntvitedUser + silverTreeNumUser;
            Integer resultTeamGoldTreeNum = goldTreeNumIntvitedUser + goldTreeNumUser;
            Integer resultTeamFarmerNum = farmerNumIntvitedUser + farmerNumUser;
            Integer resultTeamForestStartNum = forestStartNumIntvitedUser + forestStartNumUser;
            Integer resultTeamPartnerNum = partnerNumIntvitedUser + partnerNumUser;

            //3.1、判断当前用户的等级
            User byUserId = usersMapper.getByUserId(userId);
            if (null != byUserId){
                int userLevel = byUserId.getUserLevel();
                if (0 == userLevel){
                    resultTeamNormalNum = resultTeamNormalNum + 1;
                }if (1 == userLevel){
                    resultTeamSeedlingNum = resultTeamSeedlingNum + 1;
                }if (2 == userLevel){
                    resultTeamBronzeTreeNum = resultTeamBronzeTreeNum + 1;
                }if (3 == userLevel){
                    resultTeamSilverTreeNum = resultTeamSilverTreeNum + 1;
                }if (4 == userLevel){
                    resultTeamGoldTreeNum = resultTeamGoldTreeNum + 1;
                }if (5 == userLevel){
                    resultTeamFarmerNum = resultTeamFarmerNum + 1;
                }if (6 == userLevel){
                    resultTeamForestStartNum = resultTeamForestStartNum + 1;
                }if (7 == userLevel){
                    resultTeamPartnerNum = resultTeamPartnerNum + 1;
                }
            }

            teamDataMap.put("resultTeamNormalNum",resultTeamNormalNum);
            teamDataMap.put("resultTeamSeedlingNum",resultTeamSeedlingNum);
            teamDataMap.put("resultTeamBronzeTreeNum",resultTeamBronzeTreeNum);
            teamDataMap.put("resultTeamSilverTreeNum",resultTeamSilverTreeNum);
            teamDataMap.put("resultTeamGoldTreeNum",resultTeamGoldTreeNum);
            teamDataMap.put("resultTeamFarmerNum",resultTeamFarmerNum);
            teamDataMap.put("resultTeamForestStartNum",resultTeamForestStartNum);
            teamDataMap.put("resultTeamPartnerNum",resultTeamPartnerNum);

        }
        return teamDataMap;

    }

    //整体团队数据维护
    public void teamData(Map<String, Integer> teamDataMap, String userId){
        //最上级用户对象
        User user = usersMapper.getByUserId(userId);
        TeamUserInfo teamUserInfoMapperByUserId = teamUserInfoMapper.getByUserId(userId);
        teamUserInfoMapperByUserId.setNormalUserNum(teamDataMap.get("resultTeamNormalNum"));
        teamUserInfoMapperByUserId.setSeedlingNum(teamDataMap.get("resultTeamSeedlingNum"));
        teamUserInfoMapperByUserId.setBronzeTreeNum(teamDataMap.get("resultTeamBronzeTreeNum"));
        teamUserInfoMapperByUserId.setSilverTreeNum(teamDataMap.get("resultTeamSilverTreeNum"));
        teamUserInfoMapperByUserId.setGoldTreeNum(teamDataMap.get("resultTeamGoldTreeNum"));
        teamUserInfoMapperByUserId.setFarmerNum(teamDataMap.get("resultTeamFarmerNum"));
        teamUserInfoMapperByUserId.setForestStartNum(teamDataMap.get("resultTeamForestStartNum"));
        teamUserInfoMapperByUserId.setPartnerNum(teamDataMap.get("resultTeamPartnerNum"));
        teamUserInfoMapper.updateById(teamUserInfoMapperByUserId);
        if (null != user){
            String inviteCode = user.getInviteCode();
            List<User> listUserByBeInvitedCode = usersMapper.getListUserByBeInvitedCode(inviteCode);
            if (listUserByBeInvitedCode.size() >0){
                for (User user1 : listUserByBeInvitedCode) {
                    TeamUserInfo teamUserInfoMapperByUserId1 = teamUserInfoMapper.getByUserId(user1.getUserId());
                    teamUserInfoMapperByUserId1.setNormalUserNum(teamDataMap.get("resultTeamNormalNum"));
                    teamUserInfoMapperByUserId1.setSeedlingNum(teamDataMap.get("resultTeamSeedlingNum"));
                    teamUserInfoMapperByUserId1.setBronzeTreeNum(teamDataMap.get("resultTeamBronzeTreeNum"));
                    teamUserInfoMapperByUserId1.setSilverTreeNum(teamDataMap.get("resultTeamSilverTreeNum"));
                    teamUserInfoMapperByUserId1.setGoldTreeNum(teamDataMap.get("resultTeamGoldTreeNum"));
                    teamUserInfoMapperByUserId1.setFarmerNum(teamDataMap.get("resultTeamFarmerNum"));
                    teamUserInfoMapperByUserId1.setForestStartNum(teamDataMap.get("resultTeamForestStartNum"));
                    teamUserInfoMapperByUserId1.setPartnerNum(teamDataMap.get("resultTeamPartnerNum"));
                    teamUserInfoMapper.updateById(teamUserInfoMapperByUserId1);
                    teamData(teamDataMap, user1.getUserId());
                }
            }
        }
    }

    //查询顶级用户
    public User highUser(String userId) {
        User byUserId = usersMapper.getByUserId(userId);
        String beInvitedCode = byUserId.getBeInvitedCode();
        User userByInviteCode = null;
        while (!"1".equals(beInvitedCode) && !"88888888".equals(beInvitedCode)){
            userByInviteCode = usersMapper.getUserByInviteCode(beInvitedCode);
            beInvitedCode = userByInviteCode.getBeInvitedCode();
        }
        return userByInviteCode;
    }

}
