package com.github.wxiaoqi.security.admin.rpc.service;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.biz.AppUserBiz;
import com.github.wxiaoqi.security.admin.biz.AppUserDetailBiz;
import com.github.wxiaoqi.security.admin.biz.AppUserLoginBiz;
import com.github.wxiaoqi.security.admin.biz.ElementBiz;
import com.github.wxiaoqi.security.admin.constant.RedisKey;
import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.api.vo.authority.PermissionInfo;
import com.github.wxiaoqi.security.api.vo.user.AppUserInfo;
import com.github.wxiaoqi.security.common.msg.BaseResponse;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.EmojiFilter;
import com.github.wxiaoqi.security.common.util.VerificationUtils;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.github.wxiaoqi.security.common.util.result.JsonResultUtil;
import com.xxfc.platform.activity.Feign.ActivityFeign;
import com.xxfc.platform.im.feign.ImFeign;
import com.xxfc.platform.universal.feign.ThirdFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author keliii
 */
@Service
@Slf4j
public class AppPermissionService {

    @Autowired
    AppUserBiz appUserBiz;

    @Autowired
    ElementBiz elementBiz;

    @Autowired
    ThirdFeign thirdFeign;

    @Autowired
    ImFeign imFeign;

    @Autowired
    ActivityFeign activityFeign;

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);
    @Autowired
    private RedisTemplate userRedisTemplate;
    @Autowired
    private AppUserDetailBiz appUserDetailBiz;
    @Autowired
    private AppUserLoginBiz appUserLoginBiz;


    public AppUserInfo validate(String username, String password) {
        AppUserInfo info = new AppUserInfo();
        AppUserLogin user = appUserLoginBiz.checkeUserLogin(username);
        if (user != null && encoder.matches(password, user.getPassword())) {
            info.setUsername(user.getUsername());
            info.setId(user.getId() + "");
        }
        return info;
    }

    public List<PermissionInfo> getPermissionByUsername(String username) {
        AppUser user = appUserBiz.getUserByUsername(username);
        List<PermissionInfo> result = new ArrayList<>();
//        List<Element> elements = elementBiz.getAuthorityElementByUserId(user.getId().toString());
        List<Element> elements = elementBiz.getAuthorityElementByAppUserId(user.getId().toString());
        element2permission(result, elements);
        return result;
    }

    private void element2permission(List<PermissionInfo> result, List<Element> elements) {
        PermissionInfo info;
        for (Element element : elements) {
            info = new PermissionInfo();
            info.setCode(element.getCode());
            info.setType(element.getType());
            info.setUri(element.getUri());
            info.setMethod(element.getMethod());
            info.setName(element.getName());
            info.setMenu(element.getMenuId());
            result.add(info);
        }
    }


    /**
     * 发送短信
     *
     * @param phone
     * @param type
     * @return phone手机号 type:类型(0用户注册,1微信绑定,2人脸注册,3忘记密码,4直接发送验证码) 改写发送验证码方法（暂时通过测试）
     */

    public JSONObject sendSMS(String phone, Integer type) {
        if (StringUtils.isBlank(phone) || type == null) {
            return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        // 验证手机号码是否正确
        if (!VerificationUtils.getPvu().checkMobileNumber(phone)) {
            return JsonResultUtil.createFailedResult(ResultCode.FAILED_CODE, "手机号码有误");
        }
        // 组织返回结果集
        JSONObject result = new JSONObject();
        if (type == 0) {
            AppUserLogin rsUserLogin = appUserLoginBiz.checkeUserLogin(phone);
            if (rsUserLogin != null)
                return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "用户已存在");
        } else if (type == 1) {
            AppUserLogin rsUserLogin = appUserLoginBiz.checkeUserLogin(phone);

            // 判断手机号码是否已绑定
            boolean isBind = appUserLoginBiz.checkeWechatUser(rsUserLogin);
            if (!isBind) {
                return JsonResultUtil.createFailedResultMsg(ResultCode.WX_BIND_CODE);
            } else {
                result.put("registered", rsUserLogin != null);
            }
        }/* else if (type == 3) {
            if (checkeUserLogin(phone) == null)
                return JsonResultUtil.createFailedResult(ResultCode.FAILED_CODE, "手机号未注册，请确认手机号无误");
        }*/ else if (type == 4) {
            AppUserLogin rsUserLogin = appUserLoginBiz.checkeUserLogin(phone);
            if (rsUserLogin == null)
                return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "手机号未注册");
        }
        // String sms = PassportUtil.SendSMS(phone, SystemConfig.SENDSMS_TITLE);
        String mobilecode = null;
        JSONObject data = thirdFeign.send(phone);
        if (data != null && data.getInteger("status") == ResultCode.SUCCESS_CODE) {
            mobilecode = data.getString("data");
        }
        log.info("调用短信发送接口返回值为：{}", mobilecode);
        // 判断返回值是否为空，并且是否可以转换成JSONObject
        if (StringUtils.isBlank(mobilecode))
            return JsonResultUtil.createDefaultFail();
        try {
            result.put("mobilecode", mobilecode);
            String redisLockKey = RedisKey.CONSTANT_CODE_PREFIX + phone + mobilecode;
            Boolean suc = userRedisTemplate.opsForValue().setIfAbsent(redisLockKey, mobilecode);
            if (suc) {
                userRedisTemplate.expire(redisLockKey, 5, TimeUnit.MINUTES);//5分钟内过期
            }
        } catch (Exception e) {
            return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
        return JsonResultUtil.createSuccessResultWithObj(result);
    }

    /**
     * 注册用户
     *
     * @param username
     * @param password
     * @param headimgurl
     * @param mobilecode
     */
    @Transactional
    public JSONObject register(String username, String password, String headimgurl,
                               String nickname, String mobilecode, String openId, String unionid, Integer type) {
        // 判断参数和验证码
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(mobilecode)) {
            return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        String redisLockKey = RedisKey.CONSTANT_CODE_PREFIX + username + mobilecode;
        String mobilecodeRedis = userRedisTemplate.opsForValue().get(redisLockKey) == null ? "" : userRedisTemplate.opsForValue().get(redisLockKey).toString();
        log.error("注册接口，获取redis中的验证码：" + mobilecodeRedis);
        // 获取到缓存的验证码后要先清空缓存对应键的值
        userRedisTemplate.delete(redisLockKey);
        if (StringUtils.isBlank(mobilecodeRedis)) {
            return JsonResultUtil.createFailedResult(ResultCode.NOTEXIST_CODE, "验证码错误");
        }
        // 是否已存在
        AppUserLogin user = appUserLoginBiz.checkeUserLogin(username);
        if (null != user) {
            return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "用户已存在");
        }
        // 新增用户登录信息
        try {
            Long now = System.currentTimeMillis() / 1000;
            AppUserLogin appUserLogin = new AppUserLogin();
            appUserLogin.setUsername(username);
            appUserLogin.setPassword(password);
            appUserLogin.setIsdel(0);
            appUserLogin.setStatus(0);
            //QQ
            if (type == 1 && StringUtils.isNotBlank(openId)) {
                appUserLogin.setOpenid(openId);
            } else {
                if (StringUtils.isNotBlank(openId)) {
                    appUserLogin.setWxOpenid(openId);
                }
                if (StringUtils.isNotBlank(unionid)) {
                    appUserLogin.setUnionid(unionid);
                }
            }
            appUserLogin.setCreatetime(now);
            appUserLogin.setUpdatetime(now);
            appUserLoginBiz.insertSelective(appUserLogin);
            Integer userid = appUserLogin.getId();
            log.error("注册：新增登陆用户信息： " + userid);
            // 新增用户详情
            AppUserDetail rsUserDetail = new AppUserDetail();
            rsUserDetail.setUserid(userid);
            rsUserDetail.setNickname(nickname);
            rsUserDetail.setHeadimgurl(headimgurl); // 默认路径，待写
            rsUserDetail.setCreatetime(now);
            rsUserDetail.setUpdatetime(now);
            rsUserDetail.setIsdel(0);
            appUserDetailBiz.insertSelective(rsUserDetail);
            log.error("注册：新增用户详情： " + userid);
             //自动登录获取优惠卷
            authCoupn(userid);
            // 登录结果要做做统一处理
            JSONObject data = autoLogin(userid, username, headimgurl, nickname);
            // 到im注册，获取返回结果
            Map<String,Object> map=registerIm(username,appUserLogin.getPassword(),nickname);
            if(map!=null){
                Integer imUserId=Integer.parseInt(map.get("userId").toString());
                String access_token=map.get("access_token").toString();
                String imPassword=map.get("password").toString();
                if(imUserId!=null&&imUserId>0&&StringUtils.isNotBlank(imPassword)){
                    AppUserLogin userLogin = new AppUserLogin();
                    userLogin.setId(userid);
                    userLogin.setImPassword(imPassword);
                    userLogin.setImUserid(imUserId);
                    userLogin.setUsername(username);
                    appUserLoginBiz.updateSelectiveById(userLogin);
                    log.info(username+"----userLogin updateSelectiveById---username====="+username+"----imPassword===="+imPassword);
                }
                data.put("imToken",access_token);
                data.put("imUserId",imUserId);
            }
            if (data != null) {
                return JsonResultUtil.createSuccessResultWithObj(data);
            } else {
                return JsonResultUtil.createDefaultFail();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
    }

    /**
     * 自动登录
     */
    public JSONObject autoLogin(Integer userid, String username, String headimgurl, String nickname) {
        JSONObject data = new JSONObject();
        AppUserLogin userLoign = appUserLoginBiz.selectById(userid);
        if (userLoign != null) {
            data.put("nickname", nickname);
            data.put("headerurl", headimgurl);
            AppUserVo userVo = appUserDetailBiz.getUserInfoById(userid);
            if (userVo != null) {
                if (StringUtils.isNotBlank(userVo.getNickname())) {
                    data.put("nickname", userVo.getNickname());
                }
                if (StringUtils.isNotBlank(userVo.getHeadimgurl())) {
                    data.put("headerurl", userVo.getHeadimgurl());
                }
                data.put("certificationStatus", userVo.getCertificationStatus());
            }
            // 缓存操作
            String token = "";
            String imtoken_ = "";
            //userRedisTemplate.opsForValue().set("token_" + userid,token, SystemConfig.REDISTOKENTIME, TimeUnit.SECONDS);
            //userRedisTemplate.opsForValue().set("imtoken_" + userid,imtoken_,SystemConfig.REDISTOKENTIME, TimeUnit.SECONDS);
            // 返回结果
            // data.put("token", token);
            data.put("username", StringUtils.isNotEmpty(username)?username:userLoign.getUsername());
            data.put("userId", userid);

        }
        return data;
    }

    /**
     * 微信绑定/注册
     *
     * @param username
     * @param password
     * @param openId
     * @param unionid
     * @param nickname
     * @param headimgurl
     * @param type
     * @param mobilecode
     * @return
     */
    @Transactional
    public JSONObject weCahtRegister(String username, String password, String openId,
                                     String unionid, String nickname, String headimgurl, int type, String mobilecode, Integer isQQ) {
        // 校验参数和验证码
        if (StringUtils.isBlank(username) || StringUtils.isBlank(mobilecode)) {
            return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        if (type == 2) {
            if (StringUtils.isBlank(password)) {
                return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "密码不能为空");
            }
        }
        try {
            // 获取缓存用户信息
            log.error("weCahtRegister:" + openId);
            if (StringUtils.isNotBlank(openId)) {
                if (StringUtils.isNotBlank(nickname)) {
                    // 转换特殊字符
                    nickname = EmojiFilter.filterEmoji(nickname);
                }
                log.error("微信昵称=" + nickname);
                // 微信用户未设置头像时，默认头像
                if (StringUtils.isBlank(headimgurl)) {
                    headimgurl = SystemConfig.USER_HEADER_URL_DEFAULT;
                }
                if (type == 1) { // 绑定
                    Long now = System.currentTimeMillis() / 1000;
                    AppUserLogin userLogin = appUserLoginBiz.checkeUserLogin(username);
                    if ((isQQ == 1 && StringUtils.isNotBlank(userLogin.getOpenid())) || (isQQ == 0 && StringUtils.isNotBlank(userLogin.getWxOpenid()))) {
                        // 已绑定微信
                        return JsonResultUtil.createFailedResultMsg(ResultCode.WX_BIND_CODE);
                    }
                    Integer userid = userLogin.getId();
                    if (isQQ == 1) {
                        userLogin.setOpenid(openId);
                    } else {
                        userLogin.setWxOpenid(openId);
                        // 添加unionid
                        userLogin.setUnionid(unionid);
                    }
                    userLogin.setUpdatetime(now);
                    appUserLoginBiz.updateSelectiveById(userLogin);
                    AppUserVo userVo = appUserDetailBiz.getUserInfoById(userid);
                    AppUserDetail  userDetail = new AppUserDetail();
                    if (userVo == null) {
                        userDetail.setUserid(userid);
                        userDetail.setHeadimgurl(headimgurl);
                        userDetail.setNickname(nickname);
                        userDetail.setCreatetime(now);
                        userDetail.setUpdatetime(now);
                        userDetail.setIsdel(0);
                        appUserDetailBiz.insertSelective(userDetail);
                    } /*else {
                        userDetail.setId(userVo.getId());
                        userDetail.setHeadimgurl(headimgurl);
                        userDetail.setNickname(nickname);
                        appUserDetailBiz.updateSelectiveById(userDetail);
                    }*/
                    // 登录结果要做做统一处理
                    JSONObject data = autoLogin(userid, username, headimgurl, nickname);
                    // 到im注册，获取返回结果
                    Integer  imUserId=userLogin.getImUserid();
                    String imPassword=userLogin.getImPassword();
                    if(StringUtils.isNotBlank(imPassword)&&imUserId!=null&&imUserId>0){
                        String  access_token=loginIm(username,imPassword,imUserId);
                        data.put("imToken",access_token);
                        data.put("imUserId",imUserId);
                    }
                    if (data != null) {
                        return JsonResultUtil.createSuccessResultWithObj(data);
                    }
                } else if (type == 2) { // 新增
                    JSONObject register = register(username, password, headimgurl, nickname, mobilecode,
                            openId, unionid, isQQ);
                    if (register.getInteger("status") != ResultCode.SUCCESS_CODE) {
                        if (register.getInteger("status") == ResultCode.EXIST_CODE) {
                            return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "用户已存在");
                        }
                        return JsonResultUtil.createFailedResult(register.getInteger("code"), "操作失败");
                    }
                    return register;

                }
            }
            return JsonResultUtil.createDefaultFail();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }

    }

    /**
     * 校验手机号码是否已绑定微信
     *
     * @param username
     * @return
     */

    public JSONObject checkBindWechat(String username) {
        JSONObject data = new JSONObject();
        try {
            AppUserLogin userLogin = appUserLoginBiz.checkeUserLogin(username);
            if (userLogin != null) {
                String openid = userLogin.getOpenid();
                if (StringUtils.isNotBlank(openid)) {
                    data.put("type", 0); // 已存在
                } else {
                    data.put("type", 1); // 绑定
                }
            } else {
                data.put("type", 2); // 新增
            }
            return JsonResultUtil.createSuccessResultWithObj(data);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
    }

    /**
     * 微信登录
     *
     * @param openId
     * @return
     */
    @Transactional
    public JSONObject weCahtLogin(String openId, Integer isQQ) {
        if (StringUtils.isBlank(openId)) {
            return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        AppUserLogin userLogin = appUserLoginBiz.getUserByOpenid(openId, isQQ);
        if (userLogin == null) {
            return JsonResultUtil.createFailedResult(ResultCode.WXNOTEXIST_CODE, "该微信号尚未绑定手机号");
        }
        if (userLogin.getStatus() == 1) {
            return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "用户已被禁用");
        }
        Integer userid = userLogin.getId();
        AppUserVo userVo = appUserDetailBiz.getUserInfoById(userid);
        String headimgurl = "";
        String nickname = "";
        if (userVo != null) {
            headimgurl = userVo.getHeadimgurl();
            nickname = userVo.getNickname();
        }
        JSONObject data = autoLogin(userid, userLogin.getUsername(), headimgurl, nickname);
        // 到im注册，获取返回结果
        Integer  imUserId=userLogin.getImUserid();
        String imPassword=userLogin.getImPassword();
        if(StringUtils.isNotBlank(imPassword)&&imUserId!=null&&imUserId>0){
            String  access_token=loginIm(userLogin.getUsername(),imPassword,imUserId);
            data.put("imToken",access_token);
            data.put("imUserId",imUserId);
        }
        if (data != null) {
            return JsonResultUtil.createSuccessResultWithObj(data);
        }
        return JsonResultUtil.createDefaultFail();
    }

    public JSONObject login(String username, String password, String mobilecode, int type) {
        if (StringUtils.isBlank(username) || ((StringUtils.isBlank(password) && type == 1) || (StringUtils.isBlank(mobilecode) && type == 2))) {
            return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "请求参数为空");
        }
        try {
            AppUserLogin user = appUserLoginBiz.checkeUserLogin(username);
            if (type == 1) {
                if (user == null || !encoder.matches(password, user.getPassword()))
                    return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "用户名或密码错误");
            } else {
                String redisLockKey = RedisKey.CONSTANT_CODE_PREFIX + username + mobilecode;
                String mobilecodeRedis = userRedisTemplate.opsForValue().get(redisLockKey) == null ? "" : userRedisTemplate.opsForValue().get(redisLockKey).toString();
                log.error("验证码登录接口，获取redis中的验证码：" + mobilecodeRedis);
                // 获取到缓存的验证码后要先清空缓存对应键的值
                userRedisTemplate.delete(redisLockKey);
                if (StringUtils.isBlank(mobilecodeRedis))
                    return JsonResultUtil.createFailedResult(ResultCode.NOTEXIST_CODE, "验证码错误");
                if (user == null)
                    return JsonResultUtil.createFailedResult(ResultCode.NOTEXIST_CODE, "用户不存在");

            }
            // 判断是否禁用
            if (user.getStatus() == 1) {
                return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "用户已被禁用");
            }
            Integer userid = user.getId();
            String nickname = SystemConfig.USER_NIKENAME_DEFAULT + (int) ((Math.random() * 9 + 1) * 100000);
            JSONObject data = autoLogin(userid, user.getUsername(), SystemConfig.USER_HEADER_URL_DEFAULT, nickname);
            // 到im注册，获取返回结果
            Integer  imUserId=user.getImUserid();
            String imPassword=user.getImPassword();
            if(StringUtils.isNotBlank(imPassword)&&imUserId!=null&&imUserId>0){
                String  access_token=loginIm(username,imPassword,imUserId);
                data.put("imToken",access_token);
                data.put("imUserId",imUserId);
            }
            if (data != null) {
                return JsonResultUtil.createSuccessResultWithObj(data);
            }
            return JsonResultUtil.createDefaultFail();
        } catch (Exception e) {
            log.error("userlogin->error:{}", e.getMessage(), e);
            return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
    }

    @Transactional
    public JSONObject reset(String username, String mobilecode, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(mobilecode) || StringUtils.isBlank(password)) {
            return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "请求参数为空");
        }
        try {
            String redisLockKey = RedisKey.CONSTANT_CODE_PREFIX + username + mobilecode;
            String mobilecodeRedis = userRedisTemplate.opsForValue().get(redisLockKey) == null ? "" : userRedisTemplate.opsForValue().get(redisLockKey).toString();
            log.error("验证码登录接口，获取redis中的验证码：" + mobilecodeRedis);
            // 获取到缓存的验证码后要先清空缓存对应键的值
            userRedisTemplate.delete(redisLockKey);
            if (StringUtils.isBlank(mobilecodeRedis)) {
                return JsonResultUtil.createFailedResult(ResultCode.NOTEXIST_CODE, "验证码错误");
            }
            AppUserLogin user = appUserLoginBiz.checkeUserLogin(username);
            if (user == null) {
                return JsonResultUtil.createFailedResult(ResultCode.NOTEXIST_CODE, "用户不存在");
            }
            user.setPassword(password);
            appUserLoginBiz.updatePasswordById(user);
            Integer userid = user.getId();
            String nickname = SystemConfig.USER_NIKENAME_DEFAULT + (int) ((Math.random() * 9 + 1) * 100000);
            JSONObject data = autoLogin(userid, user.getUsername(), SystemConfig.USER_HEADER_URL_DEFAULT, nickname);
            // 到im注册，获取返回结果
            Integer  imUserId=user.getImUserid();
            String imPassword=user.getImPassword();
            if(StringUtils.isNotBlank(imPassword)&&imUserId!=null&&imUserId>0){
                String  access_token=loginIm(username,imPassword,imUserId);
                data.put("imToken",access_token);
                data.put("imUserId",imUserId);
            }
            if (data != null) {
                return JsonResultUtil.createSuccessResultWithObj(data);
            }
            return JsonResultUtil.createDefaultFail();
        } catch (Exception e) {
            log.error("userlogin->error:{}", e.getMessage(), e);
            return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
    }

    //实名认证
    @Transactional
    public ObjectRestResponse upAuthentication(Integer userid, String name,String idNumber, Integer status) {
        log.error("userid===="+userid+"-----name===="+name+"----idNumber==="+idNumber+"---status==="+status);
        if (userid == null || userid == 0 || (status == 1 && StringUtils.isBlank(idNumber)&& StringUtils.isBlank(name))) {
            return ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        try {
            AppUserVo userVo = appUserDetailBiz.getUserInfoById(userid);
            if (userVo == null) {
                return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "用户不存在");
            }
            if (userVo.getCertificationStatus() == 1) {
                return ObjectRestResponse.createFailedResultWithObj(ResultCode.EXIST_CODE, "用户已认证", userVo.getIdNumber());
            }
            if (status == 1) {
                String username=userVo.getUsername();
                AppUserLogin user = new AppUserLogin();
                user.setId(userid);
                user.setUsername(username);
                user.setIdNumber(idNumber);
                user.setCertificationStatus(1);
                appUserLoginBiz.updateSelectiveById(user);
                if(StringUtils.isBlank(userVo.getRealname())){
                    Integer id=userVo.getId();
                    userVo=new AppUserVo();
                    userVo.setId(id);
                    userVo.setUserid(userid);
                    userVo.setRealname(name);
                    appUserDetailBiz.updUuserInfoById(userVo);
                }

            }
            return ObjectRestResponse.succ();
        } catch (Exception e) {
            log.error("upAuthentication->error:{}", e.getMessage(), e);
            return ObjectRestResponse.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }

    }

    //注册im
    public Map<String, Object> registerIm(String username, String password, String nickname) {
        log.error("------注册registerIm----username====="+username+"-----password==="+password+"---nickname==="+nickname);
        Map<String, Object> map = new HashMap<>();
        map.put("telephone", username);
        map.put("password", password);
        map.put("nickname", nickname);
        BaseResponse response = imFeign.register(map);
        log.error("registerIm->response:{}", response);
        if (response.getStatus() == ResultCode.SUCCESS_CODE) {
            String result = response.getMessage();
            log.error("------im注册----result======"+result);
            if (StringUtils.isNotBlank(result)) {
                JSONObject object = JSONObject.parseObject(result);
                password = object.getString("password");
                if (StringUtils.isNotBlank(result)) {
                    map.put("password", password);
                }
                JSONObject data = object.getJSONObject("data");
                log.error("------im注册----data======"+data);
                if (data != null) {
                    map.put("userId", data.getString("userId"));
                    map.put("access_token", data.getString("access_token"));
                } else {
                    map.put("userId", "");
                    map.put("access_token", "");
                }
            }
        }
        return map;

    }

    //登录im

    public String loginIm(String username, String password, Integer userId) {
        log.error("------登录loginIm----username====="+username+"-----password==="+password+"---userId==="+userId);
        Map<String, Object> map = new HashMap<>();
        map.put("telephone", username);
        map.put("password", password);
        map.put("userId", userId);
        BaseResponse response = imFeign.login(map);
        log.error("registerIm->response:{}", response);
        String access_token = "";
        if (response.getStatus() == ResultCode.SUCCESS_CODE) {
            String result = response.getMessage();
            log.error("------im登录----result======"+result);
            if (StringUtils.isNotBlank(result)) {
                JSONObject object = JSONObject.parseObject(result);
                JSONObject data = object.getJSONObject("data");
                log.error("------im登录----data======"+data);
                if (data != null) {
                    access_token = data.getString("access_token");
                }
            }
        }
        log.error("------im登录----access_token======"+access_token);
        return access_token;
    }
    //自动领取新人优惠卷
    public  String authCoupn(Integer userId){
        return  activityFeign.led(userId);
    }


    /**
     * 通过用户id登录*** Unbelievable! ! !
     * @param uid
     * @return
     */
    public JSONObject appletLoginByUserId(Integer uid) {
        JSONObject data = autoLogin(uid, null, null, null);
        if (data!=null){
            return JsonResultUtil.createSuccessResultWithObj(data);
        }
        return JsonResultUtil.createFailedResult(ResultCode.NOTEXIST_CODE, "用户不存在");
    }


    /**
     * 小程序注册用户
     *
     * @param username
     * @param password
     * @param headimgurl
     * @param nickname
     */
    @Transactional
    public JSONObject applyRegister(String username, String password, String headimgurl,String nickname) {
        // 判断参数
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        // 是否已存在
        AppUserLogin user = appUserLoginBiz.checkeUserLogin(username);
        if (null != user) {
            return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "用户已存在");
        }
        // 新增用户登录信息
        try {
            Long now = System.currentTimeMillis() / 1000;
            AppUserLogin appUserLogin = new AppUserLogin();
            appUserLogin.setUsername(username);
            appUserLogin.setPassword(password);
            appUserLogin.setIsdel(0);
            appUserLogin.setStatus(0);
            appUserLogin.setCreatetime(now);
            appUserLogin.setUpdatetime(now);
            appUserLoginBiz.insertSelective(appUserLogin);
            Integer userid = appUserLogin.getId();
            log.error("注册：新增登陆用户信息： " + userid);
            // 新增用户详情
            AppUserDetail rsUserDetail = new AppUserDetail();
            rsUserDetail.setUserid(userid);
            rsUserDetail.setNickname(nickname);
            rsUserDetail.setHeadimgurl(headimgurl); // 默认路径，待写
            rsUserDetail.setCreatetime(now);
            rsUserDetail.setUpdatetime(now);
            rsUserDetail.setIsdel(0);
            appUserDetailBiz.insertSelective(rsUserDetail);
            log.error("注册：新增用户详情： " + userid);
            //自动登录获取优惠卷
            authCoupn(userid);
            //发送短信通知用户
            thirdFeign.sendCode(username,password,SystemConfig.TEMPLATECODE);
            // 登录结果要做做统一处理
            JSONObject data = autoLogin(userid, username, headimgurl, nickname);
            // 到im注册，获取返回结果
            Map<String,Object> map=registerIm(username,appUserLogin.getPassword(),nickname);
            if(map!=null){
                Integer imUserId=Integer.parseInt(map.get("userId").toString());
                String access_token=map.get("access_token").toString();
                String imPassword=map.get("password").toString();
                if(imUserId!=null&&imUserId>0&&StringUtils.isNotBlank(imPassword)){
                    AppUserLogin userLogin = new AppUserLogin();
                    userLogin.setId(userid);
                    userLogin.setImPassword(imPassword);
                    userLogin.setImUserid(imUserId);
                    userLogin.setUsername(username);
                    appUserLoginBiz.updateSelectiveById(userLogin);
                    log.info(username+"----userLogin updateSelectiveById---username====="+username+"----imPassword===="+imPassword);
                }
                data.put("imToken",access_token);
                data.put("imUserId",imUserId);
            }
            if (data != null) {

                return JsonResultUtil.createSuccessResultWithObj(data);
            } else {
                return JsonResultUtil.createDefaultFail();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
    }



    /**
     *通过小程序注册
     * @param username
     * @return
     */
    public JSONObject appletRegistry(String username,String headimgurl,String nickname ){

        try {
            // 是否已存在
            AppUserLogin user = appUserLoginBiz.checkeUserLogin(username);
            JSONObject data=new JSONObject();
            if (null == user) {
                String password="12345678";
                data=applyRegister(username,password,headimgurl,nickname);
            }else{
                data=appletLoginByUserId(user.getId());
            }
           return  data;
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
        }
    }
}
