package com.bcxin.ins.coninsweb.user.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.dto.oauth.AccessToken;
import com.bcxin.ins.service.common.ModelSendService;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.service.oauth.OAuthService;
import com.bcxin.ins.service.order.InsCommonReportAPIService;
import com.bcxin.ins.service.user.ClientUserService;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.core.service.SysRoleService;
import com.bcxin.ins.dto.ResultDto;
import com.bcxin.ins.entity.user.SysClientUser;
import com.bcxin.ins.spring.annotation.OperationLog;
import com.bcxin.ins.spring.listener.SessionContext;
import com.bcxin.ins.spring.util.JedisUtils;
import com.bcxin.ins.util.*;
import com.bcxin.ins.util.email.EmailModel;
import com.bcxin.ins.util.email.EmailMsgType;
import com.bcxin.ins.util.email.MessageModel;
import com.bcxin.ins.util.email.SendEmailAndMsgUtil;
import com.bcxin.ins.util.http.HuaWeiSmsContent;
import com.bcxin.ins.vo.ClientUserVo;
import com.bcxin.ins.vo.ConstProp;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户信息
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {



    //@SessionAttributes({"userdto","com_organizingPath","com_businessPath","com_taxPath","cityN","userVo"})

    @Autowired
    private ClientUserService userService;


    @Autowired
    private OAuthService oAuthService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private ModelSendService mss;
    @Autowired
    private InsCommonReportAPIService insCommonReportAPIService;







    /**
     * 有在用
     * 保存用户（个人或者企业）
     */
    @RequestMapping("/registerSava/{code}")
    @OperationLog(source = OperationLog.SOURCETYPE.FRONT,title ="【请求】首页-注册")
    @ResponseBody
    public ResultDto registerSava(@PathVariable String code, HttpServletRequest request) {
        String email = request.getParameter("email");
        //查询该用户是否存在
        boolean flag=false;
        String keyyh = ConstProp.YHM_EN+email+"_"+IpAddress.getIpAddress(getRequest());
        String emailAgain=JedisUtils.get(keyyh);
//        String emailAgain=request.getSession().getAttribute("email")==null?null:request.getSession().getAttribute("email").toString();
        if(!email.equals(emailAgain)){
            return new ResultDto("请输入正确的手机号码！", "301",ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
        if(ConstProp.DIGIT_ONE.equals(code)){
            //手机注册
            flag= userService.getUserMobileForRegister(email,Constant.WEB_TYPE_COINS);
        }else if(ConstProp.DIGIT_TWO.equals(code)){
            //邮箱注册
            flag= userService.getUserEmailForRegister(email,Constant.WEB_TYPE_COINS);
        }
        if(flag){
            ClientUserVo vo =null;    //个人用户里面  个人账户/企业账户
            //再这里需要先判断下 用户是否存在 存在就修改
            vo= userService.getClientUserVo(email,MathUtil.getType(email));
            if(vo==null){
                vo= new ClientUserVo();
            }
            String  password= request.getParameter("password");
            //需要去调用支撑的保存接口
            vo.setPassword(Sha1Util.entryptPassword(password));
            vo.setTerminal_type(code);
            if(Constant.TERMINAL_TYPE_COMMON.equals(code)){
                vo.setRole_id("3");//设置角色权限
                vo.setRole_name("COMMON-ZERO-HEAD");
                vo.setTelephone(email);
            }else if(Constant.TERMINAL_TYPE_COMPANY.equals(code)){
                vo.setRole_id(ConstProp.DIGIT_ONE);//设置角色权限
                vo.setRole_name("COMMON-ONE-HEAD");
                vo.setEmail(email);
            }
            boolean userflag=userService.saveClientUserVo(vo);
            if(userflag){
                return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }else{
                return new ResultDto("注册失败！！", "301",ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }


        }else{
            return new ResultDto("账号已存在", "301",ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }

    }














    /**
     * 有在用
     * <b>业务逻辑处理，验证码校验(图片验证码) </b>
     */
    @RequestMapping("/register/checkYzm")
    @ResponseBody
    public ResultDto checkYzm(@RequestParam String captcha) {
        String key = ConstProp.YZM_EN+IpAddress.getIpAddress(getRequest());
        String sessionyanz = JedisUtils.get(key);
        //用完销毁
        JedisUtils.del(key);
        if(captcha.equals(sessionyanz)){
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        } else {
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }


    /**
     *有在用
     * <b>业务逻辑处理，验证码校验(邮箱或者手机验证码) </b>
     */
    @RequestMapping("/register/checkCode")
    @ResponseBody
    public ResultDto checkCode(String sign, String captcha, HttpServletRequest request) {
        String key = ConstProp.YZM_CCKEY+sign+"_"+IpAddress.getIpAddress(getRequest());
        logger.info("验证码确认-key："+key);
        String sessionyanz = JedisUtils.get(key);
        logger.info("验证码确认-sessionyanz："+sessionyanz);
        if(StringUtils.isEmpty(sessionyanz)){
            return new ResultDto("验证码已过期", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
        if(captcha.equals(sessionyanz)){
            JedisUtils.del(key);
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        } else {
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }



    /**
     *有在用
     *发送手机验证码
     */
    @RequestMapping("/register/sendAuthCode")
    @ResponseBody
    public ResultDto sendAuthCode(@RequestParam String tel, HttpServletRequest request) {
        if(StringUtils.isNotEmpty(tel)){
            if(!ValidatorUtil.validateMobile(tel)){
                return new ResultDto("手机号不合法", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
            String code = MathUtil.getRandomCode();
            //如果是测试环境验证码固定123456
            code = GlobalResources.IS_TEST_ENVI?"123456":code;
            logger.info("实名认证-手机号："+tel);
            logger.info("实名认证-验证码："+code);
            MessageModel mm = new MessageModel(code, EmailMsgType.AUTHCODE);
            logger.info("实名认证-手机验证码内容："+mm.getContent());
            //华为短信发送
            mss.sendHuaWeiSMS(new HuaWeiSmsContent(
                    ConstProp.SMSPLATFORM_BCXIN,
                    ConstProp.SMSCODE_P01,
                    tel,
                    JSON.toJSONString(new String[]{code})));
            String key = ConstProp.YZM_CCKEY+tel+"_"+IpAddress.getIpAddress(getRequest());
            logger.info("实名认证-key："+key);
            String keyyh = ConstProp.YHM_EN+tel+"_"+IpAddress.getIpAddress(getRequest());
            JedisUtils.set(key,code,5 * 60);
            JedisUtils.set(keyyh,tel,5 * 60);
//            request.getSession().setAttribute("checkCodekeyword",code);
//            request.getSession().setAttribute("email",tel);
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }else{
            return new ResultDto("手机号不能为空", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }

    /**
     *有在用
     *发送手机验证码
     */
    @RequestMapping("/register/loginSendAuthCode")
    @ResponseBody
    public ResultDto loginSendAuthCode(@RequestParam String tel, HttpServletRequest request) {
        if(StringUtils.isNotEmpty(tel)){
            if(!ValidatorUtil.validateMobile(tel)){
                return new ResultDto("手机号不合法", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
            String key = ConstProp.YZM_CCKEY+tel+"_"+IpAddress.getIpAddress(getRequest());
            String keyyh = ConstProp.YHM_EN+tel+"_"+IpAddress.getIpAddress(getRequest());
            if (StringUtils.isNotEmpty(JedisUtils.get(key))){
                return new ResultDto("请勿频繁发送验证码", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
            String code = MathUtil.getRandomCode();
            //如果是测试环境验证码固定123456
            code = GlobalResources.IS_TEST_ENVI?"123456":code;
            logger.info("实名认证-手机号："+tel);
            logger.info("实名认证-验证码："+code);
            MessageModel mm = new MessageModel(code, EmailMsgType.AUTHCODE);
            logger.info("实名认证-手机验证码内容："+mm.getContent());
            //华为短信发送
            mss.sendHuaWeiSMS(new HuaWeiSmsContent(
                    ConstProp.SMSPLATFORM_BCXIN,
                    ConstProp.SMSCODE_P01,
                    tel,
                    JSON.toJSONString(new String[]{code})));

            JedisUtils.set(key,code,60);
            JedisUtils.set(keyyh,tel,60);
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }else{
            return new ResultDto("手机号不能为空", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }

    /**
     *有在用
     *检查邮箱是否注册
     */
    @RequestMapping("/register/checkEmail")
    @ResponseBody
    public ResultDto checkEmail( String email, HttpServletRequest request) {
        try {
            boolean  flag= userService.getUserEmailForRegister(email,Constant.WEB_TYPE_COINS);
            if(!flag) {
                JedisUtils.set(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()),email,5 * 60);
                JedisUtils.set(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(getRequest()),Constant.USER_TYPE_EMAIL,5 * 60);
//                request.getSession().setAttribute("resetPwdEmail",email);
//                request.getSession().setAttribute("resetType",Constant.USER_TYPE_EMAIL);
                return new ResultDto("该邮箱已绑定", ConstProp.DIGIT_ONE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            } else {
                return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.DIGIT_TWO,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return null;
    }

    /**
     *有在用
     *检查手机是否注册
     */
    @RequestMapping("/register/checkMobile")
    @ResponseBody
    public ResultDto checkMobile( String tel, HttpServletRequest request) {
        boolean  flag= userService.getUserMobileForRegister(tel, Constant.WEB_TYPE_COINS);
        if(!flag) {
            JedisUtils.set(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()),tel,5 * 60);
            JedisUtils.set(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(getRequest()),Constant.USER_TYPE_MOBILE,5 * 60);
//            request.getSession().setAttribute("resetPwdEmail",tel);
//            request.getSession().setAttribute("resetType",Constant.USER_TYPE_MOBILE);
            return new ResultDto("该手机已经被注册了", ConstProp.DIGIT_ONE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        } else {
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.DIGIT_TWO,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);

        }
    }



    /**
     *有在用
     *判断用户名/手机/邮箱是否存在
     */
    @RequestMapping("/register/checkUserExist")
    @ResponseBody
    public ResultDto checkUserExist( String email, HttpServletRequest request) {

        boolean  flag= userService.checkUserExist(email,false);//表示只判断 手机和邮箱，不判断用户名字
        if(flag) {
            //存在
            JedisUtils.set(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()),email,5 * 60);
            JedisUtils.set(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(getRequest()),MathUtil.getType(email),5 * 60);
//            request.getSession().setAttribute("resetType",MathUtil.getType(email));
//            request.getSession().setAttribute("resetPwdEmail",email);
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.DIGIT_ONE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        } else {
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.DIGIT_TWO,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);

        }
    }
    /**
     *有在用
     *邮箱发送对应的 验证码
     */
    @RequestMapping("/sendEmailCode")
    @ResponseBody
    public ResultDto sendEmailCode( String email, HttpServletRequest request) {
        if(StringUtils.isNotEmpty(email)){
            String code= MathUtil.getRandomCode();
            EmailModel em = new EmailModel(code,EmailMsgType.TYYZM);
            em.addTo(email);
            System.out.println("邮箱发送验证码,EmailModel:"+JSON.toJSONString(em));
            try {
                SendEmailAndMsgUtil.sendEmail(em);
                System.out.println("邮箱发送验证码,已发送=============");
                String key = ConstProp.YZM_CCKEY+email+"_"+IpAddress.getIpAddress(getRequest());
                String keyyh = ConstProp.YHM_EN+email+"_"+IpAddress.getIpAddress(getRequest());
                JedisUtils.set(key,code,5 * 60);
                JedisUtils.set(keyyh,email,5 * 60);
//                request.getSession().setAttribute("checkCodekeyword",code);
//                request.getSession().setAttribute("email",email);
                System.out.println("邮箱发送验证码,返回=============");
                return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }catch (Exception e){
                return new ResultDto("服务器未响应，请联系管理员！！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }
        }else{
            return new ResultDto("邮箱不能为空", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }

    }

    /**
     *有在用
     *根据对应的手机号或者是邮箱发送对应的 验证码
     */
    @RequestMapping("/sendUserCode")
    @ResponseBody
    public ResultDto sendUserCode( String email, HttpServletRequest request) {


        if(StringUtils.isNotEmpty(email)){


            String code=userService.sendUserCode(email, EmailMsgType.AUTHCODE);
            if(code!=null){
                String key = ConstProp.YZM_CCKEY+email+"_"+IpAddress.getIpAddress(getRequest());
                String keyyh = ConstProp.YHM_EN+email+"_"+IpAddress.getIpAddress(getRequest());
                JedisUtils.set(key,code,5 * 60);
                JedisUtils.set(keyyh,email,5 * 60);
//                request.getSession().setAttribute("checkCodekeyword",code);
//                request.getSession().setAttribute("email",email);
                return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }else{
                return new ResultDto("验证码为空，请联系管理员！！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }

        }else{
            return new ResultDto("账号不能为空", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }

    }

    /**
     * 有在用
     * 获取随机验证码
     */
    @RequestMapping("/login")
    public ModelAndView login(String  url) {
        ModelAndView view = new ModelAndView("coninsweb/user/login_new");
//        view.addObject("url",url);
        if(StringUtils.isNotEmpty(url)){
            UserSupportUtil.setCustomSession("goToUrl",url);
        }else{
            UserSupportUtil.delCustomSession("goToUrl");
        }
        return view;
    }

    /**
     * <b> 企业登录 </b>
     * @author ZXF
     * @create 2024/04/18 0018 16:26
     * @version
     * @注意事项 </b>
     */
    @RequestMapping("/loginc")
    public ModelAndView loginc(String  url) {
        ModelAndView view = new ModelAndView("coninsweb/user/loginc_new");
        if(StringUtils.isNotEmpty(url)){
            UserSupportUtil.setCustomSession("goToUrl",url);
        }else{
            UserSupportUtil.delCustomSession("goToUrl");
        }
        return view;
    }

    /**
     * 有在用
     * 注册初始化页面
     */
    @RequestMapping("/register/init")
    public ModelAndView register( HttpServletRequest request ) {
        ModelAndView view = new ModelAndView("coninsweb/user/register_new");
        return view;
    }

    /**
     * 有在用
     * 忘记密码  第一步
     */
    @RequestMapping("/pwd/rest/init")
    public ModelAndView pwd() {
        ModelAndView view = new ModelAndView("coninsweb/user/pwdset_new_one");
        //初始化 填写数据
        return view;
    }

    /**
     * 有在用
     * 忘记密码   验证 手机或者邮箱
     */
    @RequestMapping("/pwd/rest/setUser")
    public ModelAndView setUser(String  email) {
        ModelAndView view = new ModelAndView("coninsweb/user/pwdset_new_two");
        if(StringUtils.isEmpty(email)){ //判断用户名存在不
            view = new ModelAndView("coninsweb/user/pwdset_new_one");
        }else{
            String resetPwdEmail = JedisUtils.get(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()));
            String resetType = JedisUtils.get(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(getRequest()));
            view.addObject("resetPwdEmail",resetPwdEmail);
            view.addObject("resetType",resetType);
        }

        return view;
    }

    /**
     * 有在用
     * 忘记密码   跳转到密码设置界面
     */
    @RequestMapping("/pwd/rest/setUserPwd")
    public ModelAndView setUserPwd(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("coninsweb/user/pwdset_new_three");
        String email = JedisUtils.get(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()));
//        String email = (String) request.getSession(true).getAttribute("resetPwdEmail");
        if(StringUtils.isNotEmpty(email)){
        }else{
            view = new ModelAndView("coninsweb/user/pwdset_new_one");
        }
        return view;
    }

    @RequestMapping("/pwd/rest/setSuccess")
    public ModelAndView setSuccess(String password,HttpServletRequest request) {
        ModelAndView view = new ModelAndView("coninsweb/user/pwdset_new_four");
        //判断验证码和用户名存在不
        String email = JedisUtils.get(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()));
//        String email = (String) request.getSession(true).getAttribute("resetPwdEmail");
        if(StringUtils.isNotEmpty(email)){
            ClientUserVo vo= userService.getClientUserVo(email,MathUtil.getType(email));
            if(vo==null){
                return new ModelAndView(DSUtil.operation()+"/user/pwd/rest/init");
            }
            if(userService.updClientUserVoPwd(vo,password)){
                JedisUtils.del(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()));
                JedisUtils.del(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(getRequest()));
//                request.getSession().removeAttribute("resetPwdEmail");
//                request.getSession().removeAttribute("resetType");

            }else{
                logger.debug("远程服务器修改失败");
            }

        }else{
            view = new ModelAndView("coninsweb/user/pwdset_new_one");
            logger.debug("需要填写第一步的邮箱！！");
        }
        return view;
    }

    @RequestMapping("/image")
    public ModelAndView image() {
        ModelAndView view = new ModelAndView("coninsweb/user/image");

        return view;
    }


    /**
     * 根据邮箱或者手机
     * 有在用(旧版)
     * 重置密码
     */
    @RequestMapping("/modal/reSetPwd")
    @ResponseBody
    public ResultDto reSetPwdForModal( HttpServletRequest request) {
        String email = JedisUtils.get(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()));
//        String email = (String) request.getSession(true).getAttribute("resetPwdEmail");
        if(StringUtils.isNotEmpty(email)){
            String password = request.getParameter("password");
            ClientUserVo vo= userService.getClientUserVo(email,MathUtil.getType(email));

            if(userService.updClientUserVoPwd(vo,password)){
                JedisUtils.del(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(getRequest()));
                JedisUtils.del(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(getRequest()));
//                request.getSession().removeAttribute("resetPwdEmail");
//                request.getSession().removeAttribute("resetType");
                return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            } else {
                return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
            }

        }else {
            return new ResultDto(ConstProp.BLANK_CHAR, ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
        }
    }

    /**
     * 获取登录状态（登录状态需要封装）
     *
     * 有在用
     */
    @RequestMapping(value = "/login/clentLogin")
    @OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_BLB,title ="【请求】首页-登录")
    @ResponseBody
    public JSONObject clientUserLogin(HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException {
        //获得username
        String userName = request.getParameter("j_username");
        //获得password
        String password = request.getParameter("j_password");
        //获得类型:1个人；2企业
        String type = request.getParameter("j_type");
        String rurl = (String) UserSupportUtil.getCustomSession("goToUrl");
        logger.info("得到的参数rurl是"+rurl);
        //初始状态300
        String status = ConstProp.CODE_FAILURE;
        String redirectUrl = ConstProp.BLANK_CHAR;
        String role = ConstProp.BLANK_CHAR;
        String msg = "用户名或密码错误！";
        String uType = MathUtil.getType(userName);
        if(!uType.equals(type)){
            status = "304";
            msg = "账号不存在！";
            return returnJsonMsg(status, redirectUrl, role, msg);
        }
        //getClientUser，根据所获得的username判断类型，返回1";// 手机用户类型 2 邮箱类型 3 用户类型
        SysClientUser clientUser =  userService.getClientUser(userName,uType);
        if(clientUser==null){
            status = "302";
            msg = "账号不存在！";
            return returnJsonMsg(status, redirectUrl, role, msg);
        }
//        if(StringUtils.isNotEmpty(type)&&type.equals(clientUser.getTerminal_type())){
//            status = "304";
//            msg = "账号类型不匹配！";
//            return returnJsonMsg(status, redirectUrl, role, msg);
//        }
        if(StringUtils.isNotEmpty(userName)&& StringUtils.isNotEmpty(password)){
            if(!Sha1Util.validatePassword(password,clientUser.getPassword())){
                status = "303";
                msg = "密码错误！";
                return returnJsonMsg(status, redirectUrl, role, msg);
            }
        }
        if(Constant.LOGIN_STATUS_FROZEN.equals(clientUser.getStatus()+ConstProp.BLANK_CHAR)){
            status = "301";
            msg = "账号被冻结！";
        }else{
            status = "200";
            msg = "登录成功！";
            try{
                ClientUserVo userVo = userService.getClientUserVo(userName,MathUtil.getType(userName));
                if(StringUtils.isNotEmpty(rurl)){
                    //跳转到登录页面
                    redirectUrl = rurl;
                }else{
                    String osName = System.getProperty("os.name");
                    //首页
                    redirectUrl = osName.contains("Windows")?"http://localhost:8080":GlobalResources.WEB_PRO_URL;
//                    redirectUrl = ConstProp.BLANK_CHAR+ GlobalResources.WEB_PRO_URL;//首页
                }
                HttpSession session = request.getSession();
                session.setMaxInactiveInterval(60*60);
                session.setAttribute("userdetail",userVo);
                userService.setLastTime(userVo);
                //同步登录账户的平安雇主线下报案信息
                insCommonReportAPIService.findXXReportDetails();
            }catch (Exception ex){
                status = "304";
                msg = "登录报错异常，请联系管理员";
                logger.error("登录报错"+ex);
            }
        }

        return returnJsonMsg(status, redirectUrl, role, msg);
    }

    @RequestMapping(value = "/login/clentLogin1")
    @OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_BLB,title ="【请求】首页-登录")
    @ResponseBody
    public JSONObject clientUserLogin1(HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException {
        //获得username
        String userName = request.getParameter("j_username");
        //获得password
        String password = request.getParameter("j_password");
        //获得类型:1个人账号；3个人手机；2企业
        String type = request.getParameter("j_type");
        String rurl = (String) UserSupportUtil.getCustomSession("goToUrl");
        logger.info("得到的参数rurl是"+rurl);
        //初始状态300
        String status;
        String redirectUrl = ConstProp.BLANK_CHAR;
        String role = ConstProp.BLANK_CHAR;
        String msg = "用户名或密码错误！";
        if(ConstProp.DIGIT_THREE.equals(type)){
            String key = ConstProp.YZM_CCKEY+userName+"_"+IpAddress.getIpAddress(getRequest());
            String sessionyanz = JedisUtils.get(key);
            if(StringUtils.isEmpty(sessionyanz)){
                status = "401";
                msg = "验证码已过期！";
                return returnJsonMsg(status, redirectUrl, role, msg);
            }
            if(password.equals(sessionyanz)){
                JedisUtils.del(key);
            } else {
                status = "400";
                msg = "验证码不正确！";
                return returnJsonMsg(status, redirectUrl, role, msg);
            }
        }

        String uType = MathUtil.getType(userName);
        if(!uType.equals(type)&&!ConstProp.DIGIT_THREE.equals(type)){
            status = "304";
            msg = "账号不存在！";
            return returnJsonMsg(status, redirectUrl, role, msg);
        }
        //getClientUser，根据所获得的username判断类型，返回1";// 手机用户类型 2 邮箱类型 3 用户类型
        SysClientUser clientUser =  userService.getClientUser(userName,uType);
        if(clientUser==null){
            status = "302";
            msg = "账号不存在！";
            return returnJsonMsg(status, redirectUrl, role, msg);
        }
        if(StringUtils.isNotEmpty(userName)&& StringUtils.isNotEmpty(password)){
            if(!Sha1Util.validatePassword(password,clientUser.getPassword())&&!ConstProp.DIGIT_THREE.equals(type)){
                status = "303";
                msg = "密码错误！";
                return returnJsonMsg(status, redirectUrl, role, msg);
            }
        }
        if(Constant.LOGIN_STATUS_FROZEN.equals(clientUser.getStatus()+ConstProp.BLANK_CHAR)){
            status = "301";
            msg = "账号被冻结！";
        }else{
            status = "200";
            msg = "登录成功！";
            try{

                ClientUserVo userVo = userService.getClientUserVo(userName,MathUtil.getType(userName));
                if(StringUtils.isNotEmpty(rurl)){
                    //跳转到登录页面
                    redirectUrl = rurl;
//                    logger.debug("rurl是空的。跳转到登录页面:"+redirectUrl);
                }else{
                    String osName = System.getProperty("os.name");
                    //首页
                    redirectUrl = osName.contains("Windows")?"http://localhost:8080":GlobalResources.WEB_PRO_URL;
//                    redirectUrl = ConstProp.BLANK_CHAR+ GlobalResources.WEB_PRO_URL;//首页
                }
                AccessToken accessToken = oAuthService.getAccessToken("web", userVo,"");
                if(accessToken==null){
                    status = "300";
                    return returnJsonMsg(status, "", role, "登录异常");
                }
                if(!redirectUrl.contains("ACCESS_TOKEN=")){
                    if(redirectUrl.contains("?")){
                        redirectUrl = redirectUrl+"&ACCESS_TOKEN="+accessToken.getTokenId();
                    }else{
                        redirectUrl = redirectUrl+"?ACCESS_TOKEN="+accessToken.getTokenId();
                    }
                }
//                HttpSession session = request.getSession();
//                session.setMaxInactiveInterval(60*60);
//                session.setAttribute("userdetail",userVo);
                userService.setLastTime(userVo);
                //同步登录账户的平安雇主线下报案信息
                insCommonReportAPIService.findXXReportDetails();
            }catch (Exception ex){
                status = "304";
                msg = "登录报错异常，请联系管理员";
                logger.error("登录报错"+ex);
            }
        }

        return returnJsonMsg(status, redirectUrl, role, msg);
    }

    private JSONObject returnJsonMsg(String status, String redirectUrl, String role, String msg) {
        JSONObject obj = new JSONObject();
        obj.put("status", status);
        obj.put("role", role);
        obj.put("redirectUrl", redirectUrl);
        obj.put("msg", msg);
        logger.debug("retrun,返回给页面的值："+JSON.toJSONString(obj));
        return obj;
    }


    @RequestMapping("/logout")
    public ModelAndView logout(HttpServletRequest request){
        try {
            String sessionId = JedisUtils.get(ConstProp.REDIS_HEAD_THR_TOKEN + getToken());
            if(StringUtils.isNotEmpty(getToken())){
                if(StringUtils.isNotEmpty(sessionId)){
                    //获取session
                    HttpSession session1 = SessionContext.getInstance().getSession(sessionId);
                    session1.invalidate();
                    JedisUtils.del(ConstProp.REDIS_HEAD_THR_TOKEN + getToken());
                }else{
                    System.out.println("==========> logout-blb");
                    JedisUtils.del(ConstProp.REDIS_HEAD_BLB_TOKEN+getToken());
                }
            }
            if(request.getSession()!=null){
//                String  token =request.getSession().getAttribute("token")==null?null:request.getSession().getAttribute("token").toString();
//                UserSupportUtil.getUserLogout(token);
//                if(UserSupportUtil.getRequest().getSession() != null){
//                    UserSupportUtil.getRequest().getSession().invalidate();
//                }
                request.getSession().invalidate();
            }
        }catch (Exception ex){
            logger.error("退出异常",ex);
        }
//        logger.debug(GlobalResources.WEB_PRO_URL+"user/login");
        return new ModelAndView("redirect:/user/login");
    }




}
