package com.shining.cloud.controller.user;

import cn.hutool.core.util.StrUtil;
import com.njcn.enums.ProjectEnum;
import com.njcn.enums.app.ReturnCode;
import com.njcn.enums.app.UserCodeEnum;
import com.njcn.enums.app.UserLevelEnum;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.commons.ResponseData;
import com.njcn.pojo.user.AppUser;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.AESUtil;
import com.njcn.utils.PubUtils;
import com.njcn.utils.XssFilterUtil;
import com.njcn.utils.redis.JedisManager;
import com.shining.cloud.enums.AliMsgResponseEnum;
import com.shining.cloud.pojo.user.MessageResult;
import com.shining.cloud.pojo.user.UserResult;
import com.shining.cloud.service.user.AppUserService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author hongawen
 * @date: 2019/9/19 18:04
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户操作接口")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private AppUserService appUserService;

    @Resource
    private JedisManager jedisManager;

    /**
     * 获取（登录、注册、忘记密码、重新绑定手机）验证码
     */
    @PostMapping("authCode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "验证码类型", required = true, paramType = "query"),
    })
    @ApiOperation(value = "获取验证码", notes = "获取验证码", response = ResponseData.class)
    public ResponseData authCode(String phone, String devCode, String type, HttpServletRequest request) {
        ResponseData responseData;
        if (!PubUtils.patternPhone(XssFilterUtil.dealString(phone))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PHONE_WRONG.getCode(), UserCodeEnum.PHONE_WRONG.getMsg(), null);
        }
        //判断是否为黑客攻击
        if (judgeAttachInterface(devCode, request, phone)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.SEND_CODE_FAIL.getCode(), UserCodeEnum.SEND_CODE_FAIL.getMsg(), null);
        }
        System.out.println("获取验证码的请求信息,手机号:" + phone + ",设备码为：" + devCode);
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            appUserService.setMessage(phone, devCode, type);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.SEND_CODE_SUCCESS.getCode(), UserCodeEnum.SEND_CODE_SUCCESS.getMsg(), null);
        } catch (Exception e) {
            logger.error("发送短信异常，异常为：" + e.getMessage());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.SEND_CODE_FAIL.getCode(), UserCodeEnum.SEND_CODE_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }

    /***
     * 判断当前请求是否为黑客攻击
     * @author hongawen
     * @date 2023/8/25 11:07
     * @return boolean
     */
    private boolean judgeAttachInterface(String devCode, HttpServletRequest request, String phone) {
        boolean flag = false;
        //针对设备码
        if (judgeDevCode(devCode)) {
            flag = true;
            //判断手机号是否在黑名单
        } else if (judgeSmsPhone(phone)) {
            flag = true;
            //针对ip限制，避免盗刷
        } else if (judgeRequestIp(request)) {
            flag = true;
        }
        return flag;
    }

    /***
     * 紧急处理，后期app需要加上滑块移动验证
     * @author hongawen
     * 加上设备码限制，
     * 如果同一设备码72小时内超过6次，则立即返回
     * 如果72小时内超过30次，则彻底封杀该设备码
     */
    private boolean judgeDevCode(String devCode) {
        boolean flag = true;
        String valueByPhone = jedisManager.getValueByKey(RedisDB.CODE_DB, RedisDB.SMS_DEV_CODE.concat(devCode));
        int times = StrUtil.isBlank(valueByPhone) ? 0 : Integer.parseInt(valueByPhone);
        times++;
        if (times < 6) {
            //合理范围内，缓存
            flag = false;
            jedisManager.saveValueByKey(RedisDB.CODE_DB, RedisDB.SMS_DEV_CODE.concat(devCode), String.valueOf(times), RedisDB.THREE_DAYS);
        } else if (times < 30) {
            jedisManager.saveValueByKey(RedisDB.CODE_DB, RedisDB.SMS_DEV_CODE.concat(devCode), String.valueOf(times), RedisDB.THREE_DAYS);
        } else  {
            jedisManager.saveValueByKey(RedisDB.CODE_DB, RedisDB.SMS_DEV_CODE.concat(devCode), String.valueOf(times), -1);
        }
        return flag;
    }

    /***
     * 判断手机号是否在黑名单
     * @author hongawen
     * @date 2023/8/24 20:06
     * @param phone 手机号
     * @return boolean
     */
    private boolean judgeSmsPhone(String phone) {
        String valueByPhone = jedisManager.getValueByKey(RedisDB.CODE_DB, RedisDB.SMS_PHONE.concat(phone));
        return !StrUtil.isBlank(valueByPhone);
    }

    /***
     * 紧急处理，后期app需要加上滑块移动验证
     * @author hongawen
     * 加上ip限制，
     * 如果同一ip72小时内超过6次，则立即返回
     * 如果72小时内超过30次，则彻底封杀该ip
     */
    private boolean judgeRequestIp(HttpServletRequest request) {
        boolean flag = true;
        //获取过来的ip可能有多个，通过','分割后，取第一个，并且仅仅关心ip的前两个数据范围xxx.xxx.*.*；
        String clientIpAddress = PubUtils.getClientIpAddress(request);
        clientIpAddress = clientIpAddress.split(StrUtil.COMMA)[0];
//        clientIpAddress = clientIpAddress.substring(0, findNthCharacterIndex(clientIpAddress, StrUtil.C_DOT, 2));
        String ip = RedisDB.SMS_IP + clientIpAddress;
        String ipValue = jedisManager.getValueByKey(RedisDB.CODE_DB, ip);
        int times = StrUtil.isBlank(ipValue) ? 0 : Integer.parseInt(ipValue);
        logger.error("{}来获取短信验证码，最近72小时内，已经请求了{}次", ip, times);
        times++;
        if (times < 6) {
            //合理范围内，缓存
            flag = false;
            jedisManager.saveValueByKey(RedisDB.CODE_DB, ip, String.valueOf(times), RedisDB.THREE_DAYS);
        } else if (times < 30) {
            jedisManager.saveValueByKey(RedisDB.CODE_DB, ip, String.valueOf(times), RedisDB.THREE_DAYS);
        }else {
            jedisManager.saveValueByKey(RedisDB.CODE_DB, ip, String.valueOf(times), -1);
        }
        return flag;
    }

    /***
     * 查找ip前2个255详细信息
     * @author hongawen
     * @date 2023/8/25 9:59
     * @return int
     */
    public static int findNthCharacterIndex(String input, char targetChar, int n) {
        int count = 0;
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == targetChar) {
                count++;
                if (count == n) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * 手机app注册
     */
    @PostMapping("register")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
    })
    @ApiOperation(value = "注册入口", notes = "用户注册", response = ResponseData.class)
    public ResponseData register(String phone, String code, String devCode) {
        ResponseData responseData;
        //参数校验
        if (!PubUtils.patternPhone(XssFilterUtil.dealString(phone))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PHONE_WRONG.getCode(), UserCodeEnum.PHONE_WRONG.getMsg(), null);
        }
        if (StringUtils.isBlank(devCode)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.DEVCODE_WRONG.getCode(), UserCodeEnum.DEVCODE_WRONG.getMsg(), null);
        }
        UserResult userResult;
        logger.info("controller更新手机id：" + devCode);
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            userResult = appUserService.register(phone, code, devCode);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.REGIST_SUCCESS.getCode(), UserCodeEnum.REGIST_SUCCESS.getMsg(), userResult);
        } catch (Exception e) {
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.REGIST_FAIL.getCode(), UserCodeEnum.REGIST_FAIL.getMsg(), null);
            }
            logger.error("app用户注册异常：" + e.toString());
        }
        return responseData;
    }


    /**
     * 手机app密码设置
     */
    @PostMapping("setPsd")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户索引", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
    })
    @ApiOperation(value = "设置密码", notes = "设置密码", response = ResponseData.class)
    public ResponseData setPsd(String userId, String password, String devCode) {
        ResponseData responseData;
        //参数校验
        if (StringUtils.isBlank(userId)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.USERID_WRONG.getCode(), UserCodeEnum.USERID_WRONG.getMsg(), null);
        }
        if (!PubUtils.patternPasswordPhone(XssFilterUtil.dealString(password))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PASSWORD_WRONG.getCode(), UserCodeEnum.PASSWORD_WRONG.getMsg(), null);
        }
        if (StringUtils.isBlank(devCode)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.DEVCODE_WRONG.getCode(), UserCodeEnum.DEVCODE_WRONG.getMsg(), null);
        }
        logger.info("controller更新手机id：" + devCode);
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            appUserService.setPsd(userId, devCode, password);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.SETPWD_SUCCESS.getCode(), UserCodeEnum.SETPWD_SUCCESS.getMsg(), null);
        } catch (Exception e) {
            logger.error("app用户设置密码异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.SETPWD_FAIL.getCode(), UserCodeEnum.SETPWD_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }


    /**
     * 手机app登录入口
     */
    @PostMapping("login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "登录类型", required = true, paramType = "query"),
            @ApiImplicitParam(name = "key", value = "验证码/密码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
    })
    @ApiOperation(value = "登录入口", notes = "APP登录", response = ResponseData.class)
    public ResponseData login(String phone, String type, String key, String devCode, HttpServletRequest request) {
        ResponseData responseData;
        //参数校验
        if (!PubUtils.patternPhone(XssFilterUtil.dealString(phone))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PHONE_WRONG.getCode(), UserCodeEnum.PHONE_WRONG.getMsg(), null);
        }
        if (StringUtils.isBlank(key)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.KEY_WRONG.getCode(), UserCodeEnum.KEY_WRONG.getMsg(), null);
        }
        if (StringUtils.isBlank(devCode)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.DEVCODE_WRONG.getCode(), UserCodeEnum.DEVCODE_WRONG.getMsg(), null);
        }
        UserResult userResult = new UserResult();
        logger.info("controller更新手机id：" + devCode);
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            TokenManager.appLogin(phone, type, key, devCode, ProjectEnum.APP.getItem());
            AppUser appUser = (AppUser) SecurityUtils.getSubject().getPrincipal();
            userResult.setPhone(appUser.getPhone());
            userResult.setRoleCode(appUser.getUserLevel());
            userResult.setUserName(StringUtils.isEmpty(appUser.getName()) ? null : appUser.getName());
            userResult.setRoleName(UserLevelEnum.getMsgByCode(appUser.getUserLevel()));
            userResult.setUserId(appUser.getUserIndex());
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.LOGIN_SUCCESS.getCode(), UserCodeEnum.LOGIN_SUCCESS.getMsg(), userResult);
        } catch (Exception e) {
            logger.error("app用户登录异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.LOGIN_FAIL.getCode(), UserCodeEnum.LOGIN_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }

    /**
     * 手机app忘记密码-重置密码
     */
    @PostMapping("resetPsd")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
    })
    @ApiOperation(value = "重置密码", notes = "重置密码", response = ResponseData.class)
    public ResponseData resetPsd(String phone, String code, String password, String devCode) {
        ResponseData responseData;
        //参数校验
        if (!PubUtils.patternPhone(XssFilterUtil.dealString(phone))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PHONE_WRONG.getCode(), UserCodeEnum.PHONE_WRONG.getMsg(), null);
        }
        if (!PubUtils.patternPasswordPhone(XssFilterUtil.dealString(password))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PASSWORD_WRONG.getCode(), UserCodeEnum.PASSWORD_WRONG.getMsg(), null);
        }
        logger.info("controller更新手机id：" + devCode);
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            appUserService.resetPsd(phone, code, password, devCode);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.RESETPWD_SUCCESS.getCode(), UserCodeEnum.RESETPWD_SUCCESS.getMsg(), null);
        } catch (Exception e) {
            logger.error("忘记密码重置密码异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.RESETPWD_FAIL.getCode(), UserCodeEnum.RESETPWD_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }


    /**
     * 手机app已登录修改密码
     */
    @PostMapping("modifyPsd")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
    })
    @ApiOperation(value = "修改密码", notes = "修改密码", response = ResponseData.class)
    public ResponseData modifyPsd(String userId, String phone, String code, String password, String devCode) {
        ResponseData responseData;
        //参数校验
        if (!PubUtils.patternPasswordPhone(XssFilterUtil.dealString(password))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PASSWORD_WRONG.getCode(), UserCodeEnum.PASSWORD_WRONG.getMsg(), null);
        }
        logger.info("controller更新手机id：" + devCode);
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            appUserService.modifyPsd(userId, phone, code, password, devCode);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.RESETPWD_SUCCESS.getCode(), UserCodeEnum.RESETPWD_SUCCESS.getMsg(), null);
        } catch (Exception e) {
            logger.error("修改密码异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.RESETPWD_FAIL.getCode(), UserCodeEnum.RESETPWD_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }


    /**
     * 手机app角色升级
     */
    @PostMapping("roleUpdate")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "referralCode", value = "推荐码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
    })
    @ApiOperation(value = "角色升级", notes = "角色升级", response = ResponseData.class)
    public ResponseData roleUpdate(String userId, String referralCode, String devCode) {
        ResponseData responseData;
        //参数校验
        if (StringUtils.isEmpty(referralCode)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.REFERRAL_CODE_ERROR.getCode(), UserCodeEnum.REFERRAL_CODE_ERROR.getMsg(), null);
        }
        logger.info("controller更新手机id：" + devCode);
        UserResult userResult;
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            userResult = appUserService.roleUpdate(userId, referralCode, devCode);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.UPDATE_ROLE_SUCCESS.getCode(), UserCodeEnum.UPDATE_ROLE_SUCCESS.getMsg(), userResult);
        } catch (Exception e) {
            logger.error("角色升级异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.UPDATE_ROLE_FAIL.getCode(), UserCodeEnum.UPDATE_ROLE_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }

    /**
     * 手机app确认旧手机验证码
     */
    @PostMapping("comfirmCode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号码号码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "短信验证码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
    })
    @ApiOperation(value = "确认旧手机验证码", notes = "确认旧手机验证码", response = ResponseData.class)
    public ResponseData comfirmCode(String phone, String devCode, String code) {
        ResponseData responseData;
        //参数校验
        if (!PubUtils.patternPhone(XssFilterUtil.dealString(phone))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PHONE_WRONG.getCode(), UserCodeEnum.PHONE_WRONG.getMsg(), null);
        }
        if (StringUtils.isBlank(devCode)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.DEVCODE_WRONG.getCode(), UserCodeEnum.DEVCODE_WRONG.getMsg(), null);
        }
        logger.info("controller更新手机id：" + devCode);
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            appUserService.comfirmCode(phone, devCode, code);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.MESSAGE_CODE_RIGHT.getCode(), UserCodeEnum.MESSAGE_CODE_RIGHT.getMsg(), null);
        } catch (Exception e) {
            logger.error("确认旧手机验证码异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.MESSAGE_CODE_WRONG.getCode(), UserCodeEnum.MESSAGE_CODE_WRONG.getMsg(), null);
            }
        }
        return responseData;
    }


    /**
     * 手机app重新绑定手机号
     */
    @PostMapping("rebindPhone")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "phoneNew", value = "新号码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "短信验证码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备码", required = true, paramType = "query"),
    })
    @ApiOperation(value = "重新绑定手机号", notes = "重新绑定手机号", response = ResponseData.class)
    public ResponseData rebindPhone(String userId, String phoneNew, String devCode, String code) {
        ResponseData responseData;
        //参数校验
        if (!PubUtils.patternPhone(XssFilterUtil.dealString(phoneNew))) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.PHONE_WRONG.getCode(), UserCodeEnum.PHONE_WRONG.getMsg(), null);
        }
        if (StringUtils.isBlank(devCode)) {
            return PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.DEVCODE_WRONG.getCode(), UserCodeEnum.DEVCODE_WRONG.getMsg(), null);
        }
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            appUserService.rebindPhone(userId, phoneNew, devCode, code);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.REST_PHONE_SUCCESS.getCode(), UserCodeEnum.REST_PHONE_SUCCESS.getMsg(), null);
        } catch (Exception e) {
            logger.error("重新绑定手机号异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.REST_PHONE_FAIL.getCode(), UserCodeEnum.REST_PHONE_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }


    /**
     * 手机app用户实时消息配置
     */
    @PostMapping("msgSet")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "eventInfo", value = "暂态消息模块", required = true, paramType = "query"),
            @ApiImplicitParam(name = "targetInfo", value = "稳态消息模块", required = true, paramType = "query"),
            @ApiImplicitParam(name = "deviceInfo", value = "终端消息模块", required = true, paramType = "query"),
            @ApiImplicitParam(name = "systemInfo", value = "系统消息消息模块", required = true, paramType = "query"),
    })
    @ApiOperation(value = "用户实时消息配置", notes = "用户实时消息配置", response = ResponseData.class)
    public ResponseData msgSet(String userId, String eventInfo, String targetInfo, String deviceInfo, String systemInfo) {
        ResponseData responseData;
        try {
            appUserService.msgSet(userId, eventInfo, targetInfo, deviceInfo, systemInfo);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.SET_INFO_SUCCESS.getCode(), UserCodeEnum.SET_INFO_SUCCESS.getMsg(), null);
        } catch (Exception e) {
            logger.error("用户实时消息配置异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.SET_INFO_FAIL.getCode(), UserCodeEnum.SET_INFO_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }

    /**
     * 手机app用户获取消息配置
     */
    @PostMapping("getMsg")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "devCode", value = "设备ID", required = true, paramType = "query"),
    })
    @ApiOperation(value = "用户获取消息配置", notes = "用户获取消息配置", response = ResponseData.class)
    public ResponseData getMsg(String userId, String devCode) {
        ResponseData responseData;
        MessageResult messageResult;
        try {
            devCode = AESUtil.aesPKCS5PaddingDecrypt(devCode);
            messageResult = appUserService.getMsg(userId, devCode);
            responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_SUCCESS, UserCodeEnum.GET_MESSAGE_SUCCESS.getCode(), UserCodeEnum.GET_MESSAGE_SUCCESS.getMsg(), messageResult);
        } catch (Exception e) {
            logger.error("用户获取消息配置异常：" + e.toString());
            if (e.getMessage().length() < 10) {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.getCodeByMsg(e.getMessage()), e.getMessage(), null);
            } else {
                responseData = PubUtils.assignmentAppResponse(ReturnCode.RETURN_FAIL, UserCodeEnum.GET_MESSAGE_FAIL.getCode(), UserCodeEnum.GET_MESSAGE_FAIL.getMsg(), null);
            }
        }
        return responseData;
    }


}
