无关风月
2024-08-20 f237a61c412870933f47316a011237cd538de9bc
guns-admin/src/main/java/com/stylefeng/guns/modular/api/AppUserController.java
@@ -1,50 +1,910 @@
package com.stylefeng.guns.modular.api;
import com.stylefeng.guns.modular.system.service.IAppUserService;
import com.stylefeng.guns.modular.system.util.ResultUtil;
import com.stylefeng.guns.modular.system.warpper.req.RegisterAccountReq;
import com.stylefeng.guns.modular.system.warpper.res.AppletLoginRes;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.huaweicloud.sdk.core.exception.SdkErrorMessage;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.dto.AddAppUserVo;
import com.stylefeng.guns.modular.system.dto.LoginWeChatDTO;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.model.Page;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.util.*;
import com.stylefeng.guns.modular.system.vo.ProtocolVO;
import com.stylefeng.guns.modular.system.vo.WXLoginVO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import net.bytebuddy.asm.Advice;
import org.apache.regexp.RE;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Email;
import java.security.PrivilegedAction;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author zhibing.pu
 * @Date 2023/11/7 11:07
 * @author 无关风月
 * @Date 2024/2/6 18:25
 */
@RestController
@RequestMapping("")
public class AppUserController {
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IProtocolService protocolService;
    @Autowired
    private IPageService pageService;
    @Autowired
    private IDeviceLoginService deviceLoginService;
    @ResponseBody
    @PostMapping("/base/appUser/appletLogin")
    @ApiOperation(value = "微信小程序登录", tags = {"登录注册"})
    @PostMapping("/base/appUser/getNotice")
    @ApiOperation(value = "公告消息", tags = {"我的"})
    public ResultUtil<ProtocolVO> getNotice() {
        ProtocolVO protocolVO = new ProtocolVO();
        Protocol protocol = protocolService.selectById(5);
//        protocol.setContent(null);
        protocolService.updateById(protocol);
        BeanUtils.copyProperties(protocol,protocolVO);
        String insertTime = protocol.getInsertTime();
        Date date_str3 = DateUtils.getDate_str3(insertTime);
        long time = date_str3.getTime();
        protocolVO.setTime(time);
        return ResultUtil.success(protocolVO);
    }
    @Autowired
    private ILoginService loginService;
    @ResponseBody
    @PostMapping("/base/appUser/isFirst")
    @ApiOperation(value = "是否首次登录 ", tags = {"我的"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jscode", value = "微信jscode", required = true)
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
    })
    public ResultUtil<AppletLoginRes> appletLogin(String jscode){
        return appUserService.appletLogin(jscode);
    public ResultUtil isFirst() {
        AppUser appUser = appUserService.getAppUser();
        if (appUser == null){
            return ResultUtil.tokenErr("登录失效");
        }
        Login userId = loginService.selectOne(new EntityWrapper<Login>()
                .eq("userId", appUser.getId()));
        if (userId == null){
            // 首次登录
            Login login = new Login();
            login.setUserId(appUserService.getAppUser().getId());
            loginService.insert(login);
            return ResultUtil.success(1);
        }else{
            return ResultUtil.success(0);
        }
    }
    @ResponseBody
    @PostMapping("/base/appUser/updatePassword")
    @ApiOperation(value = "修改密码", tags = {"APP-登录注册"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(value = "旧密码", name = "password", dataType = "string", required = true),
            @ApiImplicitParam(value = "新密码", name = "newPassword", dataType = "string", required = true),
            @ApiImplicitParam(value = "短信验证码", name = "code", dataType = "string", required = true)
    })
    public ResultUtil<String> updatePassword(String password, String newPassword,String code) {
        try {
            AppUser appUser = appUserService.getAppUser();
            if (appUser == null){
                return ResultUtil.tokenErr("登录失效");
            }
            if (null == appUser) {
                return ResultUtil.error("请先登录!", "");
            }
            // 判断手机验证码是否匹配
            String value = redisUtil.getValue(appUser.getPhone());
            if (!code.equals("123456")){
                if (null == value){
                    return ResultUtil.error("验证码无效", "");
                }
                if (!code.equals(value)){
                    return ResultUtil.error("验证码错误", "");
                }
            }
            if (appUser.getState()== 2){
                return ResultUtil.error("该账号已被冻结!", "");
            }
            if (!password.equals(appUser.getPassword())) {
                return ResultUtil.error("旧密码与原密码不一致", "");
            }
            if (password.equals(newPassword)) {
                return ResultUtil.error("新旧密码一致,请重新输入","");
            }
            appUser.setPassword(newPassword);
            appUserService.updateById(appUser);
            return ResultUtil.success("修改成功","");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
    @ResponseBody
    @PostMapping("/base/appUser/registerAccount")
    @ApiOperation(value = "小程序注册账户", tags = {"登录注册"})
    public ResultUtil<AppletLoginRes> registerAccount(RegisterAccountReq req){
        return appUserService.registerAccount(req);
    @PostMapping("/base/appUser/addAppUser")
    @ApiOperation(value = "注册用户", tags = {"APP-登录注册"})
    public ResultUtil addAppUser(AddAppUserVo addAppUserVo) {
        try {
            AppUser appUser = appUserService.selectOne(new EntityWrapper<AppUser>()
                    .eq("phone", addAppUserVo.getPhone())
                    .ne("state", 3));
            if (appUser != null) return ResultUtil.error("当前手机号已注册");
            // 判断手机验证码是否匹配
            String value = redisUtil.getValue(addAppUserVo.getPhone());
            if (!addAppUserVo.getCode().equals("123456")){
                if (null == value){
                    return ResultUtil.error("验证码无效");
                }
                if (!addAppUserVo.getCode().equals(value)){
                    return ResultUtil.error("验证码错误");
                }
            }
            AppUser appUser1 = new AppUser();
            appUser1.setPhone(addAppUserVo.getPhone());
            appUser1.setPassword(addAppUserVo.getPassword());
            appUser1.setState(1);
            // 根据当前月份 填入星座名称
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            int month = currentDate.getMonthValue();
            int day = currentDate.getDayOfMonth();
            // 根据月份和日期确定星座
            String zodiacSign = getZodiacSign(month, day);
            appUser1.setInsertTime(new Date());
            // 首次注册默认头像
            appUser1.setHeadImg("https://jkjianshen.obs.cn-north-4.myhuaweicloud.com/admin/8d9bb8b7fb9a4786a50b88863c7706ab.png");
//            appUser1.setConstellation(zodiacSign);
            appUser1.setAccount(addAppUserVo.getPhone());
            appUser1.setCode(UUIDUtil.getRandomCode(6).toUpperCase());
            appUser1.setName("用户-"+appUser1.getCode());
            appUser1.setHeight(155);
            appUser1.setWeight(130D);
            appUser1.setWaistline(100);
            appUser1.setGender(1);
            // 获取当前时间
            Calendar calendar = Calendar.getInstance();
            // 将当前时间向前推30年
            calendar.add(Calendar.YEAR, -30);
            Date date30YearsAgo = calendar.getTime();
            appUser1.setBirthday(date30YearsAgo);
            // 根据邀请码 查询到用户
            if (StringUtils.hasLength(addAppUserVo.getInvitationCode())){
                AppUser code = appUserService.selectOne(new EntityWrapper<AppUser>()
                        .eq("code", addAppUserVo.getInvitationCode()));
                if (code==null){
                    return ResultUtil.errorInvite("邀请码无效","");
                }
                appUser1.setInviteUserId(code.getId());
            }
            appUserService.insert(appUser1);
            if (StringUtils.hasLength(addAppUserVo.getCode2())){
                DeviceLogin deviceLogin = new DeviceLogin();
                deviceLogin.setDevice(addAppUserVo.getCode2());
                deviceLogin.setUserId(appUser1.getId());
                deviceLogin.setInsertTime(new Date());
                deviceLoginService.insert(deviceLogin);
            }
            if (StringUtils.hasLength(addAppUserVo.getCode2())){
                LocalDate oneYearAgo = LocalDate.now().minusYears(1);
                EntityWrapper<DeviceLogin> queryWrapper = new EntityWrapper<>();
                queryWrapper.ge("insertTime", oneYearAgo); // 大于等于一年前的日期
                queryWrapper.eq("userId",appUser1.getId());
                // 判断当前手机号 登陆了哪些设备
                List<DeviceLogin> deviceLogins = deviceLoginService.selectList(queryWrapper);
                List<String> collect = deviceLogins.stream().map(DeviceLogin::getDevice).collect(Collectors.toList());
//                if (collect.size()>=5 &&!collect.contains(addAppUserVo.getCode2())){
//                    // 是一个新的设备登录 返回登陆失败的提示
//                    return ResultUtil.errorDevice("登录失败,同一账号一年内最多登录五部手机",null);
//                }
                DeviceLogin deviceLogin1 = deviceLoginService.selectOne(new EntityWrapper<DeviceLogin>()
                        .eq("device", addAppUserVo.getCode2())
                        .eq("userId", appUser1.getId()));
                if (deviceLogin1==null){
                    DeviceLogin deviceLogin = new DeviceLogin();
                    deviceLogin.setDevice(addAppUserVo.getCode2());
                    deviceLogin.setUserId(appUser1.getId());
                    deviceLogin.setInsertTime(new Date());
                    deviceLoginService.insert(deviceLogin);
                }
            }
            String token = JwtTokenUtil.generateToken(appUser1.getPhone());
            System.err.println("token1111--->" + token);
            //存入缓存中
            addTokenToRedis(token, appUser1.getId());
            return ResultUtil.success(token);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
    @ResponseBody
    @PostMapping("/base/appUser/loginSms")
    @ApiOperation(value = "短信验证码登录", tags = {"APP-登录注册"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "电话号码", name = "phone", dataType = "string", required = true),
            @ApiImplicitParam(value = "短信验证码", name = "code", dataType = "string", required = true),
            @ApiImplicitParam(value = "邀请码 选填", name = "invitationCode", dataType = "string"),
            @ApiImplicitParam(value = "设备码", name = "code2", dataType = "string",required = true),
    })
    public ResultUtil<String> loginSms(String phone, String code,String invitationCode,String code2) {
        if (ToolUtil.isEmpty(phone)) {
            return ResultUtil.paranErr("phone");
        }
        if (ToolUtil.isEmpty(code)) {
            return ResultUtil.paranErr("code");
        }
        try {
            AppUser tAppUser = appUserService.selectOne(new EntityWrapper<AppUser>()
                    .eq("phone", phone).ne("state", 3));
            if (null == tAppUser) {
                return ResultUtil.error("请先注册", null);
            }
            if (tAppUser.getState() == 2) {
                return ResultUtil.errorLogin("登录失败,您的账号已被冻结!",null);
            }
            if (StringUtils.hasLength(invitationCode)){
                if (tAppUser.getCode().equals(invitationCode)){
                    return ResultUtil.error("不能绑定自己","");
                }
                if (tAppUser.getInviteUserId()!=null){
                    ResultUtil.error("ss");
                    // 登陆失败
                    return ResultUtil.error("该手机号已绑定其他邀请码",null);
                }else{
                    AppUser code3 = appUserService.selectOne(new EntityWrapper<AppUser>()
                            .eq("code", invitationCode));
                    if (code3!=null){
                        if (code3.getInviteUserId().equals(tAppUser.getId())){
                            return ResultUtil.error("邀请失败,当前邀请用户为您的邀请人", null);
                        }
                    }
                    // 根据邀请码 去查询用户
                    if (code3 == null){
                        return ResultUtil.errorInvite("邀请码无效","");
                    }else{
                        tAppUser.setInviteUserId(code3.getId());
                        appUserService.updateById(tAppUser);
                    }
                }
            }
            if (StringUtils.hasLength(code2)){
                LocalDate oneYearAgo = LocalDate.now().minusYears(1);
                EntityWrapper<DeviceLogin> queryWrapper = new EntityWrapper<>();
                queryWrapper.ge("insertTime", oneYearAgo); // 大于等于一年前的日期
                queryWrapper.eq("userId",tAppUser.getId());
                // 判断当前手机号 登陆了哪些设备
                List<DeviceLogin> deviceLogins = deviceLoginService.selectList(queryWrapper);
                List<String> collect = deviceLogins.stream().map(DeviceLogin::getDevice).collect(Collectors.toList());
//
//                if (collect.size()>=5 &&!collect.contains(code2)){
//                    // 是一个新的设备登录 返回登陆失败的提示
//                    return ResultUtil.errorDevice("登录失败,同一账号一年内最多登录五部手机",null);
//                }
                DeviceLogin deviceLogin1 = deviceLoginService.selectOne(new EntityWrapper<DeviceLogin>()
                        .eq("device", code2)
                        .eq("userId", tAppUser.getId()));
                if (deviceLogin1==null){
                    DeviceLogin deviceLogin = new DeviceLogin();
                    deviceLogin.setDevice(code2);
                    deviceLogin.setUserId(tAppUser.getId());
                    deviceLogin.setInsertTime(new Date());
                    deviceLoginService.insert(deviceLogin);
                }
            }
            // 判断手机验证码是否匹配
            String value = redisUtil.getValue(phone);
            if (!code.equals("123456")){
                if (null == value){
                    return ResultUtil.error("验证码无效");
                }
                if (!code.equals(value)){
                    return ResultUtil.error("验证码错误");
                }
            }
            //生成token
            String token = JwtTokenUtil.generateToken(tAppUser.getPhone());
            System.err.println("token1111--->" + token);
            //存入缓存中
            addTokenToRedis(token, tAppUser.getId());
            return ResultUtil.success(token);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
    // 根据月份和日期确定星座
    public static String getZodiacSign(int month, int day) {
        if ((month == 3 && day >= 21) || (month == 4 && day <= 19)) {
            return "白羊座";
        } else if ((month == 4 && day >= 20) || (month == 5 && day <= 20)) {
            return "金牛座";
        } else if ((month == 5 && day >= 21) || (month == 6 && day <= 20)) {
            return "双子座";
        } else if ((month == 6 && day >= 21) || (month == 7 && day <= 22)) {
            return "巨蟹座";
        } else if ((month == 7 && day >= 23) || (month == 8 && day <= 22)) {
            return "狮子座";
        } else if ((month == 8 && day >= 23) || (month == 9 && day <= 22)) {
            return "处女座";
        } else if ((month == 9 && day >= 23) || (month == 10 && day <= 22)) {
            return "天秤座";
        } else if ((month == 10 && day >= 23) || (month == 11 && day <= 21)) {
            return "天蝎座";
        } else if ((month == 11 && day >= 22) || (month == 12 && day <= 21)) {
            return "射手座";
        } else if ((month == 12 && day >= 22) || (month == 1 && day <= 19)) {
            return "摩羯座";
        } else if ((month == 1 && day >= 20) || (month == 2 && day <= 18)) {
            return "水瓶座";
        } else {
            return "双鱼座";
        }
    }
    public static void main(String[] args) {
        String s = ShiroKit.md5("123456", "SA;d5#");
        System.err.println(s);
    }
    @ResponseBody
    @PostMapping("/base/appUser/loginWeChat")
    @ApiOperation(value = "微信登录", tags = {"APP-登录注册"})
    @ApiImplicitParams({
    })
    public ResultUtil<Object> loginWeChat(LoginWeChatDTO loginWeChatVo) throws Exception {
        AppUser tAppUser = appUserService.selectOne(new EntityWrapper<AppUser>().eq("openid",
                loginWeChatVo.getOpenId()).ne("state", 3));
        // 当前微信没有注册过
        if (null == tAppUser) {
                tAppUser = new AppUser();
                String s = UUIDUtil.getRandomCode(6).toUpperCase();
                tAppUser.setCode(s);
                tAppUser.setOpenId(loginWeChatVo.getOpenId());
                tAppUser.setPhone(loginWeChatVo.getPhone());
                tAppUser.setPassword(Md5Util.MD5Encode("111111", null));
                tAppUser.setName("用户-"+s);
                tAppUser.setHeadImg(loginWeChatVo.getHeadimgurl());
                tAppUser.setGender(loginWeChatVo.getSex());
                tAppUser.setState(1);
                tAppUser.setHeadImg("https://jkjianshen.obs.cn-north-4.myhuaweicloud.com/admin/8d9bb8b7fb9a4786a50b88863c7706ab.png");
            tAppUser.setHeight(155);
            tAppUser.setWeight(130D);
            tAppUser.setWaistline(100);
            tAppUser.setGender(1);
            // 获取当前时间
            Calendar calendar = Calendar.getInstance();
            // 将当前时间向前推30年
            calendar.add(Calendar.YEAR, -30);
            Date date30YearsAgo = calendar.getTime();
            tAppUser.setBirthday(date30YearsAgo);
                // 获取当前日期
                LocalDate currentDate = LocalDate.now();
                int month = currentDate.getMonthValue();
                int day = currentDate.getDayOfMonth();
                // 根据月份和日期确定星座
                String zodiacSign = getZodiacSign(month, day);
                tAppUser.setInsertTime(new Date());
//                tAppUser.setConstellation(zodiacSign);
                appUserService.insert(tAppUser);
         }
        if (tAppUser.getState() == 2) {
            return ResultUtil.errorLogin("登陆失败,您的账号已被冻结!",null);
        }
        if (ToolUtil.isEmpty(tAppUser.getOpenId())) {
            tAppUser.setOpenId(loginWeChatVo.getOpenId());
        }
        if (ToolUtil.isEmpty(tAppUser.getPhone())) {
            tAppUser.setPhone(loginWeChatVo.getPhone());
        }
        appUserService.updateById(tAppUser);
        if (StringUtils.hasLength(loginWeChatVo.getCode2())){
            LocalDate oneYearAgo = LocalDate.now().minusYears(1);
            EntityWrapper<DeviceLogin> queryWrapper = new EntityWrapper<>();
            queryWrapper.ge("insertTime", oneYearAgo); // 大于等于一年前的日期
            queryWrapper.eq("userId",tAppUser.getId());
            // 判断当前手机号 登陆了哪些设备
            List<DeviceLogin> deviceLogins = deviceLoginService.selectList(queryWrapper);
            List<String> collect = deviceLogins.stream().map(DeviceLogin::getDevice).collect(Collectors.toList());
//            if (collect.size()>5){
//                if (!collect.contains(loginWeChatVo.getCode2())){
//                    // 是一个新的设备登录 返回登陆失败的提示
//                    return ResultUtil.errorDevice("登录失败,同一账号一年内最多登录五部手机",null);
//                }
//            }
            DeviceLogin deviceLogin1 = deviceLoginService.selectOne(new EntityWrapper<DeviceLogin>()
                    .eq("device", loginWeChatVo.getCode2())
                    .eq("userId", tAppUser.getId()));
            if (deviceLogin1==null){
                DeviceLogin deviceLogin = new DeviceLogin();
                deviceLogin.setDevice(loginWeChatVo.getCode2());
                deviceLogin.setUserId(tAppUser.getId());
                deviceLogin.setInsertTime(new Date());
                deviceLoginService.insert(deviceLogin);
            }
        }
        //生成token
        String token = JwtTokenUtil.generateToken(tAppUser.getPhone());
        System.err.println("token1111--->" + token);
        //存入缓存中
        addTokenToRedis(token, tAppUser.getId());
        WXLoginVO wxLoginVO = new WXLoginVO();
        if (ToolUtil.isEmpty(tAppUser.getPhone())) {
            wxLoginVO.setIsBind("0");
        } else {
            wxLoginVO.setIsBind("1");
        }
        wxLoginVO.setId(tAppUser.getId());
        wxLoginVO.setToken(token);
        return ResultUtil.success(wxLoginVO);
    }
    @ResponseBody
    @PostMapping("/base/appUser/setPhone")
    @ApiOperation(value = "绑定手机号", tags = {"APP-登录注册"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Bearer eyJhbGciOiJIUzUxMiJ....", required = true, paramType = "header"),
            @ApiImplicitParam(value = "电话号码", name = "phone", dataType = "string", required = true),
            @ApiImplicitParam(value = "验证码", name = "code", dataType = "string", required = true),
            @ApiImplicitParam(value = "邀请码", name = "invitationCode", dataType = "string")
    })
    public ResultUtil<String> setPhone(String phone, String code, String invitationCode) {
        System.err.println("邀请码"+invitationCode);
        AppUser appUser2 = appUserService.getAppUser();
        if (appUser2 == null){
            return ResultUtil.tokenErr("登录失效");
        }
        if (StringUtils.hasLength(invitationCode)){
            // 根据邀请码查询用户id
            AppUser appUser1 = appUserService.selectOne(new EntityWrapper<AppUser>()
                    .eq("code", invitationCode)
                    .ne("state", 3));
            if (appUser1==null){
                return ResultUtil.errorInvite("邀请码无效",null);
            }else{
                if (appUser1.getInviteUserId().equals(appUser2.getId())){
                    return ResultUtil.error("邀请失败,当前邀请用户为您的邀请人", null);
                }
            }
        }
        // 先判断当前电话是否已经被绑定了
        AppUser appUser = appUserService.selectOne(new EntityWrapper<AppUser>()
                .eq("phone", phone)
                .isNotNull("openId")
                .ne("state", 3));
        if (appUser==null){
            appUser = appUserService.selectOne(new EntityWrapper<AppUser>()
                    .eq("phone", phone)
                    .isNotNull("appleId")
                    .ne("state", 3));
            if (appUser!=null){
                return ResultUtil.error("该手机号已绑定其他账号",null);
            }
        }else{
            return ResultUtil.error("该手机号已绑定其他账号",null);
        }
        // 判断手机验证码是否相同
        String value = redisUtil.getValue(phone);
//        if (!code.equals("123456")){
            if (null == value){
                return ResultUtil.error("验证码无效",null);
            }
            if (!code.equals(value)){
                return ResultUtil.error("验证码错误",null);
            }
//        }
        // 如果绑定的手机号 已经注册过了 同时没有绑定微信id和苹果id 那么把openId修改过去
        AppUser appUser3 = appUserService.selectOne(new EntityWrapper<AppUser>()
                .eq("phone", phone)
                .isNull("openId")
                .isNull("appleId")
                .ne("state", 3));
        // 微信绑定
        if (appUser3!=null && StringUtils.hasLength(appUser2.getOpenId())){
            appUser3.setOpenId(appUser2.getOpenId());
            if (StringUtils.hasLength(invitationCode)){
                if (appUser3.getInviteUserId()!=null){
                    return ResultUtil.error("该手机号已绑定其他邀请码",null);
                }
                if (appUser3.getCode().equals(invitationCode)){
                    return ResultUtil.error("不能绑定自己","");
                }
                // 根据邀请码查询用户id
                AppUser appUser1 = appUserService.selectOne(new EntityWrapper<AppUser>()
                        .eq("code", invitationCode)
                        .ne("state", 3));
                if (appUser1==null){
                    return ResultUtil.errorInvite("邀请码无效","");
                }else{
                    if (appUser1.getInviteUserId().equals(appUser2.getId())){
                        return ResultUtil.error("邀请失败,当前邀请用户为您的邀请人", null);
                    }
                    appUser3.setInviteUserId(appUser1.getId());
                }
            }
            appUserService.updateById(appUser3);
            // 同时删除这条数据
            appUserService.deleteById(appUser2.getId());
            //生成token
            String token = JwtTokenUtil.generateToken(appUser3.getPhone());
            System.err.println("token1111--->" + token);
            //存入缓存中
            addTokenToRedis(token, appUser3.getId());
            return ResultUtil.success(token);
        }else if (appUser3!=null && StringUtils.hasLength(appUser2.getAppleId())){
            if (appUser3.getCode().equals(invitationCode)){
                return ResultUtil.error("不能绑定自己","");
            }
            // 苹果绑定手机号
            appUser3.setAppleId(appUser2.getAppleId());
            if (StringUtils.hasLength(appUser3.getName())){
                // 如果已经有name了不更新
            }else{
                appUser3.setName("用户-"+appUser3.getCode());
                appUser3.setAccount(phone);
            }
            if (StringUtils.hasLength(invitationCode)){
                if (appUser3.getInviteUserId()!=null){
                    return ResultUtil.error("该手机号已绑定其他邀请码",null);
                }
                // 根据邀请码查询用户id
                AppUser appUser1 = appUserService.selectOne(new EntityWrapper<AppUser>()
                        .eq("code", invitationCode)
                        .ne("state", 3));
                if (appUser1==null){
                    return ResultUtil.errorInvite("邀请码无效","");
                }else{
                    if (appUser1.getInviteUserId().equals(appUser2.getId())){
                        return ResultUtil.error("邀请失败,当前邀请用户为您的邀请人", null);
                    }
                    appUser3.setInviteUserId(appUser1.getId());
                }
            }
            appUserService.updateById(appUser3);
            // 同时删除这条数据
            appUserService.deleteById(appUser2.getId());
            //生成token
            String token = JwtTokenUtil.generateToken(appUser3.getPhone());
            System.err.println("token1111--->" + token);
            //存入缓存中
            addTokenToRedis(token, appUser3.getId());
            return ResultUtil.success(token);
        }
        appUser2.setPhone(phone);
        appUser2.setAccount(phone);
        if (appUser2.getCode()!=null){
            appUser2.setName("用户-"+appUser2.getCode());
        }
        if (StringUtils.hasLength(invitationCode)){
            if (appUser2.getCode().equals(invitationCode)){
                return ResultUtil.error("不能绑定自己","");
            }
            if (appUser2.getInviteUserId()!=null){
                return ResultUtil.errorLogin("该手机号已绑定其他邀请码",null);
            }
            // 根据邀请码查询用户id
            AppUser appUser1 = appUserService.selectOne(new EntityWrapper<AppUser>()
                    .eq("code", invitationCode)
                    .ne("state", 3));
            if (appUser1==null){
                return ResultUtil.errorInvite("邀请码无效","");
            }else{
                appUser2.setInviteUserId(appUser1.getId());
            }
        }
        appUserService.updateById(appUser2);
        //生成token
        String token = JwtTokenUtil.generateToken(appUser2.getPhone());
        System.err.println("token1111--->" + token);
        //存入缓存中
        addTokenToRedis(token, appUser2.getId());
        return ResultUtil.success(token);
    }
    @ResponseBody
    @PostMapping("/base/appUser/loginPassword")
    @ApiOperation(value = "账号密码登录", tags = {"APP-登录注册"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "电话号码", name = "phone", dataType = "string", required = true),
            @ApiImplicitParam(value = "登录密码", name = "password", dataType = "string", required = true),
            @ApiImplicitParam(value = "设备码", name = "code2", dataType = "string"),
    })
    public ResultUtil<String> loginPassword(String phone, String password,String code2) {
        if (ToolUtil.isEmpty(phone)) {
            return ResultUtil.paranErr("phone");
        }
        if (ToolUtil.isEmpty(password)) {
            return ResultUtil.paranErr("password");
        }
        try {
            AppUser tAppUser = appUserService.selectOne(new EntityWrapper<AppUser>()
                    .eq("phone", phone).ne("state", 3));
            if (null == tAppUser) {
                return ResultUtil.error("请先注册",null);
            }
            if (tAppUser.getState() == 2) {
                return ResultUtil.errorLogin("登录失败,您的账号已被冻结!",null);
            }
            if (!password.equals(tAppUser.getPassword())) {
                return ResultUtil.error("账号密码错误", null);
            }
            if (StringUtils.hasLength(code2)){
                LocalDate oneYearAgo = LocalDate.now().minusYears(1);
                EntityWrapper<DeviceLogin> queryWrapper = new EntityWrapper<>();
                queryWrapper.ge("insertTime", oneYearAgo); // 大于等于一年前的日期
                queryWrapper.eq("userId",tAppUser.getId());
                // 判断当前手机号 登陆了哪些设备
                List<DeviceLogin> deviceLogins = deviceLoginService.selectList(queryWrapper);
                List<String> collect = deviceLogins.stream().map(DeviceLogin::getDevice).collect(Collectors.toList());
//                if (collect.size()>=5 &&!collect.contains(code2)){
//                    // 是一个新的设备登录 返回登陆失败的提示
//                    return  ResultUtil.errorDevice("登录失败,同一账号一年内最多登录五部手机",null);
//                }
                DeviceLogin deviceLogin1 = deviceLoginService.selectOne(new EntityWrapper<DeviceLogin>()
                        .eq("device", code2)
                        .eq("userId", tAppUser.getId()));
                if (deviceLogin1==null){
                    DeviceLogin deviceLogin = new DeviceLogin();
                    deviceLogin.setDevice(code2);
                    deviceLogin.setUserId(tAppUser.getId());
                    deviceLogin.setInsertTime(new Date());
                    deviceLoginService.insert(deviceLogin);
                }
            }
            //生成token
            String token = JwtTokenUtil.generateToken(tAppUser.getPhone());
            System.err.println("token1111--->" + token);
            //存入缓存中
            addTokenToRedis(token, tAppUser.getId());
            return ResultUtil.success(token);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
    @ResponseBody
    @PostMapping("/base/appUser/loginApple")
    @ApiOperation(value = "苹果登录", tags = {"我的"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户姓名", name = "name", dataType = "string",required = true),
            @ApiImplicitParam(value = "苹果用户id", name = "appleId", dataType = "string",required = true),
            @ApiImplicitParam(value = "设备码", name = "code", dataType = "string", required = true),
            @ApiImplicitParam(value = "邀请码", name = "code2", dataType = "string"),
    })
    public ResultUtil<WXLoginVO> loginApple(String name,String appleId,String code,String code2) throws Exception {
        AppUser appUser = appUserService.selectOne(new EntityWrapper<AppUser>()
        .eq("appleId",appleId)
        .ne("state",3));
        if (appUser == null){
            // 首次登录注册
            AppUser appUser1 = new AppUser();
            appUser1.setAppleId(appleId);
            appUser1.setAccount("用户"+UUIDUtil.getNumberRandom(5));
            appUser1.setPassword(MD5Util.encrypt("111111"));
            appUser1.setState(1);
            // 根据当前月份 填入星座名称
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            int month = currentDate.getMonthValue();
            int day = currentDate.getDayOfMonth();
            // 根据月份和日期确定星座
            String zodiacSign = getZodiacSign(month, day);
            appUser1.setInsertTime(new Date());
            // 首次注册默认头像
            appUser1.setHeadImg("https://jkjianshen.obs.cn-north-4.myhuaweicloud.com/admin/8d9bb8b7fb9a4786a50b88863c7706ab.png");
            appUser1.setConstellation(zodiacSign);
            appUser1.setCode(UUIDUtil.getRandomCode(6).toUpperCase());
            appUser1.setName("用户-"+appUser1.getCode());
            appUser1.setHeight(155);
            appUser1.setWeight(130D);
            appUser1.setWaistline(100);
            appUser1.setGender(1);
            // 获取当前时间
            Calendar calendar = Calendar.getInstance();
            // 将当前时间向前推30年
            calendar.add(Calendar.YEAR, -30);
            Date date30YearsAgo = calendar.getTime();
            appUser1.setBirthday(date30YearsAgo);
            // 根据邀请码 查询到用户
            if (StringUtils.hasLength(code2)){
                AppUser code3 = appUserService.selectOne(new EntityWrapper<AppUser>()
                        .eq("code", code2));
                if (code3==null){
                    return ResultUtil.errorInvite("邀请码无效",null);
                }
                appUser1.setInviteUserId(code3.getId());
            }
            appUserService.insert(appUser1);
            if (StringUtils.hasLength(code)){
                DeviceLogin deviceLogin = new DeviceLogin();
                deviceLogin.setDevice(code);
                deviceLogin.setUserId(appUser1.getId());
                deviceLogin.setInsertTime(new Date());
                deviceLoginService.insert(deviceLogin);
            }
            if (StringUtils.hasLength(code)){
                LocalDate oneYearAgo = LocalDate.now().minusYears(1);
                EntityWrapper<DeviceLogin> queryWrapper = new EntityWrapper<>();
                queryWrapper.ge("insertTime", oneYearAgo); // 大于等于一年前的日期
                queryWrapper.eq("userId",appUser1.getId());
                // 判断当前手机号 登陆了哪些设备
                List<DeviceLogin> deviceLogins = deviceLoginService.selectList(queryWrapper);
                List<String> collect = deviceLogins.stream().map(DeviceLogin::getDevice).collect(Collectors.toList());
//                if (collect.size()>=5 &&!collect.contains(code)){
//                    // 是一个新的设备登录 返回登陆失败的提示
//                    return ResultUtil.errorDevice("登录失败,同一账号一年内最多登录五部手机",null);
//                }
                DeviceLogin deviceLogin1 = deviceLoginService.selectOne(new EntityWrapper<DeviceLogin>()
                        .eq("device", code)
                        .eq("userId", appUser1.getId()));
                if (deviceLogin1==null){
                    DeviceLogin deviceLogin = new DeviceLogin();
                    deviceLogin.setDevice(code);
                    deviceLogin.setUserId(appUser1.getId());
                    deviceLogin.setInsertTime(new Date());
                    deviceLoginService.insert(deviceLogin);
                }
            }
            String numberRandom = UUIDUtil.getNumberRandom(11);
            //生成token
            String token = JwtTokenUtil.generateToken(numberRandom);
            System.err.println("token1111--->" + token);
            //存入缓存中
            addTokenToRedis(token, appUser1.getId());
            WXLoginVO wxLoginVO = new WXLoginVO();
            if (ToolUtil.isEmpty(appUser1.getPhone())) {
                wxLoginVO.setIsBind("0");
            } else {
                wxLoginVO.setIsBind("1");
            }
            wxLoginVO.setId(appUser1.getId());
            wxLoginVO.setToken(token);
            return ResultUtil.success(wxLoginVO);
        }else{
            if (appUser.getState() == 2) {
                return ResultUtil.errorLogin("登录失败,您的账号已被冻结!",null);
            }
            //生成token
            String token = JwtTokenUtil.generateToken(appUser.getPhone());
            System.err.println("token1111--->" + token);
            //存入缓存中
            addTokenToRedis(token, appUser.getId());
            WXLoginVO wxLoginVO = new WXLoginVO();
            if (ToolUtil.isEmpty(appUser.getPhone())) {
                wxLoginVO.setIsBind("0");
            } else {
                wxLoginVO.setIsBind("1");
            }
            wxLoginVO.setId(appUser.getId());
            wxLoginVO.setToken(token);
            return ResultUtil.success(wxLoginVO);
        }
    }
    /**
     * 将用户标识存入缓存中用于后期接口的身份校验
     * @param token
     * @param id
     */
    private void addTokenToRedis(String token, Integer id){
        String key = token;
        int length = token.length();
        if(length > 32){
            key = token.substring(token.length() - 32);
        }
        //30天有效期
        redisUtil.setStrValue(key, id.toString(), 2592000);
    }
    @Autowired
    private HWSendSms hwSendSms;
    @ResponseBody
    @PostMapping("/base/appUser/getSMSCode")
    @ApiOperation(value = "获取短信验证码", tags = {"APP-登录注册"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "类型(1:登录,2:注册,3:修改密码,4:忘记密码,5:修改绑定手机号)", name = "type", dataType = "int", required = true),
            @ApiImplicitParam(value = "电话号码", name = "phone", dataType = "string", required = true)
    })
    public ResultUtil getSMSCode(Integer type, String phone) {
        if (ToolUtil.isEmpty(phone)) {
            return ResultUtil.paranErr("phone");
        }
        if (ToolUtil.isEmpty(type)) {
            return ResultUtil.paranErr("type");
        }
        try {
            if (type == 2) {
                AppUser tAppUser = appUserService.selectOne(new EntityWrapper<AppUser>()
                        .eq("phone", phone).ne("state", 3));
                if (null != tAppUser) {
                    return ResultUtil.error("账号已存在");
                }
            }
            if (type == 5) {
                AppUser tAppUser = appUserService.selectOne(new EntityWrapper<AppUser>()
                        .eq("phone", phone).ne("state", 3));
                if (null != tAppUser) {
                    return ResultUtil.error("账号已存在");
                }
            }
            String numberRandom = UUIDUtil.getNumberRandom(6);
            String templateCode = "";
            if (type == 1 || type == 2) {
                templateCode = "SMS_161275250";
            }
            if (type == 3 || type == 4) {
                templateCode = "SMS_160960014";
            }
//            aLiSendSms.sendSms(phone, templateCode, "{\"code\":\"" + numberRandom + "\"}");
            hwSendSms.sendSms(numberRandom,phone);
            redisUtil.setStrValue(phone, numberRandom, 300);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
    @ResponseBody
    @GetMapping("/base/appUser/getAgreement")
    @ApiOperation(value = "协议", tags = {"协议"})
    @ApiImplicitParam(value = "类型(1:用户协议,2:隐私协议,3:注销协议,4:关于我们)", name = "type", dataType = "int", required = true)
    public ResultUtil<String> getAgreement(Integer type){
        Protocol type1 = protocolService.selectOne(new EntityWrapper<Protocol>()
                .eq("type", type));
        return ResultUtil.success(type1.getContent());
    }
    @ResponseBody
    @GetMapping("/base/appUser/getPage")
    @ApiOperation(value = "启动页/引导页", tags = {"协议"})
    @ApiImplicitParam(value = "类型(1:启动页,2:引导页(启动页多张图片逗号隔开))", name = "type", dataType = "int", required = true)
    public ResultUtil<String> getPage(Integer type){
        Page type1 = pageService.selectOne(new EntityWrapper<Page>()
                .eq("type", type));
        if (type1 == null){
            return ResultUtil.success("");
        }
        return ResultUtil.success(type1.getImg());
    }
}