package cn.wisenergy.service.app.impl;

import cn.wisenergy.common.utils.R;
import cn.wisenergy.common.utils.RedisUtils;
import cn.wisenergy.common.utils.ResultUtils;
import cn.wisenergy.common.utils.ShareCodeUtil;
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.model.vo.AerialDeliveryVo;
import cn.wisenergy.model.vo.UserPoolVo;
import cn.wisenergy.service.app.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.util.*;

/**
 * @author 86187
 * @ Description: 用户接口实现
 * @ Author     : 86187
 * @ Date       : 2021/1/6 16:11
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UsersMapper, User> implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RecommendUserMapper recommendUserMapper;

    @Autowired
    private TeamUserInfoMapper teamUserInfoMapper;

    @Override
    public User getById(String userId) {
        return usersMapper.getByUserId(userId);
    }

    @Override
    public R<Integer> getById1(String userId) {

        return R.ok(usersMapper.ByUserId(userId));
    }

    @Override
    public User getByUserId(String userId) {
        return usersMapper.getByUserId(userId);
    }


    @Override
    public User queryUsersByPhone(String userId) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", userId);
        List<User> usersList = usersMapper.getUsersListByMap(param);
        if (!CollectionUtils.isEmpty(usersList)) {
            return usersList.get(0);
        }
//        return ResultUtils.returnFail("","");
        return null;
    }

    @Override
    public User queryUsersByOpenId(String id) {
        return null;
    }

    @Override
    public Map userByZx(String userId, String beInvitedCode) {
        //查询数据库，看看是否存在该用户
        // Integer yh=usersMapper.getuserIdById(userId);
        User byUserId = usersMapper.getByUserId(userId);
        if (null != byUserId) {
            R.error(0, "该用户已存在！请直接登录！");
            Map map = new HashMap();
            map.put("code", 0);
            map.put("msg", "该用户已存在！请直接登录！");
            return map;
        }
        /**
         * 判断用户推荐人的邀请码是否为空，空的话填写1
         */
        if (null == beInvitedCode || "" == beInvitedCode) {
            beInvitedCode = "1";

            //        插入用户手机号与推荐人邀请码
            usersMapper.insertbyint(userId, beInvitedCode);
        } else if ("1".equals(beInvitedCode)) {
            //用户的被邀请码，查询到推荐人用户，根据推荐人用户的邀请码查询/修改
            User user = usersMapper.getByBeInvitedCode(beInvitedCode);
            int ida = user.getId();
//        邀请人的被邀请码
            String byqm = user.getBeInvitedCode();
//        通过被邀请码，比对本人邀请码查询本人id
            int idb = usersMapper.beInvitedCode1(beInvitedCode);
            //判断被邀请用户的创建时间是否比推荐人的用户时间晚
            if (idb < ida) {
                Map map = new HashMap();
                R.error(1, "注册失败！邀请码无效,请重新填写！");
                map.put("code:", 1);
                map.put("msg:", "注册失败！邀请码无效,请重新填写！");
                return map;
            }

            if (null == beInvitedCode || "" == beInvitedCode) {
                beInvitedCode = String.valueOf(1);
            }
        }

        //根据插入的用户手机号，查询用户唯一ID
        long yqm = usersMapper.getuserIdById(userId);
        //用户唯一ID调用生成6位邀请码
        String inviteCode = ShareCodeUtil.idToCode(yqm);
        Integer userLevel = 0;
        //根据用户手机号，更新用户信息
