package com.gyee.wisdom.dataadapter.websocket.backwork;

import com.gyee.wisdom.common.data.timeseries.DoubleTsData;
import com.gyee.wisdom.common.data.timeseries.TsData;
import com.gyee.wisdom.common.data.timeseries.TsPoint;
import com.gyee.wisdom.common.data.windturbine.Windturbine;
import com.gyee.wisdom.dao.things.IThingsPointDao;
import com.gyee.wisdom.dao.windturbine.IWindturbineDao;
import com.gyee.wisdom.dataadapter.domain.timeseries.TsDataService;
import com.gyee.wisdom.dataadapter.domain.timeseries.TsPointService;
import com.gyee.wisdom.dataadapter.websocket.domain.WindturbineData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.*;


/**
 * @descrition: 风机信息缓存类
 * @author:Wanghs
 * @date:2019-09-23
 */
@Component
@Slf4j
public class WindturbineInfoCache {


    @Autowired
    private IWindturbineDao windturbineDao;

    @Autowired
    private IThingsPointDao thingsPointDao;

    @Autowired
    private TsPointService tsPointService;

    @Autowired
    private TsDataService tsDataService;

    @Autowired
    private UniformCodeConfig uniformCodeConfig;


    //key:风机编号,value风机信息
    private Map<String, WindturbineData> windturbineDataMap = new HashMap<>();

    //key:风速测点,value风机信息
    private Map<String, WindturbineData> windSpeedMap = new HashMap<>();

    //key:转速测点,value风机信息
    private Map<String, WindturbineData> rollSpeedMap = new HashMap<>();

    //key:功率测点,value风机信息
    private Map<String, WindturbineData> powerMap = new HashMap<>();

    //key:状态测点,value风机信息
    private Map<String, WindturbineData> statusMap = new HashMap<>();

    //key:挂牌测点,value风机信息
    private Map<String, WindturbineData> lockTypeMap = new HashMap<>();


    public Map<String, WindturbineData> getWindturbineDataMap() {
        return windturbineDataMap;
    }

    /**
     * @param
     * @return boolean
     * @description 风机信息初始化
     * @author wanghs
     * @date 2019-09-23
     */
    public boolean init() {

        boolean result = false;
        try {
            List<Windturbine> wList = windturbineDao.find();
            for (int i = 0; i < wList.size(); i++) {
                Windturbine things = wList.get(i);

                if (things.getWindPowerStationId().contains("FDC")) {

                    WindturbineData wData = new WindturbineData();
                    wData.setModelId(things.getModelId());
                    wData.setWindturbineId(things.getId());
                    wData.setStationId(things.getWindPowerStationId());
                    wData.setProjectId(things.getProjectId());
                    List<String> uniformcodeList = new ArrayList();

                    uniformcodeList.add(uniformCodeConfig.getWindSpeedCode());
                    uniformcodeList.add(uniformCodeConfig.getRollSpeedCode());
                    uniformcodeList.add(uniformCodeConfig.getPowerCode());
                    uniformcodeList.add(uniformCodeConfig.getStatusCode());
                    uniformcodeList.add(uniformCodeConfig.getLockCode());

                    String[] uniformcodeArray = new String[uniformcodeList.size()];
                    uniformcodeList.toArray(uniformcodeArray);

                   // List<TsPoint> pointList = thingsPointDao.findTsPointByUnformCodes("windturbine", things.getId(), uniformcodeArray);
                    List<TsPoint> pointList=tsPointService.getTsPoint("windturbine", things.getId(), uniformcodeArray);
                    for (int j = 0; j < pointList.size(); j++) {
                        TsPoint point = pointList.get(j);
                        if (point.getUniformCode().equals(uniformCodeConfig.getWindSpeedCode())) {
                            if (!windSpeedMap.containsKey(point.getId()))
                                windSpeedMap.put(point.getId(), wData);
                        } else if (point.getUniformCode().equals(uniformCodeConfig.getRollSpeedCode())) {
                            if (!rollSpeedMap.containsKey(point.getId()))
                                rollSpeedMap.put(point.getId(), wData);
                        } else if (point.getUniformCode().equals(uniformCodeConfig.getPowerCode())) {
                            if (!powerMap.containsKey(point.getId()))
                                powerMap.put(point.getId(), wData);
                        } else if (point.getUniformCode().equals(uniformCodeConfig.getStatusCode())) {
                            if (!statusMap.containsKey(point.getId()))
                                statusMap.put(point.getId(), wData);
                        } else if (point.getUniformCode().equals(uniformCodeConfig.getLockCode())) {
                            if (!lockTypeMap.containsKey(point.getId()))
                                lockTypeMap.put(point.getId(), wData);
                        }
                    }
                    if (!windturbineDataMap.containsKey(things.getId())) {
                        windturbineDataMap.put(things.getId(), wData);
                    }
                }
            }

            log.info("风机缓存初始化完毕");
            result = true;
        } catch (Exception ex) {
            log.info("风机信息缓存初始化异常" + ex.getMessage());
        } finally {
            return result;
        }

    }

