package org.example.background.service;

import com.ghgande.j2mod.modbus.util.ModbusUtil;
import org.example.background.dao.ElectricityDataDao;
import org.example.background.entity.ElectricityData;
import org.example.socket.utils.CommonConfig;
import org.example.socket.utils.IdService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MakeInfoService {

    @Resource
    private IdService idService;

    @Resource
    private ElectricityDataDao electricityDataDao;

    @Resource
    private CommonConfig config;


    //F25信息类 电能表
    public int[] sendElectricMessage(String ip, int fn) {
        return config.sendElectricInstruct(ip, fn);
    }

    public String convertPlaintext(byte[] data) {
        return ModbusUtil.toHex(data);
    }

    public Integer convertTextToData(String param, String clientIP) {
        String[] data = param.split(" ");
        return electric0(data, clientIP);
    }

    public Integer electric0(String[] data, String clientIp) {
        Integer typeF = 0;
        if(data.length > 12) {
            switch (data[12]) {
                case "0C":
                    switch (data[16] + data[17]) {
                        case "0103": //f25
                            electric0InStorage0C_25(data, clientIp);
                            typeF = 25;
                            break;
                        case "0110": //f129
                            electric0InStorage0C_129(data, clientIp);
                            typeF = 129;
                            break;
                        case "0410": //f131:
                            electric0InStorage0C_131(data, clientIp);
                            typeF = 131;
                            break;
                    }
                    break;
                case "09":
                    switch (data[16] + data[17]) {
                        case "0100": //f1 查询终端配置信息
                            electric0InStorage09_01(data, clientIp);
                            typeF = 1;
                            break;
                    }
                    break;
            }
        }
        return typeF;
    }

    public Integer electric0InStorage09_01(String[] data, String clientIp) {
        ElectricityData entity = new ElectricityData();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        String s = hexToAscii(data[18] + data[19] + data[20] + data[21]);
        String s1 = hexToAscii(data[22] + data[23] + data[24] + data[25] + data[26] + data[27] + data[28] + data[29]);
        entity.setElectricityId(idService.gen());
        try {
            entity.setAcquisitionTime(formatter.parse(formatter.format(new Date())));
        }catch (ParseException e) {
            e.printStackTrace();
        }
        entity.setCreateTime(new Date());
        return 1;
    }

    public Integer electric0InStorage0C_25(String[] data, String clientIp) {
        ElectricityData entity = new ElectricityData();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        entity.setElectricityId(idService.gen());
        entity.setZdId(String.valueOf(Integer.parseInt(data[9]+data[10],16)));

        try {
            entity.setAcquisitionTime(formatter.parse(formatter.format(new Date())));
        }catch (ParseException e) {
            e.printStackTrace();
        }
        entity.setCreateTime(new Date());
        entity.setTotalActivePower(Float.parseFloat(data[25]+data[24] + data[23]) / 10000); //总有功功率
        entity.setTotalReactivePower(Float.parseFloat(data[37] + data[36] + fixZhi(data[35])) / 10000); //总无功功率
        entity.setPowerFactor(Float.parseFloat(data[48] + data[47]) / 10); //功率因数
        entity.setAPhaseVoltage(Float.parseFloat(data[56] + data[55]) / 10); //A相电压
        entity.setBPhaseVoltage(Float.parseFloat(data[58] + data[57]) / 10); //b相电压
        entity.setCPhaseVoltage(Float.parseFloat(data[60] + data[59]) / 10); //c相电压
        entity.setAPhaseCurrent(Float.parseFloat(data[63] + data[62] + data[61]) / 1000); //A相电流
        entity.setBPhaseCurrent(Float.parseFloat(data[66] + data[65] + data[64]) / 1000); //B相电流
        entity.setCPhaseCurrent(Float.parseFloat(data[69] + data[68] + data[67]) / 1000); //C相电流
        entity.setAbPhaseVoltage((float)(entity.getAPhaseVoltage() * Math.sqrt(3))); //AB相电压
        entity.setBcPhaseVoltage((float)(entity.getBPhaseVoltage() * Math.sqrt(3))); //BC相电压
        entity.setAcPhaseVoltage((float)(entity.getCPhaseVoltage() * Math.sqrt(3))); //AC相电压
        entity.setApparentPower(Float.parseFloat(data[75] + data[74] + data[73]) / 10000); //视在功率
        entity.setFrequency(50f); //频率
        entity.setTaMultiplier(20.0f);
        entity.setTvMultiplier(1.0f);
        Integer insert = electricityDataDao.insert(entity);
        System.out.println("已入库");
        return insert;
    }

    public Integer electric0InStorage0C_129(String [] data, String clientIp) {
        ElectricityData entity = new ElectricityData();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        entity.setZdId(String.valueOf(Integer.parseInt(data[9]+data[10],16)));
        try {
            entity.setAcquisitionTime(formatter.parse(formatter.format(new Date())));
        }catch (ParseException e) {
            e.printStackTrace();
        }
        ElectricityData electricityData = electricityDataDao.select(entity);
        Integer integer = 0;
        if(StringUtils.isEmpty(electricityData)){
            System.out.println("上一步数据没有载入，无法执行当前入库操作");
        }else {
            DateFormat sdf1 = new SimpleDateFormat("yyMMddHHmm");
            try {
                electricityData.setReadTime(sdf1.parse(data[22] + data[21] + data[20] + data[19] + data[18]));
            }catch (ParseException e){
                e.printStackTrace();
            }
            electricityData.setPositiveActiveCharge(Float.parseFloat(data[28] + data[27] + data[26] + data[25] + data[24]) / 10000); //正向有功总电能示值
            electricityData.setPositiveActiveTipCharge(Float.parseFloat(data[33] + data[32] + data[31] + data[30] + data[29]) / 10000);//尖
            electricityData.setForwardActivePeakCharge(Float.parseFloat(data[38] + data[37] + data[36] + data[35] + data[34]) / 10000);//峰
            electricityData.setPositiveActivePowerLevel(Float.parseFloat(data[43] + data[42] + data[41] + data[40] + data[39]) / 10000); //平
            electricityData.setPositiveActiveValleyCharge(Float.parseFloat(data[48] + data[47] + data[46] + data[45] + data[44]) / 10000);//谷
            integer = electricityDataDao.updateByPrimaryKey(electricityData);
            System.out.println("已经填补剩余数据");
        }
        return integer;
    }

    public Integer electric0InStorage0C_131(String [] data, String clientIp) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        ElectricityData entity = new ElectricityData();
        entity.setZdId(String.valueOf(Integer.parseInt(data[9]+data[10],16)));
        try {
            entity.setAcquisitionTime(formatter.parse(formatter.format(new Date())));
        }catch (ParseException e) {
            e.printStackTrace();
        }
        ElectricityData electricityData = electricityDataDao.select(entity);
        Integer integer = 0;
        if(StringUtils.isEmpty(electricityData)){
            System.out.println("上一步数据没有载入，无法执行当前入库操作");
        }else {
            electricityData.setReverseActiveCharge(Float.parseFloat(data[28] + data[27] + data[26] + data[25] + data[24]) / 10000);//反向有功总电能示值
            electricityData.setReverseActiveTipCharge(Float.parseFloat(data[33] + data[32] + data[31] + data[30] + data[29]) / 10000); //尖
            electricityData.setReverseActivePeakCharge(Float.parseFloat(data[38] + data[37] + data[36] + data[35] + data[34]) / 10000);//峰
            electricityData.setReverseActivePowerLevel(Float.parseFloat(data[43] + data[42] + data[41] + data[40] + data[39]) / 10000);  //平
            electricityData.setReverseActiveValleyCharge(Float.parseFloat(data[48] + data[47] + data[46] + data[45] + data[44]) / 10000);//谷
            integer = electricityDataDao.updateByPrimaryKey(electricityData);
            System.out.println("已经填补剩余数据");
        }
        return integer;
    }

    public int[] detectingHeartbeat(String param, String clientIp) {
        String[] data = param.split(" ");
        int[] ints = new int[0];
        if(data.length > 12) {
            switch (data[12]) {
                case "02":
                    switch (data[16] + data[17]) {
                        case "0100":
                            ints = config.sendElectricInstruct2(clientIp, 1);
                            break;
                    }
                    break;
            }
        }
        return ints;
    }

    //16进制转ASCII编码
    public static String hexToAscii(String hexString) {
        StringBuilder asciiString = new StringBuilder();
        for (int i = 0; i < hexString.length(); i += 2) {
            String hexPair = hexString.substring(i, i + 2);
            int charCode = Integer.parseInt(hexPair, 16);
            asciiString.append((char) charCode);
        }
        return asciiString.toString();
    }

    public static String fixZhi(String data) {
        int i = Integer.parseInt(data);
        if(i%80 == 0){
            return "00";
        }else {
            return data;
        }
    }
}