package com.gyee.frame.service.stopanalysis;

import com.gyee.frame.common.spring.Constant;
import com.gyee.frame.common.spring.InitialRunner;
import com.gyee.frame.model.auto.*;
import com.gyee.frame.model.custom.DNAVal;
import com.gyee.frame.model.custom.PointData;
import com.gyee.frame.model.custom.StopAnalysisNodeVo;
import com.gyee.frame.service.*;
import com.gyee.frame.util.IRealTimeDataBaseUtil;
import com.gyee.frame.util.RealTimeDataBaseFactory;
import com.gyee.frame.util.SnowflakeIdWorker;
import com.gyee.frame.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.*;


@Service
public class StopAnalysisStaticService {


    @Resource
    private WindTurbineTestingPointAiService windTurbineTestingPointAiService;
    @Resource
    private EquipmentSqlService equipmentSqlService;
    @Resource
    private MismapSqlService mismapSqlService;
    @Resource
    private WindturbineSqlService windturbineSqlService;
    @Resource
    private StopAnalysisService stopAnalysisService;
    @Resource
    private StopAnalysismainService stopAnalysismainService;
    @Resource
    private StopAnalysismainVoService stopAnalysismainVoService;
    @Resource
    private StopAnalysisDetailService stopAnalysisDetailService;
    @Resource
    private StopAnalysisDetailVoService stopAnalysisDetailVoService;

    private final String ZC = "正常";
    private final String ZY = "注意";
    private final String GZ = "关注";

    IRealTimeDataBaseUtil realApiUtil = RealTimeDataBaseFactory.createRealTimeDataBase();