    public void start() {

        try {
            getUpdateThread().start();

        } catch (Exception ex) {

        }
    }

    Thread getUpdateThread() {
        return new Thread(new Runnable() {
            public void run() {
                System.out.println("实时风机启停计算线程启动");
                while (true) {
                    try {
                        updateWinduturbineInfo();
                        Thread.sleep(1000);

                    } catch (Exception ex) {

                    }
                }
            }
        });
    }

    private void updateWinduturbineInfo() {

        //Instant st = Instant.now();
        boolean windSpeedUpdateSuccess = updateInfoByMap(windSpeedMap, "windSpeed");
        if (!windSpeedUpdateSuccess)
            log.info("风机风速更新失败");
        boolean rollSpeedUpdateSuccess = updateInfoByMap(rollSpeedMap, "rollSpeed");
        if (!rollSpeedUpdateSuccess)
            log.info("风机转速更新失败");
        boolean powerUpdateSuccess = updateInfoByMap(powerMap, "power");
        if (!powerUpdateSuccess)
            log.info("风机功率更新失败");
        boolean statusUpdateSuccess = updateInfoByMap(statusMap, "status");
        if (!statusUpdateSuccess)
            log.info("风机状态更新失败");
        boolean lockUpdateSuccess = updateInfoByMap(lockTypeMap, "lock");
        if (!lockUpdateSuccess)
            log.info("风机挂牌状态更新失败");
    }

    private boolean updateInfoByMap(Map<String, WindturbineData> updateMap, String type) {

        boolean success = false;
        try {
            String[] pointArr = new String[updateMap.size()];
            Object[] keyArr = updateMap.keySet().toArray();
            for (int i = 0; i < keyArr.length; i++) {
                pointArr[i] = keyArr[i].toString();
            }
            Map<String, TsData> mapResult = tsDataService.getLatest(pointArr);
            if (mapResult != null) {
                Iterator<Map.Entry<String, TsData>> entries = mapResult.entrySet().iterator();
                if (entries != null) {
                    while (entries.hasNext()) {
                        Map.Entry<String, TsData> entry = entries.next();
                        String key = entry.getKey();
                        TsData tsData = entry.getValue();
                        if (tsData instanceof DoubleTsData) {
                            DoubleTsData doubleTsData = (DoubleTsData) tsData;
                            if (updateMap.containsKey(key)) {
                                WindturbineData wData = updateMap.get(key);
                                switch (type) {
                                    case "windSpeed":
                                        wData.setWindSpeed(doubleTsData.getDoubleValue());
                                        break;
                                    case "rollSpeed":
                                        wData.setRollSpeed(doubleTsData.getDoubleValue());
                                        break;
                                    case "power":
                                        wData.setPower(doubleTsData.getDoubleValue());
                                        break;
                                    case "status":
                                        wData.setStatus(doubleTsData.getDoubleValue());
                                        wData.setTs(doubleTsData.getTs());
                                        break;
                                    case "lock":
                                        wData.setLockValue(doubleTsData.getDoubleValue());
                                        break;
                                    default:
                                        break;
                                }

                            }
                        }
                    }
                }
            }
            success = true;
            return success;
        } catch (Exception ex) {
            log.info("风机信息更新异常" + ex.getMessage());
        } finally {
            return success;
        }


    }
}
