package com.yeejoin.amos.boot.module.hygf.biz.emqx;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.module.hygf.api.dto.MaintenanceDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.HYGFMaintenanceTickets;
import com.yeejoin.amos.boot.module.hygf.api.entity.JpStation;
import com.yeejoin.amos.boot.module.hygf.api.entity.Maintenance;
import com.yeejoin.amos.boot.module.hygf.api.entity.TdHygfJpInverterWarn;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HYGFMaintenanceTicketsMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.JpStationMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.MaintenanceMapper;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.TdHygfJpInverterWarnMapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.component.emq.EmqxListener;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class MaintenanceResultHandlerMessage extends EmqxListener {
    public static final String WARNING_RESULT_MESSAGE = "+/warning/result";
    public static final String HYGF_MAINTENANCE_RESULT_MESSAGE = "hygfmaintenance";

    @Autowired
    EmqKeeper emqKeeper;
    //工单mapper
    @Autowired
    HYGFMaintenanceTicketsMapper hygfMaintenanceTicketsMapper;
    @Autowired
    JpStationMapper jpStationMapper;
    @Autowired
    TdHygfJpInverterWarnMapper tdHygfJpInverterWarnMapper;
    @Autowired
    MaintenanceMapper maintenanceMapper;

    @PostConstruct
    void init() throws Exception {
        emqKeeper.subscript(WARNING_RESULT_MESSAGE, 2, this);
    }

    @Override
    public void processMessage(String topic, MqttMessage message) throws Exception {
        if (topic.contains(HYGF_MAINTENANCE_RESULT_MESSAGE)) {
            log.info("收到户用光伏工单推送-消息{}", new String(message.getPayload()));
            JSONObject jsonObject = JSON.parseObject(new String(message.getPayload()));
            JxiopUpdateMaintenance(jsonObject);
        }
    }

    @Async("async")
    public void JxiopUpdateMaintenance(JSONObject jsonObject) {
        if (jsonObject.containsKey("rawData")) {
            JSONObject rawData = jsonObject.getJSONObject("rawData");
            JSONObject bizInfo = rawData.getJSONObject("bizInfo");
            JSONArray jsonArray = bizInfo.getJSONArray("dynamicDetails");
            Map<String, Object> specialMap = new HashMap<>();
            if (jsonArray.size() > 0) {
                jsonObject = (JSONObject) jsonArray.get(0);
                specialMap = jsonObject.get("specialMap") == null ? null : jsonObject.getJSONObject("specialMap").toJavaObject(Map.class);
            }
            HYGFMaintenanceTickets hygfMaintenanceTickets = new HYGFMaintenanceTickets();
            String stationid = specialMap.get("stationId") == null ? null : specialMap.get("stationId").toString();
            Long warningId = specialMap.containsKey("warningId") ? Long.valueOf(specialMap.get("warningId").toString()) : 0L;
            if(warningId>0){
               List<HYGFMaintenanceTickets> hygfMaintenanceTicketsList = hygfMaintenanceTicketsMapper.selectList(new QueryWrapper<HYGFMaintenanceTickets>().eq("warning_id", warningId).eq("handler_status","未处理"));
                if (hygfMaintenanceTicketsList.size()>0) {
                    return;
                }
            }
            String sncode = specialMap.containsKey("inverterSncode")?specialMap.get("inverterSncode").toString():"";
            String mantainancePersonId = specialMap.get("maintenancePersonId").toString();
            JpStation jpStation = jpStationMapper.selectOne(new QueryWrapper<JpStation>().eq("third_station_id", stationid));
            if (ObjectUtil.isEmpty(jpStation)) {
                jpStation = jpStationMapper.selectById(stationid);
            }
            TdHygfJpInverterWarn tdHygfJpInverterWarn = tdHygfJpInverterWarnMapper.getInverTerWarnByparams(warningId, sncode, stationid);
//            hygfMaintenanceTickets.setHandlerStatus("未处理");
            MaintenanceDto maintenance = maintenanceMapper.selectOneById(Long.valueOf(mantainancePersonId));
            hygfMaintenanceTickets.setStationId(stationid);
            hygfMaintenanceTickets.setWarningId(warningId);
            hygfMaintenanceTickets.setMaintenancePersonId(mantainancePersonId);
            if (ObjectUtil.isNotEmpty(maintenance)) {
                hygfMaintenanceTickets.setMaintenancePersonName(maintenance.getName());
                hygfMaintenanceTickets.setMaintenancePersonPhone(maintenance.getTelephone());
            }
            if (ObjectUtil.isNotEmpty(jpStation)) {
                //场站名称
                hygfMaintenanceTickets.setStationName(jpStation.getName());
                //区域公司编码
                hygfMaintenanceTickets.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
                //经销商orgCode
                hygfMaintenanceTickets.setAmosCompanyCode(jpStation.getAmosCompanyCode());
                //地址
                hygfMaintenanceTickets.setStationAddress(jpStation.getAddress());
                //经度
                hygfMaintenanceTickets.setStationLongitude(jpStation.getLongitude());
                //纬度
                hygfMaintenanceTickets.setStationLatitude(jpStation.getLatitude());
                //电站联系人电话
                hygfMaintenanceTickets.setStationContactPhone(jpStation.getUserPhone());
                // 电站联系人
                hygfMaintenanceTickets.setStationContact(jpStation.getStationContact());
                //业主姓名
                hygfMaintenanceTickets.setOwnerName(jpStation.getUserName());
                if (ObjectUtil.isEmpty(hygfMaintenanceTickets.getStationContact())) {
                    hygfMaintenanceTickets.setStationContact(jpStation.getUserName());
                }
            }
            hygfMaintenanceTickets.setInverterSn(sncode);
            if(specialMap.containsKey("warningLevel")){
                hygfMaintenanceTickets.setWarningLevel(specialMap.get("warningLevel").toString());
            }
            if(specialMap.containsKey("warningContent")){
                hygfMaintenanceTickets.setWarningContent(specialMap.get("warningContent").toString());

            }
            if(ObjectUtil.isNotNull(specialMap.get("taskStartTime"))){
                hygfMaintenanceTickets.setTaskStartTime(new Date( Long.valueOf(specialMap.get("taskStartTime").toString())));
            }
            if(ObjectUtil.isNotNull(specialMap.get("taskEndTime"))){
                hygfMaintenanceTickets.setTaskEndTime(new Date( Long.valueOf(specialMap.get("taskEndTime").toString())));
            }

            if (ObjectUtil.isNotEmpty(tdHygfJpInverterWarn)) {
                hygfMaintenanceTickets.setWarningLevel(tdHygfJpInverterWarn.getLevel());
                hygfMaintenanceTickets.setWarningContent(tdHygfJpInverterWarn.getContent());
                hygfMaintenanceTickets.setWarningStatus(tdHygfJpInverterWarn.getState());
                //告警等级
                hygfMaintenanceTickets.setWarningStartTime(new Date(tdHygfJpInverterWarn.getStartTime()));
                hygfMaintenanceTickets.setTicketType("手动");
            }


            hygfMaintenanceTicketsMapper.insert(hygfMaintenanceTickets);
//            if (ObjectUtil.isNotEmpty(tdHygfJpInverterWarn)) {
//                tdHygfJpInverterWarn.setHandlerStatus("处理中");
//                tdHygfJpInverterWarnMapper.insert(tdHygfJpInverterWarn);
//            }
            log.info("创建运维工单成功{}", JSON.toJSONString(hygfMaintenanceTickets));
        }
    }
}
