package com.aidex.quartz.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.aidex.common.constant.Constants;
import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.utils.StringUtils;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.system.domain.SysAlarm;
import com.aidex.system.domain.SysConfig;
import com.aidex.system.domain.SysShip;
import com.aidex.system.service.SysShipService;
import com.alibaba.fastjson2.JSONArray;
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 java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.aidex.common.enums.AlarmType.*;

/**
 * @author ：ChenSir
 * @date ：Created in 2024/3/17 20:07
 * @description：由于mds令牌有时效性，某些场景（模块或页面）需要线程常驻，那么需要mds长期有效，由于接口调用可以顺延mds的时效，建议定时器每隔5分钟请求一次本接口，确保mds不会过期。
 */
@Component("RefreshMdsTask")
public class RefreshMdsTask {

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

	@Autowired
	private RedisCache redisCache;

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

	@Autowired
	private SysShipService sysShipService;


	/**
	 * 刷新GPS的token
	 * @return token
	 */
	public String refreshGPSToken(){
		logger.info("刷新GPS的token----------开始");
		String token = "";
		try{
			String mds = redisCache.getStringValue(Constants.GPS_TOKEN_PREFIX);
			SysConfig configUrl = ConfigUtils.getConfigByKey("sys.gps.api.url");
			if (configUrl != null && StringUtils.isNotBlank(mds)) {
				String url = configUrl.getConfigValue();
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("w", "RefreshMds");
				paramMap.put("method", "QueryApi");
				paramMap.put("mds", mds);
				//链式构建请求
				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")){
						logger.info("Gps平台刷新token结束,获取token为-----{}", mds);
						redisCache.expire(Constants.GPS_TOKEN_PREFIX, Constants.GPS_TOKEN_EXPIRATION, TimeUnit.MINUTES);
					}else {
						logger.info("Gps平台获取token初始化结束,Http 请求结果错误！-----{}", jsonObjec);
						// 重新获取token
						getGpsToken();
					}
				}else {
					logger.info("Gps平台获取token初始化结束,Http 请求结果为空！");
				}
			}
		}catch (Exception e){
			token = e.getLocalizedMessage();
		}
		logger.info("刷新GPS的token----------结束");
		return token;
	}

	public void getGpsToken(){
		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");
					if (token != null && StringUtils.isNotEmpty(token.getString("mds"))){
						redisCache.deleteKey(Constants.GPS_LOGIN_INFO_PREFIX);
						redisCache.setCacheObject(Constants.GPS_LOGIN_INFO_PREFIX, token.toJSONString());
						redisCache.deleteKey(Constants.GPS_TOKEN_PREFIX);
						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重新获取结束");
	}


	/**
	 * 刷新GPS的token
	 * @return token
	 */
	public void updateShipStatus(){
		logger.info("通过船只编号更新船只状态----------开始");
		try{
			SysShip sysShip = new SysShip();
			sysShip.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
			List<SysShip> list = sysShipService.findList(sysShip);

			String mds = redisCache.getStringValue(Constants.GPS_TOKEN_PREFIX);
			SysConfig configUrl = ConfigUtils.getConfigByKey("sys.gps.api.url");
			String url = configUrl.getConfigValue();
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("method", "QueryApi");
			paramMap.put("w", "UserDevices");
			paramMap.put("mds", mds);
			logger.info("请求参数:{}", paramMap);
			//链式构建请求
			String result = HttpRequest.post(url + ACTION_URL)
					.form(paramMap)//表单内容
					.timeout(50000)//超时，毫秒
					.execute().body();
			logger.info("请求结果:{}", result);
			if (result != null) {
				JSONObject jsonObjec = JSONObject.parseObject(result);
				if (jsonObjec.getBoolean("success")){
					logger.info("通过mds获取设备数据,mds----{}，设备数据为-----{}", mds, jsonObjec.getJSONArray("data"));
					JSONArray data  = jsonObjec.getJSONArray("data");
					for (int i = 0; i < data.size(); i++) {
						JSONObject json = data.getJSONObject(i);
						if (json != null && StringUtils.isNotEmpty(json.getString("macid"))){
							SysShip shipByMacId = sysShipService.getShipByMacId(json.getString("macid"));
							if (shipByMacId != null){
								sysShipService.updateStatusByMacId(json.getString("macid"), json.getString("status"));
							}
						}
					}
				}else {
					logger.info("通过mds获取设备数据结束,Http 请求结果错误！-----{}", jsonObjec);
				}
			for (SysShip item : list){
				if (configUrl != null && StringUtils.isNotBlank(mds)) {

					}else {
						logger.info("通过mds获取设备数据结束,Http 请求结果为空！");
					}
				}
			}
		}catch (Exception e){
			logger.error(e.getLocalizedMessage());
		}
		logger.info("通过船只编号更新船只状态----------结束");
	}

}
