package com.mvc.forwarmana;

import com.mvc.model.TAireadModel;
import com.mvc.model.forwarding.DicForwarderModel;
import com.mvc.netty.dealconstant.PackageOperateCode;
import com.mvc.utils.CRC16Util;
import com.mvc.utils.DateUtil;
import com.mvc.utils.NumberUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;

/**
 * 昌平水务局
 */
@Component
public class CPForwarder {
    private static final String MSG_SERIAL_NUMBER = "0001";//流水号

    /**
     * 根据TAireadModel生成报文
     *
     * @param aireadModel
     */
    public String generateMessage(TAireadModel aireadModel, DicForwarderModel forwarderModel) {
        try {
            //***特别注意,遥测站编码后4位要求16进制 2024-01-03 guozhao
            aireadModel.setStationCode(PackUtils.convertStationCode(aireadModel.getStationCode()));

            StringBuilder sb = new StringBuilder();
            sb.append(PackageOperateCode.SOH.getKey().toUpperCase());//帧头
            sb.append(forwarderModel.getCenterAddress());//中心站地址
            sb.append(aireadModel.getStationCode());//遥测站地址
            sb.append(forwarderModel.getMessagePwd());//设备密码
            sb.append(aireadModel.getFunCode());//功能码

            String body = getMessageBody(aireadModel, forwarderModel);//报文内容部分

            int length = body.length() / 2;
            int flagAndLen = 0 << 12 | length;
            sb.append(NumberUtil.numToHex16(flagAndLen));//报文长度
            sb.append(PackageOperateCode.STX.getKey().toUpperCase());//起始符
            sb.append(body);//报文内容部分
            sb.append(PackageOperateCode.ETX.getKey().toUpperCase());

            int crc = CRC16Util.calcCrc16(NumberUtil.hexStringToBytes(sb.toString()));
            sb.append(StringUtil.leftPad(Integer.toHexString(crc), 4, '0'));
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取报文内容部分
     *
     * @param aireadModel
     * @return
     */
    private String getMessageBody(TAireadModel aireadModel, DicForwarderModel forwarderModel) {
        StringBuilder sb = new StringBuilder();
        sb.append(MSG_SERIAL_NUMBER);//流水号

        String rptTime = DateUtil.formateDate(aireadModel.getRptTime(), "yyMMddHHmmss");
        sb.append(rptTime);//发报时间

        sb.append(PackageOperateCode.O_F1F1.getKey().toUpperCase());//遥测站引导符
        sb.append(aireadModel.getStationCode());//遥测站编码

        sb.append(forwarderModel.getStationType());//遥测站分类

        sb.append(PackageOperateCode.O_F0F0.getKey().toUpperCase());//观测时间引导符
        String sampleTime = DateUtil.formateDate(aireadModel.getSampleTime(), "yyMMddHH00");
        sb.append(sampleTime);//观测时间

        if (forwarderModel.getExtendFlag().equals("1")) {
            sb.append("282A0000000000");//取水口流量1
        }

        /** 累计流量1开始 */
        sb.append("FF012A");//固定5字节BCD码
        sb.append(getResultValue(aireadModel.getResultValue()));
        /** 累计流量1结束 */

        if (forwarderModel.getExtendFlag().equals("1")) {
            sb.append("452000000000");//终端报警状态
        }

        sb.append("3812");//电压协议头
        sb.append(getVoltageString(aireadModel.getVoltage()));//电池电压

        sb.append("FF0208");
        String rsrp = aireadModel.getRsrp() == null ? "00" : StringUtils.leftPad(aireadModel.getRsrp().toString(), 2, '0');
        sb.append(rsrp);//信号质量(BCD)
        //sb.append(NumberUtil.numToHex8(aireadModel.getRsrp()));//信号质量
        return sb.toString();
    }

    /**
     * 获取最终端结果的报文内容
     *
     * @param value
     * @return
     */
    private String getResultValue(BigDecimal value) {
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        decimalFormat.setMinimumFractionDigits(2); // 设置最小小数位数为2
        String formattedString = decimalFormat.format(value);
        formattedString = formattedString.replace(".", "");
        formattedString = StringUtils.leftPad(formattedString, 10, "0");
        return formattedString;
    }

    /**
     * 获取电压的报文内容
     *
     * @param value
     * @return
     */
    private String getVoltageString(BigDecimal value) {
        // 将BigDecimal转换为double
        double doubleValue = value.doubleValue();
        String strValue = String.valueOf(doubleValue);
        if (strValue.contains(".")) {//小数
            String[] arr = strValue.split("\\.");
            return StringUtils.leftPad(arr[0], 2, '0') + StringUtils.rightPad(arr[1], 2, '0');
        } else {//整数
            return StringUtils.leftPad(strValue, 4, '0');
        }
    }

    public static void main(String[] args) {
        CPForwarder forwarder = new CPForwarder();

        Date date = DateUtil.parseTimeStr("2024-01-03 00:00:00","yyyy-MM-dd HH:mm:ss");

        TAireadModel aireadModel = new TAireadModel();
        aireadModel.setStationCode("1101141003");
        aireadModel.setFunCode("32");
        aireadModel.setResultValue(BigDecimal.valueOf(123456.46));
        aireadModel.setSampleTime(date);
        aireadModel.setRptTime(new Date());
        aireadModel.setVoltage(new BigDecimal(3.55));
        aireadModel.setRsrp(60);

        DicForwarderModel dicForwarderModel = new DicForwarderModel();
        dicForwarderModel.setServerIp("61.50.129.85");
        dicForwarderModel.setServerPort(8202);
        dicForwarderModel.setTransportProtocol(1);
        dicForwarderModel.setMessageProtocol(1);
        dicForwarderModel.setExtendFlag("1");
        dicForwarderModel.setUseFlag("1");
        dicForwarderModel.setCenterAddress("01");
        dicForwarderModel.setMessagePwd("2020");
        dicForwarderModel.setStationType("49");

        System.out.println(forwarder.generateMessage(aireadModel,dicForwarderModel));
    }
}