    public List<StopAnalysismainVo> stopAnalysisList(String wpId, String modelId, String typeId) throws Exception {

        List<StopAnalysismainVo> vos = new ArrayList<>();

        if (StringUtils.notEmp(wpId) && StringUtils.notEmp(modelId) && StringUtils.notEmp(typeId)) {

            stopAnalysismainVoService.deleteAll();
            stopAnalysisDetailVoService.deleteAll();
            List<Windturbine> wtls = InitialRunner.wp_wtmap.get(wpId);

            if (typeId.equals("1")) {
                List<String> wtidls = new ArrayList<String>();
                List<String> codejkls = new ArrayList<String>();
                List<String> clxjkls = new ArrayList<String>();
                List<String> fdjjkls = new ArrayList<String>();
                List<String> bjjkls = new ArrayList<String>();
                List<String> zkjkls = new ArrayList<String>();
                List<String> codeztls = new ArrayList<String>();
                for (Windturbine wt : wtls) {
//                    public static final String CLXJKZT = "JKZT002";// 齿轮箱健康状态
//                    public static final String FDJJKZT = "JKZT003";// 发电机健康状态
//                    public static final String BJJKZT = "JKZT004";// 变桨健康
//                    public static final String ZKJKZT = "JKZT005";// 主控健康状态
                    wtidls.add(wt.getId());
                    codejkls.add(Constant.FJJKZT);
                    clxjkls.add(Constant.CLXJKZT);
                    fdjjkls.add(Constant.FDJJKZT);
                    bjjkls.add(Constant.BJJKZT);
                    zkjkls.add(Constant.ZKJKZT);
                    codeztls.add(Constant.FJZT);

                }

                String[] jkpoints = new String[wtidls.size()];
                String[] ztpoints = new String[wtidls.size()];

                String[] clxpoints = new String[wtidls.size()];
                String[] fdjpoints = new String[wtidls.size()];
                String[] bjpoints = new String[wtidls.size()];
                String[] zkpoints = new String[wtidls.size()];

                // 获得训练参数对象
                for (int x = 0; x < wtidls.size(); x++) {

                    WindTurbineTestingPointAi ai1 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtidls.get(x), codejkls.get(x));
                    jkpoints[x] = ai1.getId();
                    WindTurbineTestingPointAi ai2 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtidls.get(x), codeztls.get(x));
                    ztpoints[x] = ai2.getId();
                    WindTurbineTestingPointAi ai3 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtidls.get(x), clxjkls.get(x));
                    clxpoints[x] = ai3.getId();
                    WindTurbineTestingPointAi ai4 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtidls.get(x), fdjjkls.get(x));
                    fdjpoints[x] = ai4.getId();
                    WindTurbineTestingPointAi ai5 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtidls.get(x), bjjkls.get(x));
                    bjpoints[x] = ai5.getId();
                    WindTurbineTestingPointAi ai6 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtidls.get(x), zkjkls.get(x));
                    zkpoints[x] = ai6.getId();

                }

                // 获得风机健康状态结果数组
                DNAVal[] jkvalues = realApiUtil.getRealtimeTagValues(jkpoints);
                // 获得风机实时状态结果数组
                DNAVal[] ztvalues = realApiUtil.getRealtimeTagValues(ztpoints);

                DNAVal[] clxvalues = realApiUtil.getRealtimeTagValues(clxpoints);
                DNAVal[] fdjvalues = realApiUtil.getRealtimeTagValues(fdjpoints);
                DNAVal[] bjvalues = realApiUtil.getRealtimeTagValues(bjpoints);
                DNAVal[] zkvalues = realApiUtil.getRealtimeTagValues(zkpoints);


                for (int x = 0; x < wtls.size(); x++) {
                    Windturbine wt = wtls.get(x);
                    String wtId = wt.getId();
                    double jk = jkvalues[x].DValue;
                    double zt = ztvalues[x].DValue;
                    double clx = clxvalues[x].DValue;
                    double fdj = fdjvalues[x].DValue;
                    double bj = bjvalues[x].DValue;
                    double zk = zkvalues[x].DValue;
                    StopAnalysismainVo vo = new StopAnalysismainVo();
                    vo.setWtid(wt.getId());
                    vo.setModelid(wt.getModelid());
                    if (zt == 2.0) {
                        vo.setModelid(GZ);
                    } else {
                        vo.setJudegvulue(getJudgeVaue(clx,fdj,bj,zk));
                    }
                    //添加雪花主键id
                    String id=SnowflakeIdWorker.getUUID();
                    vo.setId(id);
                    stopAnalysismainVoService.insertSelective(vo);

                    vos.add(vo);
                }

            } else if (typeId.equals("2")) {
                Calendar c = Calendar.getInstance();

                c.set(Calendar.SECOND, 0);
                c.set(Calendar.MILLISECOND, 0);
                Date endDate = c.getTime();
                c.add(Calendar.MINUTE, -10);
                Date beginDate = c.getTime();

                for (int x = 0; x < wtls.size(); x++) {
                    Windturbine wt = wtls.get(x);
                    String wtId = wt.getId();
                    StopAnalysismainVo vo = new StopAnalysismainVo();
                    vo.setWtid(wt.getId());
                    vo.setModelid(wt.getModelid());
//                    public static final String CLXJKZT = "JKZT002";// 齿轮箱健康状态
//                    public static final String FDJJKZT = "JKZT003";// 发电机健康状态
//                    public static final String BJJKZT = "JKZT004";// 变桨健康
//                    public static final String ZKJKZT = "JKZT005";// 主控健康状态
                    WindTurbineTestingPointAi ai1 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtId, Constant.CLXJKZT);
                    List<PointData> pointls1 = realApiUtil.getHistoryDatasSnap(ai1, beginDate.getTime() / 1000, endDate.getTime() / 1000, (long) 10, 60L);
                    WindTurbineTestingPointAi ai2 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtId, Constant.FDJJKZT);
                    List<PointData> pointls2 = realApiUtil.getHistoryDatasSnap(ai1, beginDate.getTime() / 1000, endDate.getTime() / 1000, (long) 10, 60L);
                    WindTurbineTestingPointAi ai3 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtId, Constant.BJJKZT);
                    List<PointData> pointls3 = realApiUtil.getHistoryDatasSnap(ai1, beginDate.getTime() / 1000, endDate.getTime() / 1000, (long) 10, 60L);
                    WindTurbineTestingPointAi ai4 = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtId, Constant.ZKJKZT);
                    List<PointData> pointls4 = realApiUtil.getHistoryDatasSnap(ai1, beginDate.getTime() / 1000, endDate.getTime() / 1000, (long) 10, 60L);


                    if (!pointls1.isEmpty() && !pointls2.isEmpty() && !pointls3.isEmpty() &&!pointls4.isEmpty()) {
                        double csl = 0.0;
                        double lsl = 0.0;
                        double ysl = 0.0;
                        for (int i=0;i<pointls1.size();i++) {

                            PointData point1=pointls1.get(i);
                            PointData point2=pointls2.get(i);
                            PointData point3=pointls3.get(i);
                            PointData point4=pointls4.get(i);

                            double clx = point1.getPointValueInDouble();
                            double fdj = point2.getPointValueInDouble();
                            double bj = point3.getPointValueInDouble();
                            double zk = point4.getPointValueInDouble();

                            String state=getJudgeVaue(clx,fdj,bj,zk);
                            if (state.equals(GZ)) {
                                csl++;
                            } else if (state.equals(ZY)) {
                                lsl++;
                            } else {
                                ysl++;
                            }
                        }

                        if (csl >=2) {
                            vo.setJudegvulue(GZ);
                        } else if (lsl>= 4) {
                            vo.setJudegvulue(ZY);
                        } else {
                            vo.setJudegvulue(ZC);
                        }

                    } else {
                        vo.setJudegvulue(ZC);
                    }
                    //添加雪花主键id
                    String id=SnowflakeIdWorker.getUUID();
                    vo.setId(id);
                    stopAnalysismainVoService.insertSelective(vo);

                    vos.add(vo);
                }

            }

        }
        return vos;
    }

    private String getJudgeVaue(double clx,double fdj,double bj,double zk) {
        double total=clx+fdj+bj+zk;
        if (clx==4|| fdj==4|| bj==4|| zk==4) {
            return GZ;
        } else if (clx==3|| fdj==3|| bj==3|| zk==3) {
            return ZY;
        } else {
            return ZC;
        }
    }

    private String getJudgeVaue(double values) {
        if (values<=2.0) {
            return ZC;
        } else if (values== 3) {
            return ZY;
        } else {
            return GZ;
        }
    }



    private List<StopAnalysisDetailVo> saveLocationTreeByWtId(String mainId,String wtId, String values) throws Exception {

        List<StopAnalysisDetailVo> nodes = new ArrayList<StopAnalysisDetailVo>();
        if (StringUtils.notEmp(wtId)) {


            List<String> codels = new ArrayList<String>();


            codels.add(Constant.CLXJKZT);
            codels.add(Constant.FDJJKZT);
            codels.add(Constant.BJJKZT);
            codels.add(Constant.ZKJKZT);


            String[] points = new String[codels.size()];

            for (int i = 0; i < codels.size(); i++) {

                WindTurbineTestingPointAi ai = windTurbineTestingPointAiService.getWindTurbineTestingPointAi2(wtId, codels.get(i));
                points[i] = ai.getId();
            }

            // 获得风机健康状态结果数组
            DNAVal[] jkvalues = realApiUtil.getRealtimeTagValues(points);


            //随机生成诊断等级
            if (values.equals(ZY)) {
                Random random = new SecureRandom();
                int index = random.nextInt(4);
                jkvalues[index].DValue = 3;
            } else if (values.equals(GZ)) {
                Random random = new SecureRandom();
                int index = random.nextInt(4);
                jkvalues[index].DValue = 4;
            }

            String clxzt = getJudgeVaue(jkvalues[0].DValue);
            String fdjzt = getJudgeVaue(jkvalues[1].DValue);
            String bjzt = getJudgeVaue(jkvalues[2].DValue);
            String zkzt = getJudgeVaue(jkvalues[3].DValue);


            MismapSql mis = mismapSqlService.findMismapSqlById(wtId);
            String wtNum = mis.getMiskey();
            WindturbineSql wt = windturbineSqlService.findWindturbineById(wtNum);

            if (StringUtils.notEmp(wt) && StringUtils.notEmp(wt.getLocation())) {

                List<EquipmentSql> eqls = equipmentSqlService.getEquipmentListByLocation(wt.getLocation());
                if (!eqls.isEmpty()) {

                    for (EquipmentSql eq : eqls) {
                        StopAnalysisDetailVo node = new StopAnalysisDetailVo();
                        node.setId(eq.getLocation());
                        node.setPid(eq.getParent());
                        node.setName(eq.getDescription());
                        node.setWtid(wtId);
                        if (eq.getDescription().indexOf("齿轮箱") != -1) {
                            node.setJudegvulue(clxzt);
                        } else if (eq.getDescription().indexOf("发电机") != -1) {
                            node.setJudegvulue(fdjzt);
                        } else if (eq.getDescription().indexOf("变桨") != -1) {
                            node.setJudegvulue(bjzt);
                        } else if (eq.getDescription().indexOf("塔") != -1) {
                            node.setJudegvulue(zkzt);
                        } else {
                            node.setJudegvulue(ZC);
                        }
                        stopAnalysisDetailVoService.insertSelective(node);
                        //	node.setOpen(true);
                        nodes.add(node);
                    }

                }
            }
        }

        return nodes;
    }




    /**
     * 获取部件结构树
     *
     * @return
     */
    public List<StopAnalysisNodeVo> findLocationTreeByWtId(String mainId,String wtId, String values) throws Exception {

        List<StopAnalysisNodeVo> vos = new ArrayList<>();
        if (StringUtils.notEmp(wtId)) {

            List<StopAnalysisDetailVo> list=stopAnalysisDetailVoService.findStopAnalysisDetailVoList(wtId);
            if(list.isEmpty())
            {
                list=saveLocationTreeByWtId(mainId,wtId, values);

            }

            List<StopAnalysisNodeVo> nodes = new ArrayList<StopAnalysisNodeVo>();
            for(StopAnalysisDetailVo eq:list)
            {
                StopAnalysisNodeVo node=new StopAnalysisNodeVo();
                node.setId(eq.getId());
                node.setPid(eq.getPid());
                node.setName(eq.getName());
                node.setJudegVulue(eq.getJudegvulue());
                //	node.setOpen(true);
                nodes.add(node);
            }

            StopAnalysisTreeUtil treeUtil=new StopAnalysisTreeUtil(nodes);
            vos=treeUtil.buildJSONTree();

        }

        return vos;
    }

    public void saveStopAnalysis(String wpId, String modelId, String typeId)
    {
        StopAnalysis stopAnalysis=new StopAnalysis();
       //添加雪花主键id
        String id=SnowflakeIdWorker.getUUID();

        List<StopAnalysismainVo> mainlist=stopAnalysismainVoService.findStopAnalysismainVoList();
        List<StopAnalysisDetailVo> detaillist=stopAnalysisDetailVoService.findStopAnalysisDetailVoList();


        if(!mainlist.isEmpty() && !detaillist.isEmpty())
        {
            stopAnalysis.setId(id);
            stopAnalysis.setWpid(wpId);
            stopAnalysis.setRuleid(modelId);
            stopAnalysis.setTimetype(typeId);
            stopAnalysis.setJudegdate(new Date());
            stopAnalysisService.insertSelective(stopAnalysis);

            stopAnalysismainService.saveStopAnalysismainList(id,mainlist);
            stopAnalysisDetailService.saveStopAnalysisDetailList(id,detaillist);
        }

    }
    
}
