package com.github.wxiaoqi.security.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.api.vo.user.AppUserInfo;
import com.github.wxiaoqi.security.api.vo.user.UserInfo;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.auth.common.util.jwt.JWTInfo;
import com.github.wxiaoqi.security.auth.feign.IUserService;
import com.github.wxiaoqi.security.auth.service.AuthService;
import com.github.wxiaoqi.security.auth.util.user.JwtAuthenticationRequest;
import com.github.wxiaoqi.security.auth.util.user.JwtTokenUtil;
import com.github.wxiaoqi.security.common.constant.RequestTypeConstants;
import com.github.wxiaoqi.security.common.exception.auth.UserInvalidException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author keliii
 */
@Slf4j
@Service("appAuthService")
public class AppAuthServiceImpl implements AuthService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private IUserService userService;

    @Override
    public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
        AppUserInfo info = userService.AppValidate(authenticationRequest);
        if (info!=null&&!StringUtils.isEmpty(info.getId())) {
            // 在jwt中加入requestType
            return jwtTokenUtil.generateToken(new JWTInfo(info.getUsername(), info.getId() + "", info.getName(),
                    RequestTypeConstants.APP));
        }
        throw new UserInvalidException("用户不存在或账户密码错误!");
    }

    @Override
    public ObjectRestResponse loginSmall(JwtAuthenticationRequest authenticationRequest) throws Exception {
        UserInfo info = userService.validateSmall(authenticationRequest);
        if (info!=null&&!StringUtils.isEmpty(info.getId())) {
            info.setPassword(null);
            JSONObject object=new JSONObject();
            String token=jwtTokenUtil.generateToken(new JWTInfo(info.getUsername(), info.getId() + "", info.getName()));
            object.put("token",token);
            object.put("info",info);
            return ObjectRestResponse.succ(object);
        }
        throw new UserInvalidException("用户不存在或账户密码错误!");
    }

    @Override
    public String refresh(String oldToken) throws Exception {
        return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
    }

    @Override
    public void validate(String token) throws Exception {
        jwtTokenUtil.getInfoFromToken(token);
    }
    @Override
    public JSONObject sendsms(String username, Integer type) throws Exception {
        return userService.sendsms(username,type);
    }

    @Override
    public JSONObject register(String username, String mobilecode, String password,String code) throws Exception {
        return userService.register(username,mobilecode,password,code);
    }

    @Override
    public JSONObject wxregister(String username, String mobilecode, String password, String nickname, String headimgurl, String openid, String unionid, Integer type,Integer  isQQ,String code) throws Exception {
        return userService.wxregister(username,mobilecode,password,nickname,headimgurl,openid,unionid,type,isQQ,code);
    }

    @Override
    public JSONObject checkBindWechat(String username) throws Exception {
        return userService.checkBindWechat(username);
    }

    @Override
    public JSONObject wxlogin(String openid,Integer isQQ,String code) throws Exception {
        return userService.wxlogin(openid,isQQ,code);
    }

    @Override
    public JSONObject tlogin(String username, String password, String mobilecode, Integer type,String code) throws Exception {
        return userService.login(username,password,mobilecode,type,code);
    }

    @Override
    public String getToken(String username,Integer id) throws Exception {
        return jwtTokenUtil.generateToken(new JWTInfo(username, id + "",null,
                RequestTypeConstants.APP));
    }

    @Override
    public JSONObject reset(String username, String mobilecode, String password) throws Exception {
        return userService.reset(username,mobilecode,password);
    }

    @Override
    public JSONObject appletLoginByUserId(Integer userid) {
        return userService.appletLogin(userid);
    }

    @Override
    public JSONObject appletRegistry(String username,String headimgurl,String nickname,Integer  userid) {
        return userService.appletRegistry(username,headimgurl,nickname,userid);
    }

    @Override
    public String loginImiWithToken() {
        return userService.loginImiWithToken();
    }

    @Override
    public ObjectRestResponse checkToken(String token) {
        try {
            if (StringUtils.isEmpty(token)){
                return ObjectRestResponse.createFailedResult(10003,"参数不能为空");
            }
            IJWTInfo ijwtInfo=jwtTokenUtil.getInfoFromToken(token);
            if (ijwtInfo==null){
                return ObjectRestResponse.createFailedResult(10009,"token失效");
            }
            token=jwtTokenUtil.generateToken(ijwtInfo);
            return ObjectRestResponse.succ(token);
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return ObjectRestResponse.createFailedResult(10009,"token失效");
        }

    }

    @Override
    public ObjectRestResponse updUsername(String username, String mobilecode, String token) {
        if (StringUtils.isEmpty(token)){
            return ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"token不能为空");
        }
        try {
            IJWTInfo ijwtInfo=jwtTokenUtil.getInfoFromToken(token);
            if (ijwtInfo==null){
                return ObjectRestResponse.createFailedResult(10009,"token失效");
            }
            Integer userId= Integer.parseInt(ijwtInfo.getId());
            ObjectRestResponse objectRestResponse=userService.updUsername(username,mobilecode,userId);
            if (objectRestResponse.getStatus()==ResultCode.SUCCESS_CODE){
                token=getToken(username,userId);
                objectRestResponse.setData(token);
            }
            return objectRestResponse;
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"操作失败");
        }
    }

}
