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

import com.alibaba.fastjson.JSONObject;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@Service("baseAuthService")
public class AuthServiceImpl implements AuthService {

    private JwtTokenUtil jwtTokenUtil;
    private IUserService userService;

    @Autowired
    public AuthServiceImpl(
            JwtTokenUtil jwtTokenUtil,
            IUserService userService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }

    @Override
    public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
        UserInfo info = userService.validate(authenticationRequest);
        if (!StringUtils.isEmpty(info.getId())) {
            return jwtTokenUtil.generateToken(new JWTInfo(info.getUsername(), info.getId() + "", info.getName()));
        }
        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 void validate(String token) throws Exception {
        jwtTokenUtil.getInfoFromToken(token);
    }

    @Override
    public String refresh(String oldToken) throws Exception {
        return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
    }
    @Override
    public JSONObject sendsms(String username, Integer type, String pointList) throws Exception {
        return userService.sendsms(username,type, pointList);
    }
    @Override
    public JSONObject register(String username, String mobilecode, String password,String code,Integer channel,String registerSource) throws Exception {
        return userService.register(username,mobilecode,password,code,channel,registerSource);
    }

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

    @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,"操作失败");
        }
    }
}
