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.checkerframework.checker.index.qual.LengthOf;
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) {
                int userLevel = user.getUserLevel();
                Integer id = user.getId();
                String userId = user.getUserId();
                log.info("当前用户id--------------"+userId+"当前用户等级----------------"+userLevel);
                //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);
                //3、随机用户的直推表数据维护
                RecommendUser recommendUserMapperByRandUser = recommendUserMapper.getByUserId(randUser.getUserId());
                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);
                }
                //4、用户的团队表数据维护
                teamUserInfoByAerialDelivery(randUserId,userId);
                //5、查看当前用户是否要进行升级
                userLevelService.userLevelUpgrade(randUser.getUserId());
            }
        }


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

    /**
     * 团队数据维护
     * @param beInvitedUserId 推荐人userId
     * @param userId 当前用户的userId
     */
    private void teamUserInfoByAerialDelivery(String beInvitedUserId, String userId) {
        TeamUserInfo teamUserInfoByIntvitedUser = teamUserInfoMapper.getByUserId(beInvitedUserId);
        TeamUserInfo teamUserInfoByUserId = teamUserInfoMapper.getByUserId(userId);
        //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、最终团队各个等级的人数 推荐人用户本身的数量 + 当前用户的数量 + 当前用户自身（1）
        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;
            }
        }

        Map<String, Integer> teamDataMap = new ConcurrentHashMap<String, Integer>();
        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);
        //4.1 根据当前用户向上维护数据
        upWardDataPreserve(teamDataMap,beInvitedUserId);

        //4.2 根据当前用户向下维护数据（包括当前用户自身）
        downWardDataPreserve(teamDataMap,userId);
    }

    /**
     * 根据推荐人的id向上进行团队数据维护
     * @param teamDataMap  团队表数据
     * @param beInvitedUserId  当前用户的推荐人id
     */
    private void upWardDataPreserve(Map<String, Integer> teamDataMap, String beInvitedUserId) {

        User userById = usersMapper.getByUserId(beInvitedUserId);
        TeamUserInfo teamUserInfoMapperByUserId = teamUserInfoMapper.getByUserId(beInvitedUserId);

        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);
        //推荐人的用户表对象
        User invitedUserId = usersMapper.getByUserId(beInvitedUserId);
        //推荐人的推荐人用户对象
        //todo: 推荐人用户id获取推荐人的上级用户
        User user = usersMapper.getuserByBeInvitedCode(invitedUserId.getBeInvitedCode());

        if (null != user){
            String userId = user.getUserId();
            upWardDataPreserve(teamDataMap,userId);
        }else {
            return;
        }
    }

    /**
     * 根据推荐人的id向下进行团队数据维护
     * @param teamDataMap  团队数据
     * @param userId  当前用户的id
     */
    private void downWardDataPreserve(Map<String, Integer> teamDataMap, String 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"));

        //当前用户对象中获取当前用户的邀请码
        User userByUserId = usersMapper.getByUserId(userId);
        String inviteCode = userByUserId.getInviteCode();
        //获取当前用户的所有下一级用户
        List<User> listByIntvitedCode = usersMapper.getListByIntvitedCode(inviteCode);
        //当前用户有下级用户
        if (listByIntvitedCode.size() > 0){
            for (User user : listByIntvitedCode) {
                String downUserId = user.getUserId();
                downWardDataPreserve(teamDataMap,downUserId);
            }
        }else {
            //当前用户没有下级用户是退出
            return;
        }

    }
}
