package com.yeejoin.amos.boot.module.jxiop.biz.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.AlarmEventDto;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.ColModel;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.DataGridMock;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.ResultsData;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.AlarmEvent;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.EquipAlarmEvent;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.EquipmentSpecificIndex;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.EquipmentSpecificIndexAlarmDic;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.EquipmentSpecificIndexAlarmDicMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.EquipmentSpecificIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdmapper.AlarmEventMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdmapper.EquipAlarmEventMapper;

@Service
public class AlarmEventServiceImpl extends BaseService<AlarmEventDto, AlarmEvent, AlarmEventMapper> {

	@Autowired
	private EquipAlarmEventMapper equipAlarmEventMapper;

	@Autowired
	private EquipmentSpecificIndexMapper equipmentSpecificIndexMapper;

	@Autowired
	private EquipmentSpecificIndexAlarmDicMapper equipmentSpecificIndexAlarmDicMapper;

	@Autowired
	private RedisUtils redisUtils;

	@Autowired
	private static Map<String, EquipmentSpecificIndex> map;

	@Autowired
	private static Map<Integer, String> typeMap;

	@PostConstruct
	public void init() {
		QueryWrapper<EquipmentSpecificIndex> wrapper = new QueryWrapper<>();
		wrapper.eq("is_alarm", 1);
		List<EquipmentSpecificIndex> list = equipmentSpecificIndexMapper.selectList(wrapper);
		map = list.stream().collect(Collectors.toMap(EquipmentSpecificIndex::getEquipmentSpecificName,
				Function.identity(), (key1, key2) -> key2));
		List<EquipmentSpecificIndexAlarmDic> typelist = equipmentSpecificIndexAlarmDicMapper.selectList(null);
		typeMap = typelist.stream().collect(
				Collectors.toMap(EquipmentSpecificIndexAlarmDic::getValue, EquipmentSpecificIndexAlarmDic::getName));
	}

	@Async("jxiopAsyncExecutor")
	public void handleMessage(List<ConsumerRecord<String, String>> record) {
		List<AlarmEvent> alarmEvents = new ArrayList<>();
		List<EquipAlarmEvent> equipAlarmEvents = new ArrayList<>();
		String group = null;
		for (ConsumerRecord<String, String> one : record) {
			JSONObject obj = JSONObject.parseObject(one.value());
			String objName = obj.getString("equipmentSpecificName");
			String indexName = obj.getString("equipmentIndexName");
			String gatewayId = obj.getString("gatewayId");
			String value = obj.getString("value");
			String valueLabel = obj.getString("valueLabel");
			Integer isAlarm = Integer.valueOf(obj.getString("isAlarm"));
			if (!typeMap.containsKey(isAlarm)) {
				continue;
			} else {
				group=typeMap.get(isAlarm);
			}
			if ("升压站".equals(objName)) {
				AlarmEvent alarmEvent = new AlarmEvent();
				alarmEvent.setEventDesc(indexName);
				// alarmEvent.setStationId("");
				// alarmEvent.setStationName("");
				alarmEvent.setGatewayId(gatewayId);
				alarmEvent.setAlarmGroupName(group);
				alarmEvent.setValue(value);
				alarmEvents.add(alarmEvent);
			} else {
				EquipAlarmEvent equipAlarmEvent = new EquipAlarmEvent();
				if (indexName.contains("实时故障") && objName.contains("风机")) {
					// LambdaQueryWrapper<EquipmentSpecificIndex> wrapper = new
					// LambdaQueryWrapper<>();
					// wrapper.eq(EquipmentSpecificIndex::getEquipmentSpecificName, objName);
					// EquipmentSpecificIndex equipmentSpecificIndex =
					// equipmentSpecificIndexMapper.selectOne(wrapper);
					EquipmentSpecificIndex equipmentSpecificIndex = map.get(objName);
					if (equipmentSpecificIndex == null) {
						continue;
					}
					String valueEnum = equipmentSpecificIndex.getValueEnum();
					JSONArray arr = JSONObject.parseArray(valueEnum);
					if(arr==null) 
					{
						continue;
					}
					for (Object o : arr) {
						JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(o));
						if (json.containsKey("key") && value.equals(json.get("key"))) {
							String warn = json.getString("label");
							if (warn.indexOf("备留") == -1) {
								equipAlarmEvent.setEquipName(objName);
								equipAlarmEvent.setEventDesc(indexName);
								equipAlarmEvent.setGatewayId(gatewayId);
								equipAlarmEvent.setValue(warn);
								equipAlarmEvent.setAlarmGroupName(group);
								equipAlarmEvents.add(equipAlarmEvent);
							}
						}
					}
				} else {
					// equipAlarmEvent.setEquipIndex(value);
					equipAlarmEvent.setEquipName(objName);
					equipAlarmEvent.setEventDesc(indexName);
					// equipAlarmEvent.setFrontModule(value);
					equipAlarmEvent.setGatewayId(gatewayId);
					equipAlarmEvent.setValue(value);
					equipAlarmEvent.setAlarmGroupName(group);
					equipAlarmEvents.add(equipAlarmEvent);
				}
			}

		}
		if (alarmEvents.size() > 0) {
			this.baseMapper.save(alarmEvents);
		}
		if (equipAlarmEvents.size() > 0) {
			this.equipAlarmEventMapper.save(equipAlarmEvents);
		}

		// System.out.println(record);
	}

	public ResultsData getFaultEvent(int current, int size, String gatewayId) {
		PageHelper.startPage(current, size);
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, -2);
		List<AlarmEvent> alarmEventList = this.baseMapper.getEventList(gatewayId, calendar.getTime());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar car = Calendar.getInstance();
		alarmEventList.forEach(i -> {
			if ("true".equals(i.getValue())) {
				i.setValue("合");
			} else if ("false".equals(i.getValue())) {
				i.setValue("分");
			}
			i.setStationName("升压站");
			long mills = i.getCreatedTime()/ 1000000 ;
			car.setTimeInMillis(mills);
			// System.out.println(sdf.format(car.getTime()));
			String time = sdf.format(car.getTime());
			if (time.contains("1970-")) {
				mills = i.getCreatedTime();
				car.setTimeInMillis(mills);
				time = sdf.format(car.getTime());
			}
			i.setTime(time);
		});
		PageInfo<EquipAlarmEvent> page = new PageInfo(alarmEventList);
		// 构建平台数据
		DataGridMock DataGridMock = new DataGridMock(current, (int) page.getTotal(), false, current, alarmEventList);
		ColModel colModelStationName = new ColModel("stationName", "stationName", "名称", "名称", "dataGrid",
				"stationName");
		ColModel colModelEventDesc = new ColModel("eventDesc", "eventDesc", "事件描述", "事件描述", "dataGrid", "eventDesc");
		ColModel colModelAlarmGroupName = new ColModel("alarmGroupName", "alarmGroupName", "事件类型", "事件类型", "dataGrid",
				"alarmGroupName");
		ColModel colModelEventTime = new ColModel("time", "time", "事件发生时间", "事件发生时间", "dataGrid", "time");
		ColModel colModelEventMovement = new ColModel("value", "value", "事件值", "事件值", "dataGrid", "value");
		List<ColModel> listColModel = Arrays.asList(colModelStationName, colModelEventDesc, colModelAlarmGroupName,
				colModelEventTime, colModelEventMovement);
		ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
		return resultsData;
	}

}
