package com.bcxin.ins.weixin.login.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.service.user.ClientUserService;
import com.bcxin.ins.entity.user.SysClientUser;
import com.bcxin.ins.spring.util.JedisUtils;
import com.bcxin.ins.util.Constant;
import com.bcxin.ins.util.IpAddress;
import com.bcxin.ins.util.MathUtil;
import com.bcxin.ins.util.Sha1Util;
import com.bcxin.ins.util.email.EmailModel;
import com.bcxin.ins.util.email.EmailMsgType;
import com.bcxin.ins.util.email.SendEmailAndMsgUtil;
import com.bcxin.ins.vo.ClientUserVo;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.weixin.login.service.WeiXinLoginService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.bcxin.ins.util.Constant.USER_TYPE_MOBILE;

@Service
@Transactional
public class WeiXinLoginServiceImpl  implements WeiXinLoginService {


    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ClientUserService userService;

    @Override
    public JSONObject login(Map<Object, Object> params, HttpServletRequest req, HttpServletResponse resp) {
        //获得username
        String userName = String.valueOf(params.get("j_username"));
        //获得password
        String password = String.valueOf(params.get("j_password"));
        //初始状态300
        String status = "300";
        String redirectUrl = "";
        String role = "";
        String msg = "用户名或密码错误！";
        //getClientUser，根据所获得的username判断类型，返回1";// 手机用户类型 2 邮箱类型 3 用户类型
        SysClientUser clientUser =  userService.getClientUser(userName,MathUtil.getType(userName));
        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())){
                status = "303";
                msg = "密码错误！";
                return returnJsonMsg(status, redirectUrl, role, msg);
            }
        }
        if(Constant.LOGIN_STATUS_FROZEN.equals(clientUser.getStatus()+"")){
            status = "301";
            msg = "账号被冻结！";
        }else{
            status = ConstProp.CODE_SUCCESS;
            msg = "登录成功！";
            try{
                ClientUserVo userVo = userService.getClientUserVo(userName, MathUtil.getType(userName));
                req.getSession().setAttribute("wxUserVo",userVo);
                userService.setLastTime(userVo);
                String callbackUri=req.getSession().getAttribute("callback_uri")==null?null:req.getSession().getAttribute("callback_uri").toString();
                if(StringUtils.isNotBlank(callbackUri)? !"/weixin/login".equals(callbackUri) : false){
                    status = "201";
                    msg = "登录成功！";
                    redirectUrl=callbackUri;
                }

            }catch (Exception ex){
                status = "304";
                msg = "登录报错异常，请联系管理员";
                logger.error("登录报错"+ex);
            }
        }
        return returnJsonMsg(status, redirectUrl, role, msg);
    }

    @Override
    public JSONObject checkUserExist(String email, HttpServletRequest request) {
        boolean  flag= userService.checkUserExist(email,false);//表示只判断 手机和邮箱，不判断用户名字
        if(flag) {
            //存在
            JedisUtils.set(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(request),email,5 * 60);
            JedisUtils.set(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(request),MathUtil.getType(email),5 * 60);
//            request.getSession().setAttribute("resetType", MathUtil.getType(email));
//            request.getSession().setAttribute("resetPwdEmail",email);
            return  existSuccess();
        }
        return existFail();
    }

    @Override
    public JSONObject sendEmailCode(String email, HttpServletRequest request) {

        if(StringUtils.isNotEmpty(email)){
            String code= MathUtil.getRandomCode();
            EmailModel em = new EmailModel(code,EmailMsgType.TYYZM);
            em.addTo(email);
            try {
                SendEmailAndMsgUtil.sendEmail(em);
                request.getSession().setAttribute("checkCodekeyword",code);
                request.getSession().setAttribute("email",email);
                return returnSuccess();
            }catch (Exception e){}
        }
        return  returnFail();
    }

    @Override
    public JSONObject sendTelPhoneCode(String email, HttpServletRequest request) {
        if(StringUtils.isNotEmpty(email)){
            String code=userService.sendUserCode(email, EmailMsgType.AUTHCODE);
            if(code!=null){
                request.getSession().setAttribute("checkCodekeyword",code);
                request.getSession().setAttribute("email",email);
                return  returnSuccess();
             }
        }
        return returnFail();
    }

    @Override
    public JSONObject ckeckEmail(String email, HttpServletRequest request) {

        boolean  flag= userService.getUserEmailForRegister(email, Constant.WEB_TYPE_COINS);
        if(!flag) {
            JedisUtils.set(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(request),email,5 * 60);
            JedisUtils.set(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(request),Constant.USER_TYPE_EMAIL,5 * 60);
//            request.getSession().setAttribute("resetPwdEmail",email);
//            request.getSession().setAttribute("resetType",Constant.USER_TYPE_EMAIL);
            return  existSuccess();
        }
        return  existFail();
    }

    @Override
    public JSONObject checkMobile(String tel, HttpServletRequest request) {

        boolean  flag= userService.getUserMobileForRegister(tel, Constant.WEB_TYPE_COINS);
        if(!flag) {
            JedisUtils.set(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(request),tel,5 * 60);
            JedisUtils.set(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(request),Constant.USER_TYPE_MOBILE,5 * 60);
//            request.getSession().setAttribute("resetPwdEmail",tel);
//            request.getSession().setAttribute("resetType", USER_TYPE_MOBILE);
            return existSuccess();
        }
        return  existFail();
    }

    @Override
    public JSONObject sendCode(String email, HttpServletRequest request) {
        if(USER_TYPE_MOBILE.equals(MathUtil.getType(email))){
             //是手机号码
              return sendTelPhoneCode(email,request);
        }else if(Constant.USER_TYPE_EMAIL.equals(MathUtil.getType(email))){
                //发送验证码
               return  sendEmailCode(email,request);
        }
        return   returnFail();
    }

    @Override
    public JSONObject checkCodeExist(String code, HttpServletRequest request) {
        String sessionyanz =(String)request.getSession(true).getAttribute("checkCodekeyword");
        if(code.equals(sessionyanz)){
            request.getSession(true).removeAttribute("checkCodekeyword");
            return returnSuccess();
        }
        return returnFail();
    }

    @Override
    public JSONObject register(Map<Object, Object> params, HttpServletRequest req, HttpServletResponse resp) {
        String email =params.get("email")==null?null:params.get("email").toString();
        String code = params.get("code")==null?null:params.get("code").toString();
        //查询该用户是否存在
        boolean flag=false;
        String  emailAgain=req.getSession().getAttribute("email")==null?null:req.getSession().getAttribute("email").toString();
        if(!email.equals(emailAgain)){

            return  returnFail();
        }
        if("1".equals(code)){
            //手机注册
            flag= userService.getUserMobileForRegister(email,Constant.WEB_TYPE_COINS);
        }else if("2".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= req.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("1");//设置角色权限
                vo.setRole_name("COMMON-ONE-HEAD");
                vo.setEmail(email);
            }
            boolean userflag=userService.saveClientUserVo(vo);
            if(userflag){
                return returnSuccess();
             }
        }
        return returnFail();
    }

    @Override
    public JSONObject resetPassword(HttpServletRequest request,Map<Object, Object> params) {
        String email = JedisUtils.get(ConstProp.YH_RESETPWDEMAIL+ IpAddress.getIpAddress(request));
//        String email =request.getSession().getAttribute("resetPwdEmail")==null?null:request.getSession().getAttribute("resetPwdEmail").toString();
        String password =params.get("pwd")==null?null:params.get("pwd").toString();
        if(email==null||password==null){
            return  returnFail();
        }
        ClientUserVo weixinVo= userService.getClientUserVo(email,MathUtil.getType(email));
            if(weixinVo==null){
                return  returnFail();
            }
            if(userService.updClientUserVoPwd(weixinVo,password)){
                JedisUtils.del(ConstProp.YH_RESETPWDEMAIL+IpAddress.getIpAddress(request));
                JedisUtils.del(ConstProp.YH_RESETTYPE+IpAddress.getIpAddress(request));
//                request.getSession().removeAttribute("resetPwdEmail");
//                request.getSession().removeAttribute("resetType");
                return  returnSuccess();
            }
       return  returnFail();
    }


    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;
    }


    private JSONObject returnSuccess() {
        //返回存在，或者是成功
        JSONObject obj = new JSONObject();
        obj.put("status", ConstProp.CODE_SUCCESS);
        obj.put("msg", "操作成功");
        return obj;
    }

    private JSONObject existSuccess() {
        //返回存在，或者是成功
        JSONObject obj = new JSONObject();
        obj.put("status", ConstProp.CODE_SUCCESS);
        obj.put("msg", "存在该数据");
        return obj;
    }

    private JSONObject returnFail() {
        //返回不存在，或者是失败
        JSONObject obj = new JSONObject();
        obj.put("status", "300");
        obj.put("msg", "操作失败");
        return obj;
    }

    private JSONObject existFail() {
        //返回不存在，或者是失败
        JSONObject obj = new JSONObject();
        obj.put("status", "300");
        obj.put("msg", "该数据不存在");
        return obj;
    }
}
