package com.zcloud.util;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.common.utils.HttpRequestUtil;
import com.zcloud.modules.personLocationToken.mapper.PersonLocationTokenMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 人员定位系统工具类
 * @author zhangyue
 * @date 2023/9/20/020 17:33
 */
@Component
public class PerLocUtil {

    @Value("${perLoc.url}")
    private String url;
    @Value("${perLoc.userName}")
    private String userName;
    @Value("${perLoc.pwd}")
    private String pwd;
    @Resource
    private PersonLocationTokenMapper personLocationTokenMapper;

    public String getToken() throws Exception{
        String token = personLocationTokenMapper.getToken();
        // token 不为空。验证token是否失效
        if (StringUtils.isNotEmpty(token)){
            String httpResponseStr = HttpRequestUtil.doGet(this.url + "/system/token/verifyThatTheTokenIsInvalid"+"?token="+token);
            JSONObject httpResponse = JSONObject.parseObject(httpResponseStr);
            // token 有效
            if(StringUtils.isNotEmpty(httpResponseStr) && httpResponse != null
                    && httpResponse.get("code") != null && httpResponse.getInteger("code") == 200){
                return token;
            } else {    // token 失效 或者报错
                token = goToLogin();
            }
        } else {
            token = goToLogin();
        }
        return token;
    }

    private String goToLogin() throws Exception{
        JSONObject request = new JSONObject();
        request.put("username", userName);
        request.put("password", pwd);
        String loginResStr = HttpRequestUtil.doPost(this.url + "/auth/login", request.toJSONString());
        JSONObject loginResponse = JSONObject.parseObject(loginResStr);
        // 登录成功
        if(StringUtils.isNotEmpty(loginResStr) && loginResponse != null
                && loginResponse.get("code") != null && loginResponse.getInteger("code") == 200
                && loginResponse.get("data") != null && loginResponse.getJSONObject("data").getString("access_token") != null){
            personLocationTokenMapper.edit(loginResponse.getJSONObject("data").getString("access_token"));
            return loginResponse.getJSONObject("data").getString("access_token");
        } else {    // 登录失败
            throw new RuntimeException("第三方登录失败");
        }
    }
}
