package com.aidex.framework.cache;

import cn.hutool.http.HttpRequest;
import com.aidex.common.constant.Constants;
import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.utils.StringUtils;
import com.aidex.system.domain.SysConfig;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author ：ChenSir
 * @date ：Created in 2024/3/17 13:33
 * @description：初始话获取gps平台的token，存入redis
 */
@Component
public class MyInitializer {

	protected static final Logger logger = LoggerFactory.getLogger(MyInitializer.class);

	@Autowired
	private RedisCache redisCache;

	private final String ACTION_URL = "/GetDataService.aspx";

	@PostConstruct
	public void init() {
		logger.info("Gps平台获取token初始化开始");
		SysConfig configAccount = ConfigUtils.getConfigByKey("sys.gps.account");
		SysConfig configPassword = ConfigUtils.getConfigByKey("sys.gps.password");
		SysConfig configUrl = ConfigUtils.getConfigByKey("sys.gps.api.url");
		if (configUrl != null && configPassword != null && configAccount != null) {
			String account = configAccount.getConfigValue();
			String password = configPassword.getConfigValue();
			String url = configUrl.getConfigValue();
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("userName", account);
			paramMap.put("password", password);
			paramMap.put("w", "UserLogin");
			paramMap.put("method", "SignApi");
			//链式构建请求
			String result = HttpRequest.post(url + ACTION_URL)
					.form(paramMap)//表单内容
					.timeout(10000)//超时，毫秒
					.execute().body();
			logger.info("请求结果:{}", result);
			if (result != null) {
				JSONObject jsonObjec = JSONObject.parseObject(result);
				if (jsonObjec.getBoolean("success")){
					JSONObject token = jsonObjec.getJSONObject("data");
					redisCache.setCacheObject(Constants.GPS_LOGIN_INFO_PREFIX, token.toJSONString());
					if (token != null && StringUtils.isNotEmpty(token.getString("mds"))){
						redisCache.setCacheObject(Constants.GPS_TOKEN_PREFIX, token.getString("mds"), Constants.GPS_TOKEN_EXPIRATION, TimeUnit.MINUTES);
					}else {
						logger.info("Gps平台获取token初始化结束,Http 请求结果不包含token信息！-----{}", jsonObjec);
					}
				}else {
					logger.info("Gps平台获取token初始化结束,Http 请求结果错误！-----{}", jsonObjec);
				}
			}else {
				logger.info("Gps平台获取token初始化结束,Http 请求结果为空！");
			}
		}
		logger.info("Gps平台获取token初始化结束");
	}


}
