package com.jiayue.ipfcst.client.protocol2file;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jiayue.ipfcst.client.domain.entity.BaseStatusData;
import com.jiayue.ipfcst.client.domain.entity.WeatherStationStatusData;
import com.jiayue.ipfcst.client.domain.entity.WindTowerStatusData;
import com.jiayue.ipfcst.client.utils.Constant;
import com.syjy.FileUtils;
import com.syjy.TunnelBuilder;
import com.syjy.container.ProtocolDataContainer;
import com.syjy.container.ProtocolTunnelContainer;
import com.syjy.container.RecurringTaskContainer;
import com.syjy.tunnelinfo.BaseTunnelInfo;
import com.syjy.tunnelinfo.DataPoint;
import com.syjy.tunnelinfo.TunnelStatus;
import com.syjy.tunnelinfo.TunnelType;
import com.syjy.tunnelworker.BaseProtocolTunnel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: xiuwei
 * @version:
 */
@Component
@Slf4j
public class StartPro2File implements ApplicationRunner {

    PackageWindTowerOrWeatherStationData packageWindTowerOrWeatherStationData;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<BaseTunnelInfo> tunnels = MyReadConfigFile.readConfigFile();
        if (tunnels.size() == 0) {
            return;
        }
        for (BaseTunnelInfo tunnelInfo : tunnels) {
            if (tunnelInfo instanceof GenerateFileTunnelInfo) {
                new GenerateFileTunnel((GenerateFileTunnelInfo) tunnelInfo).buildTunnel().startTunnel();
            } else if (tunnelInfo instanceof GatherModbusRtuByTcpServerTunnelInfo) {
                new ModbusRtuDataGatherWithTcpServer((GatherModbusRtuByTcpServerTunnelInfo) tunnelInfo).buildTunnel().startTunnel();
            } else {
                TunnelBuilder.buildTunnel(tunnelInfo).startTunnel();
            }
            MyDataPoint mp;
            for (DataPoint d : tunnelInfo.getDataPoints()) {
                mp = (MyDataPoint) d;
                if (mp.getEquipmentType() != null) {
                    if (packageWindTowerOrWeatherStationData == null) {
                        if (mp.getEquipmentType() == EquipmentType.WEATHER_STATION) {
                            packageWindTowerOrWeatherStationData = new PackageWindTowerOrWeatherStationData(new WeatherStationStatusData());
                        } else {
                            packageWindTowerOrWeatherStationData = new PackageWindTowerOrWeatherStationData(new WindTowerStatusData());
                        }
                    } else {
                        this.packageWindTowerOrWeatherStationData.addDataPoint(mp);
                    }

                }
            }
        }
        if (this.packageWindTowerOrWeatherStationData != null) {
            this.packageWindTowerOrWeatherStationData.init();
        }
        RecurringTaskContainer.getInstance().addRecurringTask(10, "打印实时数据入文件", () -> {
            FileUtils.write2File(FileUtils.getResourcesPath(), "realTimeData.log", ProtocolDataContainer.getInstance().toStringFormatted());
            return null;
        });

        RecurringTaskContainer.getInstance().addRecurringTask(60, "向云平台上报通道状态", () -> {
            reportTunnelStatus();
            return null;
        });
        Thread.sleep(30000L);

        RecurringTaskContainer.getInstance().addRecurringTask(60, "向云平台上报设备数据", () -> {
            if (packageWindTowerOrWeatherStationData != null) {
                JSONObject jsonObject = new JSONObject();
                BaseStatusData baseStatusData = packageWindTowerOrWeatherStationData.packageData();
                jsonObject.put("equipmentType", baseStatusData.getEquipmentType());
                jsonObject.put("equipmentData", baseStatusData);
                String resp = HttpUtil.post(Constant.cacheClientConfig.getCloudAddr() + "/environmentDatas", jsonObject.toJSONString());
                if ("0".equals(JSONObject.parseObject(resp).getString("code"))) {
                    log.info("上报环境数据至云平台正常");
                } else {
                    log.info("上报环境数据至云平台异常");
                }
            }
            return null;
        });
    }


    /**
     * 上报通道状态
     */
    public void reportTunnelStatus() {
        Map<String, Object> tunnels = new HashMap<>();
        for (Map.Entry<String, BaseProtocolTunnel> e : ProtocolTunnelContainer.getInstance().getAllTunnel().entrySet()) {
            if (TunnelType.GENERATEFILE == e.getValue().getTunnelType()) {
                if (TunnelStatus.CONNECTEDANDCOMMERROR == e.getValue().getTunnelStatus()) {
                    tunnels.put(e.getValue().getTunnelInfo().getTunnelName(), "生成文件滞留");
                } else {
                    tunnels.put(e.getValue().getTunnelInfo().getTunnelName(), "传输文件正常");
                }
            } else {
                tunnels.put(e.getValue().getTunnelInfo().getTunnelName(), e.getValue().getTunnelStatus().getCnDescribe());
            }
            tunnels.put("time", DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stationCode", Constant.cacheClientConfig.getStationCode());
        jsonObject.put("tunnelStatus", tunnels);
        String resp = HttpUtil.post(Constant.cacheClientConfig.getCloudAddr() + "tunnelStatus/", jsonObject.toJSONString());
        if ("0".equals(JSONObject.parseObject(resp).getString("code"))) {
            log.info("上报通道状态至云平台正常");
        } else {
            log.info("上报通道状态至云平台异常");
        }


    }

}
