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

import com.gyee.wisdom.common.data.photovoltaic.Inverter;
import com.gyee.wisdom.common.data.photovoltaic.InverterBasicData;
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.dao.pv_inverter.IInverterDao;
import com.gyee.wisdom.dao.things.IThingsPointDao;
import com.gyee.wisdom.dataadapter.domain.timeseries.TsDataService;
import com.gyee.wisdom.dataadapter.help.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @descrition:光伏逆变器信息
 * @author:WXW
 * @date:2020-04-28
 */
@Component
@Slf4j
public class PhotovoltaicInverterServer implements Runnable
{

    @Autowired
    private IInverterDao iInverterDao;
    @Autowired
    private IThingsPointDao thingsPointDao;
    @Autowired
    private TsDataService tsDataService;

    private Map<String, InverterBasicData> inverterMap = new HashMap<>();
    private Map<String, InverterBasicData> pvIMap = new HashMap<>();
    private Map<String, InverterBasicData> pvUMap = new HashMap<>();
    private Map<String, InverterBasicData> pvWMap = new HashMap<>();
    private Map<String, InverterBasicData> pvSMap = new HashMap<>();

    @Value("${uniformcode.pv_I:AIG060}")
    private String pv_I;
    @Value("${uniformcode.pv_U:AIG061}")
    private String pv_U;
    @Value("${uniformcode.pv_P:AI130}")
    private String pv_P;
    @Value("${uniformcode.pv_statue:FJZT}")
    private String pv_S;

    private String[] pv_uniformCode;

    public boolean allowUpdatePVData=true;

    public Map<String,InverterBasicData> getInverterMap()
    {
        return inverterMap;
    }

    public boolean init()
    {
        try
        {
            pv_uniformCode = new String[]{pv_I, pv_U, pv_P, pv_S};
            // 查询所有光伏逆变器基本信息
            List<Inverter> inverterList = iInverterDao.findAllInverter();
            //
            inverterList.forEach(i ->
                    {
                        // 变为光伏逆变器数据信息
                        InverterBasicData pvIVT = new InverterBasicData(i);
                        List<TsPoint> pointList = thingsPointDao.findTsPointByUnformCodes("windturbine", i.getId(), pv_uniformCode);
                        pointList.forEach(p -> // 按照标签点存放到对应类型的Map中
                                {
                                    if (pv_I.equals(p.getUniformCode()) && !pvIMap.containsKey(p.getId()))//电流
                                    {
                                        pvIMap.put(p.getId(), pvIVT);
                                    }
                                    else if (pv_U.equals(p.getUniformCode()) && !pvUMap.containsKey(p.getId()))//电压
                                    {
                                        pvUMap.put(p.getId(), pvIVT);
                                    }
                                    else if (pv_P.equals(p.getUniformCode()) && !pvWMap.containsKey(p.getId()))//功率
                                    {
                                        pvWMap.put(p.getId(), pvIVT);
                                    }
                                    else if (pv_S.equals(p.getUniformCode()) && !pvSMap.containsKey(p.getId()))//状态
                                    {
                                        pvSMap.put(p.getId(), pvIVT);
                                    }
                                }
                        );

                        if (!inverterMap.containsKey(i.getId())) // 所有光伏的数据表
                        {
                            inverterMap.put(i.getId(), pvIVT);
                        }
                    }
            );
            Constant.d("[光伏]信息缓存              [OK]! \n");
            return true;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            Constant.d("[光伏]信息缓存              [Error]!\n" + ex.getMessage());
            return false;
        }
    }

    private void updatePVData()
    {
        updateMapOf(PVDataType.I);
        updateMapOf(PVDataType.U);
        updateMapOf(PVDataType.P);
        updateMapOf(PVDataType.S);
        //Constant.dOneLine(Constant.dateFormat.format(new Date()));
//        Constant.dOneLine((updateMapOf(PVDataType.I) ? " 光伏I " : " 光伏I[Error]! "));
//        Constant.dOneLine((updateMapOf(PVDataType.U) ? " 光伏U " : " 光伏U[Error]! "));
//        Constant.dOneLine((updateMapOf(PVDataType.P) ? " 光伏P " : " 光伏P[Error]! "));
//        Constant.dOneLine((updateMapOf(PVDataType.S) ? " 光伏S " : " 光伏S[Error]! "));
        //Constant.d(Constant.dateFormat.format(new Date()));
    }

    private boolean updateMapOf(PVDataType pvT)
    {
        try
        {
            Map<String, InverterBasicData> refPointMap;
            switch (pvT)
            {
                case I:
                {
                    refPointMap = pvIMap;
                }
                break;
                case U:
                {
                    refPointMap = pvUMap;
                }
                break;
                case P:
                {
                    refPointMap = pvWMap;
                }
                break;
                case S:
                {
                    refPointMap = pvSMap;
                }
                break;
                default:
                {
                    return false;
                }
            }
            //String [] piontIDKeys=refPointMap.keySet().toArray(new String[0]);
            Map<String, TsData> tsDataMap = tsDataService.getLatest(refPointMap.keySet().toArray(new String[0]));
            if (tsDataMap != null)
            {
                tsDataMap.entrySet().forEach(
                        kv ->
                        {
                            if (kv.getValue() instanceof DoubleTsData && refPointMap.containsKey(kv.getKey())) // 数值类型
                            {
                                switch (pvT)
                                {
                                    case I:
                                    {
                                        refPointMap.get(kv.getKey()).setI(((DoubleTsData) kv.getValue()).getDoubleValue());
                                    }
                                    break;
                                    case U:
                                    {
                                        refPointMap.get(kv.getKey()).setU(((DoubleTsData) kv.getValue()).getDoubleValue());
                                    }
                                    break;
                                    case P:
                                    {
                                        refPointMap.get(kv.getKey()).setP(((DoubleTsData) kv.getValue()).getDoubleValue());
                                    }
                                    break;
                                    case S:
                                    {
                                        refPointMap.get(kv.getKey()).setStatue(((DoubleTsData) kv.getValue()).getDoubleValue());
                                        refPointMap.get(kv.getKey()).setTs(kv.getValue().getTs());
                                    }
                                    break;
                                    default:
                                        break;
                                }
                            }
                        }
                );
            }
            return true;
        }
        catch (Exception e)
        {
            Constant.d(pvT.toString()+"  \n");
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public void run()
    {
        Constant.d("-------    [光伏] 基本信息服务启动    --------");
        if(init())
        {
            allowUpdatePVData=true;
            while (allowUpdatePVData)
            {
                try
                {
                    updatePVData();
                    Thread.sleep(1800);
                }
                catch(Exception ex)
                {
                    Constant.d("光伏逆变器数据更新:       "+Constant.dateFormat.format(new Date())+"\n");
                    ex.printStackTrace();
                }
            }
        }
    }

    enum PVDataType
    {
        I,
        U,
        P,
        S
    }
}