//        usersMapper.edit1(userLevel,inviteCode,userId);
        User byUserId1 = usersMapper.getByUserId(userId);
        byUserId1.setInviteCode(inviteCode);
        byUserId1.setUserLevel(0);

        usersMapper.edit(byUserId1);

        String BYQM = String.valueOf(usersMapper.BYQMById(userId));

        if ("1".equals(BYQM)) {
            Map map = new HashMap();
            map.put("code", 0);
            map.put("msg", "注册成功！");
            return map;
        }
        //插入直推用户表
        RecommendUser recommendUser = new RecommendUser();
        recommendUser.setUserId(userId);
        recommendUserMapper.insert(recommendUser);
        //插入用户团队表
        TeamUserInfo teamUserInfo = new TeamUserInfo();
        teamUserInfo.setUserId(userId);
        teamUserInfoMapper.insert(teamUserInfo);
        //根据用户的推荐人邀请码比对推荐人的本人邀请码，查询推荐人的用户ID=userid
        String userid = String.valueOf(usersMapper.inviteCodeBeInvitedCode(Integer.valueOf(beInvitedCode)));
        //根据用户推荐人的userid,查询数据库，看推荐人用户是否存在
        Integer a = recommendUserMapper.zcByUserId(userid);

        //判断从数据库中是否存在该用户    如果存在，普通用户+1
        if (null != a && 0 != a) {
            Integer normalUserNum = recommendUser.getNormalUserNum();
            //更新直推表用户中的普通用户字段+1
            recommendUser.setNormalUserNum(normalUserNum + 1);
            //更新直推表用户数据
            recommendUserMapper.updateById(recommendUser);
        } else {
            Map map = new HashMap();
            R.error(1, "注册失败！验证码无效,请重新填写！");
            map.put("code:", 1);
            map.put("msg:", "注册失败！验证码无效,请重新填写！");
            return map;
        }
        //递归向上修改团队用户信息表
        teamgg(beInvitedCode);
        Map map = new HashMap();
        R.ok("直推表普通用户数量+1成功！", 0);
        map.put("code:", 0);
        map.put("msg:", "直推表普通用户数量+1成功");
        return map;
    }

    @Override
    public Integer getUserIdById(String userId) {
        return null;
    }


    @Override
    public R<AerialDeliveryVo> queryAerialDelivery() {
        log.info("shop-mall[]UserServiceImpl[]queryAerialDelivery[]input.method");
        //获取本月新注册用户
        Map<String, Object> map = new HashMap<>(4);
        map.put("createTime", new Date());
        List<User> list = usersMapper.getList(map);
        if (CollectionUtils.isEmpty(list)) {
            return R.ok(new AerialDeliveryVo());
        }

        AerialDeliveryVo aerialDeliveryVo = new AerialDeliveryVo();
        List<UserPoolVo> userPoolVoList = new ArrayList<>();
        for (User user : list) {
            UserPoolVo userPoolVo = new UserPoolVo();
            userPoolVo.setUserId(user.getUserId());
            userPoolVo.setHeadImage(user.getHeadImage());
            userPoolVo.setIntoTime(user.getCreateTime());
            userPoolVoList.add(userPoolVo);
        }
        aerialDeliveryVo.setTotal(list.size());
        aerialDeliveryVo.setUserPoolVos(userPoolVoList);
        return R.ok(aerialDeliveryVo);
    }

    @Override
    public R<Boolean> setHeadImage(String userId, String headImage) {
        log.info("shop-mall[]UserServiceImpl[]setHeadImage[]input.param.userId,headImage:" + userId, headImage);
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(headImage)) {
            return R.error("入参不能为空!");
        }

        //获取用户信息
        User user = usersMapper.getByUserId(userId);
        if (null == user) {
            return R.error("用户信息不存在!");
        }

        //添加头像
        user.setHeadImage(headImage);
        int count = usersMapper.edit(user);
        if (count == 0) {
            return R.error("设置头像失败!");
        }
        return R.ok(0, true);
    }

    @Override
    public R<Boolean> fillInInviteCode(String userId, String inviteCode) {
        log.info("shop-mall[]UserServiceImpl[]fillInInviteCode[]input.param.userId,inviteCode:" + userId, inviteCode);
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(inviteCode)) {
            return R.error("入参不能为空!");
        }

        //1、获取用户信息
        User user = usersMapper.getByUserId(userId);
        if (null == user) {
            return R.error("用户信息不存在!");
        }

        //2、根据邀请码，获取邀请人信息
        User userCode = usersMapper.queryByInviteCode(inviteCode);
        if (null == userCode) {
            return R.error("邀请人信息不存在!");
        }

        //3、判断邀请人的注册时间是否大于当前用户
        if (user.getCreateTime().getTime() > userCode.getCreateTime().getTime()) {
            return R.error("请填写注册时间大于自己的用户邀请码!");
        }

        //4、设置用户被邀请码
        user.setBeInvitedCode(inviteCode);
        int count = usersMapper.edit(user);
        if (count == 0) {
            return R.ok(1, false);
        }
        return R.ok(0, true);
    }

    //私有构造方法-传入被邀请码
    private R teamgg(String beInvitedCode) {
        //用户的被邀请码，查询到推荐人用户，根据推荐人用户的邀请码查询/修改
        User user = usersMapper.getByBeInvitedCode(beInvitedCode);
        //根据用户的推荐人邀请码比对推荐人的本人邀请码，查询推荐人的用户ID=userid
        String userid = String.valueOf(usersMapper.inviteCodeBeInvitedCode(Integer.valueOf(beInvitedCode)));
        //根据用户推荐人的userid,查询数据库，看推荐人用户是否存在
        Integer c = teamUserInfoMapper.czByUserId(userid);
        if (null != c && 0 != c) {
            TeamUserInfo teamUserInfo = new TeamUserInfo();
            int normalUserNum1 = teamUserInfo.getNormalUserNum();
            //更新团队表用户中的普通用户字段+1
            teamUserInfo.setNormalUserNum(normalUserNum1 + 1);
            //更新团队表用户数据
            teamUserInfoMapper.updateById(teamUserInfo);
        } else {
            return R.error(0, "验证码无效");
        }
        beInvitedCode = user.getBeInvitedCode();
        //递归向上修改团队用户信息表
        teamgg(beInvitedCode);
        return R.ok("团队表普通用户数量+1成功！", 0);
    }
}
