package cn.wisenergy.service.app.impl;

import cn.wisenergy.common.utils.R;
import cn.wisenergy.common.utils.ShareCodeUtil;
import cn.wisenergy.mapper.RecommendUserMapper;
import cn.wisenergy.mapper.UsersMapper;
import cn.wisenergy.model.app.User;
import cn.wisenergy.service.app.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import javax.xml.transform.Result;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @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;

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

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

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



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

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

    @Override
    public Integer userByZx(String userId, String beInvitedCode) {
        /**
         * 判断用户等级是否为空，空的话填写0
         */
        if(null==beInvitedCode || ""==beInvitedCode){
            beInvitedCode= String.valueOf(1);
        }
//        插入用户手机号与推荐人邀请码
        usersMapper.insertbyint(userId,beInvitedCode);
        //根据插入的用户手机号，查询用户唯一ID
        Integer yqm=usersMapper.getByUserId(userId);
        //用户唯一ID调用生成6位邀请码
        String inviteCode= ShareCodeUtil.idToCode(yqm);
        //根据用户手机号，更新用户信息
        User user = new User();
        user.setInviteCode(inviteCode);
        user.setUserLevel(0);
        usersMapper.updateById(user);
        //插入直推用户表

        //插入用户团队表

        //根据邀请码查询推荐人的普通用户字段+1
        Integer a=recommendUserMapper.zcByUserId(userId);
        if(null!=a && 0 != a){

        }
        //根据邀请码递归所有团队成员普通用户+1

    }

}
