package com.yeejoin.equipmanage.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.yeejoin.equipmanage.common.entity.EquipmentSpecific;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecificIndex;
import com.yeejoin.equipmanage.common.entity.PointSystem;
import com.yeejoin.equipmanage.common.utils.HttpContentTypeUtil;
import com.yeejoin.equipmanage.dto.DynamicDetails;
import com.yeejoin.equipmanage.dto.TabContent;
import com.yeejoin.equipmanage.dto.WarningDto;
import com.yeejoin.equipmanage.mapper.PointSystemMapper;
import com.yeejoin.equipmanage.service.IPointSystemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;

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

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

    @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;

    @Override
    public void sendWarning(String address, String value,String valueLabe) {
        try {
            //通过测点地址获取，和对应值 获取kks
            QueryWrapper<PointSystem> pointSystemWrapper = new QueryWrapper<>();
            pointSystemWrapper.lambda().eq(PointSystem::getAddress, address);
            pointSystemWrapper.lambda().eq(PointSystem::getValue, value);
            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")
            );

            return WarningDto;
    }


}
