package com.yuchen.saas.park.service.pull.input;


import com.alibaba.fastjson.JSON;
import com.yuchen.saas.message.api.feign.ws.WebSocketFeignServer;
import com.yuchen.saas.message.api.vo.NoticeVo;
import com.yuchen.saas.park.api.entity.park.PmgBatHandlerWarning;
import com.yuchen.saas.park.api.entity.park.PmgBatRfidInfo;
import com.yuchen.saas.park.api.entity.park.PmgBatWarningInfo;
import com.yuchen.saas.park.api.vo.park.DeviceEventVo;
import com.yuchen.saas.park.api.vo.park.PmgBatWarningCategoryVo;
import com.yuchen.saas.park.service.pull.untils.StompClient;
import com.yuchen.saas.park.service.service.IHandlerWarningService;
import com.yuchen.saas.park.service.service.IWarningCategoryService;
import com.yuchen.saas.park.service.service.IWarningInfoService;
import com.yuchen.saas.park.service.service.PmgBatRfidInfoService;
import com.yuchen.saas.parking.api.vo.IoTEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class RfidInput {

  final String DEVICEKEY = "8gF31iKdiJe0NW3a";
  final String DEVICENAME = "8gF31iKdiJe0NW31";
  final String IDENTITY = "discovery_rfid";

  private static final Logger LOGGER = LoggerFactory.getLogger(RfidInput.class);

  private final Map<String, Long> states = new ConcurrentHashMap<>();

  private static List<String> epcs = new ArrayList<>();

  @Autowired
  private PmgBatRfidInfoService pmgBatRfidInfoService;

  @Autowired
  private IWarningCategoryService iWarningCategoryService;

  @Autowired
  private IHandlerWarningService iHandlerWarningService;

  @Autowired
  private WebSocketFeignServer pushService;

  @Autowired
  private IWarningInfoService iWarningInfoService;

  @Value("${rfid.lost.time}")
  private Long lostTime;

  @Autowired
  StompClient stompClient;

  //@Scheduled(cron = "0/10 * *  * * ?") modify by qianjiang
  public void waterMeterMonitorSchedule() {
    try {
      List<String>  epcList = pmgBatRfidInfoService.getEpc();
      if(epcList.size() == 0) {
        LOGGER.debug("无标签");
        return;
      }

//    List<String> list = nestRedis.get("epc");
      epcList.forEach(epc -> {
        System.out.println("标签"+epc);
        Long current = System.currentTimeMillis() / 1000L;
        Map<String, Object> propValues = new HashMap<>();
        if (states.containsKey(epc) && states.get(epc) > current - lostTime) {
          LOGGER.debug("标签 {} 状态正常, 最后次上报时间 {}", epc, states.get(epc));
//        // 状态
//        propValues.put("state", "1");
//        deviceEventVo.setOut(propValues);
//        iStompClient.postEvent(JSON.toJSONString(deviceEventVo));
        } else {
          // 丢失预警
          LOGGER.warn("标签 {} 丢失状态, 最后次上报时间 {}", epc, states.get(epc));

              PmgBatRfidInfo pmgBatRfidInfo = pmgBatRfidInfoService.getByEpc(epc);


              if(pmgBatRfidInfo.getEpc() == null){
                LOGGER.warn("epc 为空", epc, states.get(epc));
                return;
              }
              propValues.put("state", "0");
              propValues.put("value",pmgBatRfidInfo.getSomethingName());
//        iStompClient.postEvent(JSON.toJSONString(deviceEventVo));
              propValues.put("time",System.currentTimeMillis()/1000L);
              PmgBatWarningCategoryVo pmgBatWarningCategoryVo = iWarningCategoryService.getByIdentity(IDENTITY);
              if(pmgBatWarningCategoryVo.getIdentity() == null){
                LOGGER.warn("报警事件为空", epc, states.get(epc));
                return;
              }
                Long time = System.currentTimeMillis()/1000L;

                // 告警事件处理
                PmgBatHandlerWarning pmgBatHandlerWarning = iHandlerWarningService.getHandlerResult(DEVICEKEY,
                        DEVICENAME);
                if(pmgBatHandlerWarning != null) {
                  if(pmgBatHandlerWarning.getEndTime() != null && time < pmgBatHandlerWarning.getEndTime()) {
                    return;
                  }
                }

                LOGGER.info("结果为：{}",pmgBatHandlerWarning);
                // 封装数据发送到stomp
                DeviceEventVo deviceEventVo = new DeviceEventVo();
                deviceEventVo.setParkId(String.valueOf(pmgBatRfidInfo.getParkId()));
                deviceEventVo.setEquipmentName(pmgBatRfidInfo.getSomethingName());
                deviceEventVo.setProduct("");
                deviceEventVo.setOut(propValues);
                deviceEventVo.setPosition(pmgBatRfidInfo.getPlace());
                deviceEventVo.setLevel(pmgBatWarningCategoryVo.getLevel());
                deviceEventVo.setLevelName(pmgBatWarningCategoryVo.getLevelName());
                deviceEventVo.setRemark(pmgBatWarningCategoryVo.getRemark());
                deviceEventVo.setParkId(String.valueOf(pmgBatRfidInfo.getParkId()));
                deviceEventVo.setIdentify(IDENTITY);
                deviceEventVo.setProductKey(DEVICEKEY);
                deviceEventVo.setDeviceName(DEVICENAME);
                deviceEventVo.setEventTime(time);
                pushService.postEvent(NoticeVo.getByParkIdAndData(String.valueOf(pmgBatRfidInfo.getParkId()), JSON.toJSONString(deviceEventVo)));

                // 存入mysql
                // 封装数据保存历史报警
                PmgBatWarningInfo pmgBatWarningInfo = new PmgBatWarningInfo();
                pmgBatWarningInfo.setProductKey(DEVICEKEY);
                pmgBatWarningInfo.setDeviceName(DEVICENAME);
                pmgBatWarningInfo.setIdentity(IDENTITY);
                pmgBatWarningInfo.setCreateDept(pmgBatRfidInfo.getCreateDept());
                pmgBatWarningInfo.setRemark(pmgBatWarningCategoryVo.getRemark());
                pmgBatWarningInfo.setLevel(pmgBatWarningCategoryVo.getLevel());
                pmgBatWarningInfo.setIsHandling("0");
                pmgBatWarningInfo.setName(pmgBatRfidInfo.getSomethingName());
                pmgBatWarningInfo.setLevelName(pmgBatWarningCategoryVo.getLevelName());
                pmgBatWarningInfo.setParkId(pmgBatRfidInfo.getParkId());
                pmgBatWarningInfo.setEventTime(time);
                iWarningInfoService.save(pmgBatWarningInfo);

                // 已处理未处理
                stompClient.getWarningHandlerResult(String.valueOf(pmgBatRfidInfo.getParkId()));

            }
      });
    }catch (Exception e){
      e.printStackTrace();
    }
  }

  public void input( IoTEvent ioTEvent) {
    try {

      String epc = String.valueOf(ioTEvent.getOut().get("rfid_no"));
      if(epc == null) {
        throw new Exception("非法标签信息");
      }
      states.put(epc,System.currentTimeMillis()/1000L);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
