package com.huatek.busi.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.huatek.busi.common.UploadCycle;
import com.huatek.busi.common.util.DecimalUtil;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.CubicleNumberMapper;
import com.huatek.busi.mapper.GeneratorNumberMapper;
import com.huatek.busi.mapper.SiteUploadCycleMapper;
import com.huatek.busi.mapper.TransformerNumberMapper;
import com.huatek.busi.service.CubicleNumberService;
import com.huatek.busi.service.GeneratorNumberService;
import com.huatek.busi.util.CalcUtil;
import com.huatek.busi.util.DateUtil;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@Service(interfaceClass = GeneratorNumberService.class)
@Transactional(rollbackFor = Exception.class)
public class GeneratorNumberServiceImpl implements GeneratorNumberService {

    @Autowired
    GeneratorNumberMapper generatorNumberMapper;

    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private GeneratorNumberService generatorNumberService;

    @Autowired
    private TransformerNumberMapper transformerNumberMapper;

    @Autowired
    private SiteUploadCycleMapper siteUploadCycleMapper;

    @Override
    public EquipmentSumNumber findSumGeneratorNumber() throws Exception{
        //查询所有站点Id
        List<SiteData> findSite = transformerNumberMapper.findSiteData() ;

        EquipmentSumNumber findSumNumber = new EquipmentSumNumber();
        //查詢所有裝置
        List<EquipmentSensor> equipmentList = generatorNumberMapper.findEquipmentVoList();
        boolean flag = false;
        int count = 0;
        String ids="";
        String faultIds="";
        for (SiteData siteData:findSite) {
            String siteId = siteData.getId();
            for (EquipmentSensor equipmentTemperatureCache : equipmentList) {
                String sensorId = equipmentTemperatureCache.getSensorId();
                String subSensorID = sensorId.substring(15, 17);
                //获取当前系统时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String newDate = sdf.format(new Date());
                if (subSensorID.equals("07")) {
                    //获取设备最新一条时间
                    String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                    //获取设备间隔时间
                    String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.fdjzz + "");
                    if (cycle != null) {
                        int temp = Integer.parseInt(cycle);
                        int cycleVo = temp + 2;
                        BigDecimal timeValue = DecimalUtil.getVal(cycleVo);
                        int oldTime = timeValue.intValue();
                        Date dt = sdf.parse(newDate);
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(dt);
                        //计算时间差
                        rightNow.add(Calendar.MINUTE, -oldTime);
                        Date sub = rightNow.getTime();
                        String reStr = sdf.format(sub);
                        Integer finalValue = newDateValue.compareTo(reStr);
                        if (finalValue > 0) {
                            count += 1;
                            ids+=sensorId+",";
                        }else{
                            faultIds+=sensorId+",";
                        }
                    }
                }
                if (subSensorID.equals("22")) {
                    //获取设备最新一条时间
                    String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                    //获取设备间隔时间
                    String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.fdjzz + "");
                    if (cycle != null) {
                        int temp = Integer.parseInt(cycle);
                        int cycleVo = temp + 2;
                        BigDecimal timeValue = DecimalUtil.getVal(cycleVo);
                        int oldTime = timeValue.intValue();
                        Date dt = sdf.parse(newDate);
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(dt);
                        //计算时间差
                        rightNow.add(Calendar.MINUTE, -oldTime);
                        Date sub = rightNow.getTime();
                        String reStr = sdf.format(sub);
                        Integer finalValue = newDateValue.compareTo(reStr);
                        if (finalValue > 0) {
                            count += 1;
                            ids+=sensorId+",";
                        }else{
                            faultIds+=sensorId+",";
                        }
                    }
                }
                if (subSensorID.equals("0F")) {
                    //获取设备最新一条时间
                    String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                    //获取设备间隔时间
                    String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.fdjzz + "");
                    if (cycle!= null) {
                        int temp = Integer.parseInt(cycle);
                        int cycleVo = temp + 2;
                        BigDecimal timeValue = DecimalUtil.getVal(cycleVo);
                        int oldTime = timeValue.intValue();
                        Date dt = sdf.parse(newDate);
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(dt);
                        //计算时间差
                        rightNow.add(Calendar.MINUTE, -oldTime);
                        Date sub = rightNow.getTime();
                        String reStr = sdf.format(sub);
                        Integer finalValue = newDateValue.compareTo(reStr);
                        if (finalValue > 0) {
                            count += 1;
                            ids+=sensorId+",";
                        }else{
                            faultIds+=sensorId+",";
                        }
                    }
                }
                if (subSensorID.equals("1F")) {
                    //获取设备最新一条时间
                    String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                    //获取设备间隔时间
                    String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.fdjzz + "");
                    if (cycle!= null) {
                        int temp = Integer.parseInt(cycle);
                        int cycleVo = temp + 2;
                        BigDecimal timeValue = DecimalUtil.getVal(cycleVo);
                        int oldTime = timeValue.intValue();
                        Date dt = sdf.parse(newDate);
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(dt);
                        //计算时间差
                        rightNow.add(Calendar.MINUTE, -oldTime);
                        Date sub = rightNow.getTime();
                        String reStr = sdf.format(sub);
                        Integer finalValue = newDateValue.compareTo(reStr);
                        if (finalValue > 0) {
                            count += 1;
                            ids+=sensorId+",";
                        }else{
                            faultIds+=sensorId+",";
                        }
                    }
                }


                //计算发电机外挂在线数
                findSumNumber.setSumNormal(count);
            }
            //查询发电机总外挂设备数
            int countSum = generatorNumberMapper.finSumNumber(siteId);
            //查询gis外挂总异常数
            int countFault = countSum - count;
            findSumNumber.setSumNumber(countSum);
            findSumNumber.setSumNormal(count);
            findSumNumber.setSumFault(countFault);
            findSumNumber.setSiteId(siteId);
            findSumNumber.setType("06");
            String type = "06";
            findSumNumber.setNormalIds(ids);
            findSumNumber.setFaultIds(faultIds);
            EquipmentSumCache equipmentSumCache = transformerNumberMapper.findCacheType(type,siteId);
            if (equipmentSumCache!=null){
                transformerNumberMapper.updateNumber(findSumNumber);
                flag = true;
                break;
            }
        }
        if (!flag){
            findSumNumber.setId(Uuid.getUUID());
            transformerNumberMapper.addNumber(findSumNumber);
        }
        return findSumNumber;
    }

    @Override
    public EquipmentSumSensorCache findSumGeneratorSensorNumber() {
        EquipmentSumSensorCache equipmentSumSensorCache = generatorNumberMapper.findSumSensorNumber();
        if(!ObjectUtils.isEmpty(equipmentSumSensorCache)) {
            // 计算在线率
            BigDecimal a = BigDecimal.valueOf(equipmentSumSensorCache.getNormalNumber());
            BigDecimal b = BigDecimal.valueOf(equipmentSumSensorCache.getNumber());
            equipmentSumSensorCache.setOnlineRate(new DecimalFormat().format(CalcUtil.calcRate(a, b)));
        } else {
            equipmentSumSensorCache.setNumber(0);
            equipmentSumSensorCache.setNormalNumber(0);
            equipmentSumSensorCache.setFaultNumber(0);
            equipmentSumSensorCache.setOnlineRate("0");
        }
        return equipmentSumSensorCache;
    }

    @Override
    public EquipmentSumSensorCache findSumOtherSensorNumber() {
        EquipmentSumSensorCache equipmentSumSensorCache = new EquipmentSumSensorCache();
        int otherDeviceNumber = generatorNumberMapper.findOtherSensorSumNumber();
        equipmentSumSensorCache.setNumber(otherDeviceNumber);
        return equipmentSumSensorCache;
    }
    @Override
    public List<GeneratorStatus> findGeneratorStatus() {
        List<GeneratorStatus> findStatus = generatorNumberMapper.findGeneratorStatus();
        for (GeneratorStatus generatorStatus: findStatus ) {
            String findGeneratorId= generatorStatus.getMainEquipmentId();
            TAndTransformerStatus findTransformerStatus = generatorNumberMapper.findTransformerStatus(findGeneratorId);
            if(findTransformerStatus!=null){
                generatorStatus.setStype(findTransformerStatus.getStype());
            }
            String mainEquipmentId = generatorStatus.getMainEquipmentId();
            List<EquipmentSensorCache> list = generatorNumberService.findGeneratorSensorNumber(mainEquipmentId);
            for (EquipmentSensorCache sensor: list) {
                if (sensor!=null){
                    if (sensor.getFaultNumber()!=BigDecimal.ZERO){
                        generatorStatus.setPrior("0");
                    }
                    if (sensor.getSensorName()!=null&&sensor.getFaultNumber().equals(BigDecimal.ZERO)){
                        generatorStatus.setPrior("1");
                    }
                }

            }
        }
        return findStatus;
    }

    @Override
    public int findOtherEquNumber() {
        return generatorNumberMapper.findOtherEquNumber();
    }

    @Override
    public List<EquipmentSensorCache> findGeneratorSensorNumber(String mainEquipmentId) {
        List<EquipmentSensorCache> online =  generatorNumberMapper.findGeneratorSenSor(mainEquipmentId);
        for (EquipmentSensorCache equipmentSensorCache : online) {
            int normal = equipmentSensorCache.getNormalNumber();
            BigDecimal sum = equipmentSensorCache.getNumber();
            //将int型转换为BigDecimal
            BigDecimal normalVo = new BigDecimal(0);
            int value = normal;
            normalVo = BigDecimal.valueOf((int) value);
            BigDecimal fault = sum.subtract(normalVo);
            if (!sum.equals(BigDecimal.ZERO)) {
                BigDecimal rate = CalcUtil.calcRate(normalVo, sum);
                //计算百分比
                DecimalFormat df = new DecimalFormat();
                String onlineRate = df.format(rate);
                equipmentSensorCache.setOnlineRate(onlineRate);
            }
            equipmentSensorCache.setFaultNumber(fault);
        }
        return online;
    }

    @Override
    public int findGeneratorNumber() throws ParseException {
        //查询变压器所有设备并获取到变压器设备Id
        List<EquipmentSensorNumber> findEquipment = generatorNumberMapper.findEquipment();
        //查询所有站点Id
        List<SiteData> findSite = transformerNumberMapper.findSiteData() ;
        //循环所有站点
        for (SiteData siteData:findSite) {
            String siteId = siteData.getId();
            for (EquipmentSensorNumber equipmentMainId: findEquipment) {
                String mainEquipmentId = equipmentMainId.getMainEquipmentId();
                //通过变压器id查询cache表中外挂装置
                List<EquipmentSensorNumber> findNumber = transformerNumberMapper.findTransformerNumber(mainEquipmentId);
                for (EquipmentSensorNumber equipmentTemperatureCache:findNumber) {
                    String sensorId = equipmentTemperatureCache.getSensorId();
                    String sensorCode = equipmentTemperatureCache.getExtEquipmentCode();
                    String subSensorID = sensorId.substring(15, 17);
                    //获取当前系统时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String newDate = sdf.format(new Date());
                    if (subSensorID.equals("07")) {
                        boolean flag = false;
                        int count = 0;
                        //获取设备最新一条时间
                        String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                        //获取设备间隔时间
                        String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.fdjzz + "");
                        if (cycle != null) {
                            int temp = Integer.parseInt(cycle);
                            int cycleVo = temp + 1;
                            BigDecimal timeValue = DecimalUtil.getVal(cycleVo);
                            int oldTime = timeValue.intValue();
                            Date dt = sdf.parse(newDate);
                            Calendar rightNow = Calendar.getInstance();
                            rightNow.setTime(dt);
                            //计算时间差
                            rightNow.add(Calendar.HOUR, -oldTime);
                            Date sub = rightNow.getTime();
                            String reStr = sdf.format(sub);
                            Integer finalValue = newDateValue.compareTo(reStr);
                            if (finalValue > 0) {
                                count += 1;
                            }
                            //查询记录计算出来值的表
                            List<EquipmentSensorCache> numberList= generatorNumberMapper.findSensorCache();
                            // false: 没找到
                            equipmentTemperatureCache.setId(Uuid.getUUID());
                            equipmentTemperatureCache.setNormalNumber(count);
                            // 将int型转换为BigDecimal
                            BigDecimal countVo = new BigDecimal(0);
                            int value = count;
                            countVo = BigDecimal.valueOf((int) value);
                            //获取sensorCode总数
                            BigDecimal number = generatorNumberMapper.findSesorCodeNumber(equipmentTemperatureCache.getExtEquipmentCode(), mainEquipmentId);
                            equipmentTemperatureCache.setNumber(number);
                            if (!number.equals(BigDecimal.ZERO)) {
                                BigDecimal rate = CalcUtil.calcRate(countVo, number);
                                //计算百分比
                                DecimalFormat df = new DecimalFormat();
                                String online = df.format(rate);
                                equipmentTemperatureCache.setOnlineRate(online);
                            }
                            BigDecimal faultNumber = number.subtract(countVo);
                            equipmentTemperatureCache.setFaultNumber(faultNumber);
                            for (EquipmentSensorCache equipmentSensorCache:numberList) {
                                String SensorCodeId = equipmentSensorCache.getSensorId();

                                if (sensorId.equals(SensorCodeId)){
                                    generatorNumberMapper.updatGeneratorSensor(equipmentTemperatureCache);
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag){
                                equipmentTemperatureCache.setId(Uuid.getUUID());
                                generatorNumberMapper.addGeneratorSensor(equipmentTemperatureCache);
                            }
                        }
                    }
                    if (subSensorID.equals("22")) {
                        boolean flag = false;
                        int count = 0;
                        //获取设备最新一条时间
                        String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                        //获取设备间隔时间
                        String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.fdjzz + "");
                        if (cycle != null) {
                            int temp = Integer.parseInt(cycle);
                            int cycleVo = temp + 1;
                            BigDecimal timeValue = DecimalUtil.getVal(cycleVo);
                            int oldTime = timeValue.intValue();
                            Date dt = sdf.parse(newDate);
                            Calendar rightNow = Calendar.getInstance();
                            rightNow.setTime(dt);
                            //计算时间差
                            rightNow.add(Calendar.HOUR, -oldTime);
                            Date sub = rightNow.getTime();
                            String reStr = sdf.format(sub);
                            Integer finalValue = newDateValue.compareTo(reStr);
                            if (finalValue > 0) {
                                count += 1;
                            }
                            //查询记录计算出来值的表
                            List<EquipmentSensorCache> numberList= generatorNumberMapper.findSensorCache();
                            // false: 没找到
                            equipmentTemperatureCache.setId(Uuid.getUUID());
                            equipmentTemperatureCache.setNormalNumber(count);
                            // 将int型转换为BigDecimal
                            BigDecimal countVo = new BigDecimal(0);
                            int value = count;
                            countVo = BigDecimal.valueOf((int) value);
                            //获取sensorCode总数
                            BigDecimal number = generatorNumberMapper.findSesorCodeNumber(sensorCode, mainEquipmentId);
                            equipmentTemperatureCache.setNumber(number);
                            if (!number.equals(BigDecimal.ZERO)) {
                                BigDecimal rate = CalcUtil.calcRate(countVo, number);
                                //计算百分比
                                DecimalFormat df = new DecimalFormat();
                                String online = df.format(rate);
                                equipmentTemperatureCache.setOnlineRate(online);
                            }
                            BigDecimal faultNumber = number.subtract(countVo);
                            equipmentTemperatureCache.setFaultNumber(faultNumber);
                            for (EquipmentSensorCache equipmentSensorCache:numberList) {
                                String SensorCodeId = equipmentSensorCache.getSensorId();

                                if (sensorId.equals(SensorCodeId)){
                                    generatorNumberMapper.updatGeneratorSensor(equipmentTemperatureCache);
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag){
                                equipmentTemperatureCache.setId(Uuid.getUUID());
                                generatorNumberMapper.addGeneratorSensor(equipmentTemperatureCache);
                            }
                        }
                    }

                    if (subSensorID.equals("0F")) {
                        boolean flag = false;
                        int count = 0;
                        //获取设备最新一条时间
                        String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                        //获取设备间隔时间
                        String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.fdjzz + "");
                        if (cycle != null) {
                            int temp = Integer.parseInt(cycle);
                            int cycleVo = temp + 1;
                            BigDecimal timeValue = DecimalUtil.getVal(cycleVo);
                            int oldTime = timeValue.intValue();
                            Date dt = sdf.parse(newDate);
                            Calendar rightNow = Calendar.getInstance();
                            rightNow.setTime(dt);
                            //计算时间差
                            rightNow.add(Calendar.HOUR, -oldTime);
                            Date sub = rightNow.getTime();
                            String reStr = sdf.format(sub);
                            Integer finalValue = newDateValue.compareTo(reStr);
                            if (finalValue > 0) {
                                count += 1;
                            }
                            //查询记录计算出来值的表
                            List<EquipmentSensorCache> numberList= generatorNumberMapper.findSensorCache();
                            // false: 没找到
                            equipmentTemperatureCache.setId(Uuid.getUUID());
                            equipmentTemperatureCache.setNormalNumber(count);
                            // 将int型转换为BigDecimal
                            BigDecimal countVo = new BigDecimal(0);
                            int value = count;
                            countVo = BigDecimal.valueOf((int) value);
                            //获取sensorCode总数
                            BigDecimal number = generatorNumberMapper.findSesorCodeNumber(sensorCode, mainEquipmentId);
                            equipmentTemperatureCache.setNumber(number);
                            if (!number.equals(BigDecimal.ZERO)) {
                                BigDecimal rate = CalcUtil.calcRate(countVo, number);
                                //计算百分比
                                DecimalFormat df = new DecimalFormat();
                                String online = df.format(rate);
                                equipmentTemperatureCache.setOnlineRate(online);
                            }
                            BigDecimal faultNumber = number.subtract(countVo);
                            equipmentTemperatureCache.setFaultNumber(faultNumber);
                            for (EquipmentSensorCache equipmentSensorCache:numberList) {
                                String SensorCodeId = equipmentSensorCache.getSensorId();

                                if (sensorId.equals(SensorCodeId)){
                                    generatorNumberMapper.updatGeneratorSensor(equipmentTemperatureCache);
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag){
                                equipmentTemperatureCache.setId(Uuid.getUUID());
                                generatorNumberMapper.addGeneratorSensor(equipmentTemperatureCache);
                            }
                        }
                    }
                    if (subSensorID.equals("1F")) {
                        boolean flag = false;
                        int count = 0;
                        //获取设备最新一条时间
                        String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                        //获取设备间隔时间
                        String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.fdjzz + "");
                        if (cycle != null) {
                            int temp = Integer.parseInt(cycle);
                            int cycleVo = temp + 1;
                            BigDecimal timeValue = DecimalUtil.getVal(cycleVo);
                            int oldTime = timeValue.intValue();
                            Date dt = sdf.parse(newDate);
                            Calendar rightNow = Calendar.getInstance();
                            rightNow.setTime(dt);
                            //计算时间差
                            rightNow.add(Calendar.HOUR, -oldTime);
                            Date sub = rightNow.getTime();
                            String reStr = sdf.format(sub);
                            Integer finalValue = newDateValue.compareTo(reStr);
                            if (finalValue > 0) {
                                count += 1;
                            }
                            //查询记录计算出来值的表
                            List<EquipmentSensorCache> numberList= generatorNumberMapper.findSensorCache();
                            // false: 没找到
                            equipmentTemperatureCache.setId(Uuid.getUUID());
                            equipmentTemperatureCache.setNormalNumber(count);
                            // 将int型转换为BigDecimal
                            BigDecimal countVo = new BigDecimal(0);
                            int value = count;
                            countVo = BigDecimal.valueOf((int) value);
                            //获取sensorCode总数
                            BigDecimal number = generatorNumberMapper.findSesorCodeNumber(sensorCode, mainEquipmentId);
                            equipmentTemperatureCache.setNumber(number);
                            if (!number.equals(BigDecimal.ZERO)) {
                                BigDecimal rate = CalcUtil.calcRate(countVo, number);
                                //计算百分比
                                DecimalFormat df = new DecimalFormat();
                                String online = df.format(rate);
                                equipmentTemperatureCache.setOnlineRate(online);
                            }
                            BigDecimal faultNumber = number.subtract(countVo);
                            equipmentTemperatureCache.setFaultNumber(faultNumber);
                            for (EquipmentSensorCache equipmentSensorCache:numberList) {
                                String SensorCodeId = equipmentSensorCache.getSensorId();

                                if (sensorId.equals(SensorCodeId)){
                                    generatorNumberMapper.updatGeneratorSensor(equipmentTemperatureCache);
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag){
                                equipmentTemperatureCache.setId(Uuid.getUUID());
                                generatorNumberMapper.addGeneratorSensor(equipmentTemperatureCache);
                            }
                        }
                    }

                }
            }

        }
        return 0;
    }
}
