 package com.yeejoin.amos.api.alarm.service.impl;

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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.yeejoin.amos.api.alarm.dto.DynamicDetails;
import com.yeejoin.amos.api.alarm.dto.TabContent;
import com.yeejoin.amos.api.alarm.dto.WarningDto;
import com.yeejoin.amos.api.alarm.entity2.JumpConfig;
import com.yeejoin.amos.api.alarm.entity.PointSystem;
import com.yeejoin.amos.api.alarm.mapper.PointSystemMapper;
import com.yeejoin.amos.api.alarm.mapper2.JumpConfigMapper;
import com.yeejoin.amos.api.alarm.service.IPointSystemService;
import com.yeejoin.amos.api.alarm.utils.HttpContentTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @description:
 * @author: tw
 * @createDate: 2023/6/19
 */
@Service
public class PointSystemServiceImpl extends ServiceImpl<PointSystemMapper, PointSystem> implements IPointSystemService {


    private static final Logger logger = LogManager.getLogger(PointSystemServiceImpl.class);
    @Autowired
    PointSystemMapper pointSystemMapper;
    @Value("${power.station.url}")
    private String powerStationUrl;
    private  final  String TABNAME="预警问题";

    private  final  String   TEXT= "text";

    @Value("${power.station.warning:104/data/analysis}")
    private String STATIONWARNING;
    @Autowired
    protected EmqKeeper emqKeeper;

    @Autowired
    private JumpConfigMapper jumpConfigMapper;

    public String getJumpUrlByInfo(String sbbm) {
        List<JumpConfig> jumpConfigs = jumpConfigMapper.selectList(null);
        Map<String, String> collect = jumpConfigs.stream().collect(Collectors.toMap(JumpConfig::getType, JumpConfig::getUrl));
        if (StringUtils.isEmpty(sbbm)) {
            return "";
        }
        if (sbbm.indexOf("BAT") != -1) {
            return collect.get("箱变");
        } else if (sbbm.indexOf("WG") != -1) {
            return collect.get("汇流箱");
        } else if (sbbm.indexOf("WC") != -1) {
            return collect.get("逆变器");
        } else if (sbbm.length() == 12 && sbbm.indexOf("MD") != -1) {
            return collect.get("风机");
        } else if (sbbm.length() > 12 && sbbm.indexOf("MD") != -1) {
            return collect.get("风机子系统");
        } else {
            return collect.get("默认");
        }
    }

    @Async("equipAsyncExecutor")
    public void sendWarningAsync( String date){
        try {

            logger.info("收到告警信息"+date);
            com.alibaba.fastjson.JSONObject messageObj = JSON.parseObject(date);
           String address= messageObj.get("address").toString();
           String value= messageObj.get("value").toString();
           String valueLabe=messageObj.get("valueLabel").toString();
            String gatewayId=messageObj.get("gatewayId").toString();
           this.sendWarning(address,  value, valueLabe,gatewayId);
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }



    @Override
    public void sendWarning(String address, String value,String valueLabe,String gatewayId) {
        try {
            //通过测点地址获取，和对应值 获取kks
            QueryWrapper<PointSystem> pointSystemWrapper = new QueryWrapper<>();
            pointSystemWrapper.lambda().eq(PointSystem::getAddress, address);
            pointSystemWrapper.lambda().eq(PointSystem::getValue, value);
            pointSystemWrapper.lambda().eq(PointSystem::getGatewayId, gatewayId);
            PointSystem pointSystem = pointSystemMapper.selectOne(pointSystemWrapper);
            if (pointSystem == null) {
                throw new RuntimeException("获取kks码失败！");
            }
            //调用获取设备相关信息
            Map<String, String> maps = new HashMap<>();
            maps.put("type", "equipinfo");
            maps.put("kksbm", pointSystem.getKks());
            String data = HttpContentTypeUtil.sendHttpPost(powerStationUrl, maps);

            if (StringUtils.isEmpty(data) || !(Boolean) JSON.parseObject(data).get("success")) {
                throw new RuntimeException("获取设备信息失败！");
            }
            JSONObject json = JSON.parseObject(data);
            JSONObject jsond = (JSONObject) json.get("dataset");
            JSONArray list = (JSONArray) jsond.get("datas");
            JSONObject eqdata = null;
            if (list == null || list.isEmpty()) {
                throw new RuntimeException("获取设备信息失败！");
            }
            eqdata = (JSONObject) list.get(0);

            //组装数据，发送预警
            WarningDto warningDto = setWarningDto(pointSystem, eqdata, valueLabe);
            emqKeeper.getMqttClient().publish(STATIONWARNING, JSON.toJSONString(warningDto).getBytes(), 0, false);

        }  catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("预警消息发送失败！");
    }
    }


    public WarningDto setWarningDto(PointSystem pointSystem,JSONObject eqdata,String valueLabe ){
        SimpleDateFormat sdf =new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time= sdf.format(new Date());
        String warningObjectCode=pointSystem.getKks();
            List<TabContent> tabContent=new ArrayList<>();
            tabContent.add(new TabContent( "KKS编码",   TEXT,  warningObjectCode,  "key1"));
            tabContent.add(new TabContent( "设备名称",  TEXT,  eqdata.get("kksms"),  "key2"));
            tabContent.add(new TabContent( "告警原因",  TEXT,  valueLabe,  "key3"));
            tabContent.add(new TabContent( "发生时间",  TEXT,  time,  "key4"));
            DynamicDetails dynamicDetails=new DynamicDetails( TABNAME,  tabContent);
            List<DynamicDetails> dynamicDetailsList=new ArrayList<>();
            dynamicDetailsList.add(dynamicDetails);
            StringBuilder indexKey=new StringBuilder(pointSystem.getStation())
                    .append("#")
                    .append(pointSystem.getNumber())
                    .append("#")
                    .append(pointSystem.getFunctionNum());
             String indexValue=valueLabe;
             WarningDto WarningDto=new WarningDto(
                    indexKey.toString(),
                    indexValue,
                    null,
                     (String)eqdata.get("sourceAttributionDesc"),
                     (String)eqdata.get("sourceAttribution"),
                    dynamicDetailsList,
                    warningObjectCode,
                    time ,
                    (String)eqdata.get("kksms"),
                     "equip",
                     getJumpUrlByInfo(warningObjectCode)
            );

            return WarningDto;
    }


}
