package com.example.demo.module.login;

import com.example.demo.common.RequestResult;
import com.example.demo.table.UserLogin;
import com.example.demo.table.user.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.jc.util.JCCache;
import pers.jc.util.JCUtil;

/**
 * 服务-游戏登陆
 */
@Service
public class GameLoginService {
    public static GameLoginService ins;
    public GameLoginService() {
        ins = this;
    }

    @Autowired
    GameLoginRepository repository;

    public RequestResult login(String username, String password) {
        RequestResult requestResult = new RequestResult();
        UserLogin userLogin = repository.getUserLogin(username);
        if (userLogin == null) {
            requestResult.setCode(-1);
            requestResult.setMsg("账号未注册");
        } else if (userLogin.getPassword().equals(password)) {
            String token = JCUtil.uuid();
            long timeout = System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7;
            userLogin.setToken(token);
            userLogin.setToken_timeout(timeout);
            repository.updateUserLogin(userLogin);
            JCCache.ins().put(tokenCacheKey(userLogin.getId()), token, timeout);
            requestResult.setData(userLogin.getId() + "&" + token);
            requestResult.setMsg("登录成功");
        } else {
            requestResult.setCode(-2);
            requestResult.setMsg("密码错误");
        }
        return requestResult;
    }

    public RequestResult loginByPhone(String phone) {
        Long phoneLong = Long.valueOf(phone);
        RequestResult requestResult = new RequestResult();
        if (phoneLong == null) {
            return null;
        }
        String username = "p-" + phone;
        String password = "phone";
        UserLogin userLogin = repository.getUserLogin(username);
        if (userLogin == null) {
            userLogin = new UserLogin();
            userLogin.setUsername(username);
            userLogin.setPassword(password);
            UserInfo userInfo = new UserInfo();
            userInfo.setPhone(phone);
            repository.insertNewUser(userLogin, userInfo);
            if (userLogin.getId() == 0) {
                userLogin = repository.getUserLogin(username);
            }
        }
        String token = JCUtil.uuid();
        long timeout = System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7;
        userLogin.setToken(token);
        userLogin.setToken_timeout(timeout);
        repository.updateUserLogin(userLogin);
        JCCache.ins().put(tokenCacheKey(userLogin.getId()), token, timeout);
        requestResult.setData(userLogin.getId() + "&" + token);
        requestResult.setMsg("登录成功");
        return requestResult;
    }

    public RequestResult register(String username, String password) {
        RequestResult requestResult = new RequestResult();
        if (repository.getUserLogin(username) != null) {
            requestResult.setMsg("该账号已被注册");
            requestResult.setFailCode();
        } else {
            UserLogin userLogin = new UserLogin();
            userLogin.setUsername(username);
            userLogin.setPassword(password);
            boolean res = repository.insertNewUser(userLogin);
            if (res) {
                requestResult.setMsg("注册成功");
            } else {
                requestResult.setMsg("注册失败");
                requestResult.setFailCode();
            }
        }
        return requestResult;
    }

    public RequestResult completeUserInfo(
            String username, String password, String nickname, int gender, String birthday,
            String countryCode, String stateCode, String cityCode) {
        RequestResult requestResult = new RequestResult();
        UserLogin userLogin = repository.getUserLogin(username);
        if (userLogin == null) {
            requestResult.setCode(-1);
            requestResult.setMsg("用户不存在");
        } else if (!userLogin.getPassword().equals(password)) {
            requestResult.setCode(-2);
            requestResult.setMsg("验证密码不对");
        } else if (nickname.length() > 12) {
            requestResult.setCode(-3);
            requestResult.setMsg("昵称错误");
        } else if (gender != 1 && gender != 2) {
            requestResult.setCode(-4);
            requestResult.setMsg("性别错误");
        } else if (birthday.length() != 10) {
            requestResult.setCode(-5);
            requestResult.setMsg("生日错误");
        } else if (countryCode == null || stateCode == null || cityCode == null) {
            requestResult.setCode(-6);
            requestResult.setMsg("所在地区错误");
        } else {
            UserInfo userInfo = repository.getUserInfo(userLogin.getId());
            userInfo.setNickname(nickname);
            userInfo.setGender(gender);
            userInfo.setBirthday(birthday);
            userInfo.setCountry(countryCode);
            userInfo.setState(stateCode);
            userInfo.setCity(cityCode);
            repository.updateUserInfo(userInfo);
            requestResult.setMsg("保存成功");
        }
        return requestResult;
    }

    public boolean authToken(int id, String token, String sceneName) {
        String tokenCache = JCCache.ins().get(tokenCacheKey(id), String.class);
        if (tokenCache == null) { //查数据库
            UserLogin userLogin = repository.getUserLogin(id);
            if (userLogin == null) {
                return false;
            }
            if (userLogin.getId() != id) {
                return false;
            }
            if (userLogin.getToken().equals(token)) { //token一样
                if (System.currentTimeMillis() >= userLogin.getToken_timeout()) { //超时了
                    if (!"Home".equals(sceneName)) { //不是Home场景，就继续保持认证成功
                        return true;
                    }
                } else { //未超时
                    JCCache.ins().put(tokenCacheKey(userLogin.getId()), token, userLogin.getToken_timeout());
                    return true;
                }
            }
            return false;
        } else {
            return tokenCache.equals(token);
        }
    }

    private String tokenCacheKey(int userID) {
        return "UserToken_" + userID;
    }

    public void setUserOfflineTime(int userID) {
        repository.setUserOfflineTime(userID);
    }
}
