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.SysAlarmService;
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 static com.aidex.common.enums.AlarmType.*;

/**
 * @author ：ChenSir
 * @date ：Created in 2024/3/17 20:07
 * @description：单台设备报警详单-根据起止时间和报警编号，获取告警的详细信息。
 */
@Component("GetAlarmDataByDevice")
public class GetAlarmDataByDevice {

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

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private SysShipService sysShipService;

	@Autowired
	private SysAlarmService alarmService;

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


	/**
	 * 刷新GPS的token
	 * @return token
	 */
	public void getDataService(){
		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");
			// 获取当前时间的毫秒值
			long currentTimeMillis = DateUtil.current();
			// 获取当天零点时间的毫秒值
			long startOfDay = DateUtil.beginOfDay(new Date()).getTime();
			StringBuilder builder = new StringBuilder();
			builder.append(OUT_AGE.getCode()).append(",").append(LOW_SPEED.getCode()).append(",").append(OVER_SPEED.getCode());
			for (SysShip item : list){
				if (configUrl != null && StringUtils.isNotBlank(mds)) {
					String url = configUrl.getConfigValue();
					Map<String, Object> paramMap = new HashMap<>();
					paramMap.put("method", "QueryApi");
					paramMap.put("w", "AlarmDetails");
					paramMap.put("mds", mds);
					paramMap.put("macid", item.getShipNum());
					paramMap.put("startTime", startOfDay);
					paramMap.put("endTime", currentTimeMillis);
					paramMap.put("mapType", "QQ");
					paramMap.put("alarmTypes", builder.toString());
					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("通过船只编号获取设备报警数据,船只编号----{}，获取数据为为-----{}", item.getShipNum(), jsonObjec.getJSONArray("data"));
							JSONArray data  = jsonObjec.getJSONArray("data");
							for (int i = 0; i < data.size(); i++) {
								JSONObject json = data.getJSONObject(i);
								SysAlarm sysAlarm = JSONObject.parseObject(json.toJSONString(), SysAlarm.class);
								sysAlarm.setId(json.getString("alarmid"));
								sysAlarm.setObjectId(json.getString("objectid"));
								sysAlarm.setMacId(json.getString("macid"));
								SysAlarm sysAlarmHis = alarmService.get(json.getString("alarmid"));
								if (sysAlarmHis == null) {
									sysAlarm.setIsNewRecord();
									alarmService.save(sysAlarm);
								}
							}
						}else {
							logger.info("Gps平台获取token初始化结束,Http 请求结果错误！-----{}", jsonObjec);
						}
					}else {
						logger.info("Gps平台获取token初始化结束,Http 请求结果为空！");
					}
				}
			}
		}catch (Exception e){
			logger.error(e.getLocalizedMessage());
		}
		logger.info("通过船只编号获取设备报警数据----------结束");
	}


}
