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.SiteUploadCycleMapper;
import com.huatek.busi.mapper.TransformerNumberMapper;
import com.huatek.busi.service.CubicleNumberService;
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 = CubicleNumberService.class)
@Transactional(rollbackFor = Exception.class)
public class CubicleNumberServiceImpl implements CubicleNumberService {
    @Autowired
    private TransformerNumberMapper transformerNumberMapper;

    @Autowired
    CubicleNumberMapper cubicleNumberMapper;

    @Autowired
    private SiteUploadCycleMapper siteUploadCycleMapper;

    @Autowired
    private CubicleNumberService cubicleNumberService;

    @Override
    public List<CubicleStatus> findCubicleStart() {
        List<CubicleStatus> findCubicleStart  = cubicleNumberMapper.findCubicleStart();
        for (CubicleStatus cubicleStatus:findCubicleStart) {
            String mainEquipmentId = cubicleStatus.getMainEquipmentId();
            List<EquipmentSensorCache> list = cubicleNumberService.findCubicleSensorNumber(mainEquipmentId);
            for (EquipmentSensorCache sensor: list) {
                if (sensor!=null){
                    if (sensor.getFaultNumber()!=BigDecimal.ZERO){
                        cubicleStatus.setPrior("0");
                    }
                    if (sensor.getSensorName()!=null&&sensor.getFaultNumber().equals(BigDecimal.ZERO)){
                        cubicleStatus.setPrior("1");
                    }
                }

            }
        }


        return findCubicleStart;
    }

    @Override
    public int findCubicleNumber() throws ParseException {
        //查询开关柜所有设备
        List<EquipmentSensorNumber> findEquipment = cubicleNumberMapper.findEquipment();
        for (EquipmentSensorNumber equipmentMainId: findEquipment) {
            String mainEquipmentId = equipmentMainId.getMainEquipmentId();
            //通过Id查询出缓存表中设备
            List<EquipmentSensorNumber> findNumber = transformerNumberMapper.findTransformerNumber(mainEquipmentId);
            //查询所有站点Id
            List<SiteData> findSite = transformerNumberMapper.findSiteData() ;
            //循环所有站点
            for (SiteData siteData:findSite) {
                String siteId = siteData.getId();

                for (EquipmentSensorNumber equipmentTemperatureCache:findNumber) {
                    int count = 0;
                    boolean flag = false;
                    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("05")) {
                        //获取设备最新一条时间
                        String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                        //获取设备间隔时间
                        String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.kgghw + "");
                        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.MINUTE, -oldTime);
                            Date sub = rightNow.getTime();
                            String reStr = sdf.format(sub);
                            Integer finalValue = newDateValue.compareTo(reStr);
                            if (finalValue > 0) {
                                count += 1;
                            }

                        }

                    }
                    if (subSensorID.equals("12")) {
                        //获取设备最新一条时间
                        String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                        //获取设备间隔时间
                        String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.cwzz + "");
                        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;
                            }

                        }
                    }
                    if (subSensorID.equals("16")) {
                        //获取设备最新一条时间
                        String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                        //获取设备间隔时间
                        String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.dlgxcw + "");
                        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;
                            }

                        }
                    }
                    //查询记录计算出来值的表
                    List<EquipmentSensorCache> numberList= cubicleNumberMapper.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 = cubicleNumberMapper.findAllSesorCodeNumber(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)){
                            cubicleNumberMapper.updateCubliceSensor(equipmentTemperatureCache);
                            flag = true;
                        }
                    }
                    if (!flag){
                        equipmentTemperatureCache.setId(Uuid.getUUID());
                        cubicleNumberMapper.addCubliceSensor(equipmentTemperatureCache);
                    }

                }
            }

        }
        return 0;
    }

    @Override
    public EquipmentSumNumber findSumCubicleNumber() throws Exception {

        //查询所有站点Id
        List<SiteData> findSite = transformerNumberMapper.findSiteData() ;

        EquipmentSumNumber findSumNumber = new EquipmentSumNumber();
        //查詢所有裝置
        List<EquipmentSensor> equipmentList = cubicleNumberMapper.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("05")) {
                    //获取设备最新一条时间
                    String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                    //获取设备间隔时间
                    String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.kgghw + "");
                    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("12")) {
                    //获取设备最新一条时间
                    String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                    //获取设备间隔时间
                    String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.cwzz + "");
                    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("16")) {
                    //获取设备最新一条时间
                    String newDateValue = equipmentTemperatureCache.getTimeStamp() + "";
                    //获取设备间隔时间
                    String cycle = siteUploadCycleMapper.getCycle(siteId, UploadCycle.ConfigField.dlgxcw + "");
                    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 = cubicleNumberMapper.finSumNumber(siteId);
            //查询开关柜外挂总异常数
            int countFault = countSum - count;
            findSumNumber.setSumNumber(countSum);
            findSumNumber.setSumNormal(count);
            findSumNumber.setSumFault(countFault);
            findSumNumber.setSiteId(siteId);
            findSumNumber.setType("05");
            String type = "05";
            findSumNumber.setNormalIds(ids);
            findSumNumber.setFaultIds(faultIds);
            EquipmentSumCache equipmentSumCache = transformerNumberMapper.findCacheType(type,siteId);
            if (equipmentSumCache!=null){
                if (type.equals("05")){
                    transformerNumberMapper.updateNumber(findSumNumber);
                    flag = true;
                    break;
                }
            }
        }
        if (!flag){
            findSumNumber.setId(Uuid.getUUID());
            transformerNumberMapper.addNumber(findSumNumber);
        }
        return findSumNumber;
    }

    @Override
    public List<RptTermperRecord> findCubiclePoint(String siteId, String eqmId) {
        List<RptTermperRecord> findCubiclePoint = cubicleNumberMapper.findCubiclePoint(siteId,eqmId);
        return findCubiclePoint;
    }

    public static final  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    public List<RptTemperRate> findTemperRate(String siteId, String eqmId) {
        Date dNow = new Date();
        Date dB = DateUtil.getDateByType(dNow, -1, "day");
        String dBefore = sdf.format(dB);
        List<RptTemperRate> findTemperRate = cubicleNumberMapper.findTemperRate(siteId,eqmId,dBefore);
        return findTemperRate;
    }


    @Override
    public List<RptTemper> findTemper(String siteId, String eqmId) {
        List<RptTemper> findTemper= cubicleNumberMapper.findTemper(siteId,eqmId);
        return findTemper;
    }

    @Override
    public List<EquipmentSensorCache> findCubicleSensorNumber(String mainEquipmentId) {
        List<EquipmentSensorCache>  online = cubicleNumberMapper.findCubicleSensor(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 EquipmentSumSensorCache findSumCubicleSensorNumber() {
        EquipmentSumSensorCache equipmentSumSensorCache = cubicleNumberMapper.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.setNormalNumber(0);
            equipmentSumSensorCache.setNormalNumber(0);
            equipmentSumSensorCache.setFaultNumber(0);
            equipmentSumSensorCache.setOnlineRate("-");
        }
        return equipmentSumSensorCache;
    }
}




