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.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 海淀水务局
 */
@Component
public class HdForwarder {
    private static final String MSG_SERIAL_NUMBER = "0001";//流水号

    /**
     * 根据TAireadModel生成报文
     * @param aireadModel
     */
    public String generateMessage(TAireadModel aireadModel, DicForwarderModel forwarderModel) {
        try {
            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(), "yyMMddHHmm");
        sb.append(sampleTime);//观测时间

        if (forwarderModel.getExtendFlag().equals("1")) {
            sb.append("272B0000000000");//瞬时流量
        }

        /** 累计流量开始 */
        sb.append("FF04");
        sb.append(getResultValue(aireadModel.getResultValue()));
        /** 累计流量结束 */

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

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

        sb.append("FF0308");
        sb.append(NumberUtil.numToHex8(aireadModel.getRsrp()));//信号质量
        return sb.toString();
    }

    /**
     * 获取最终端结果的报文内容
     * @param value
     * @return
     */
    private String getResultValue(BigDecimal value) {
        value = value.scale() > 5 ? value.setScale(5, RoundingMode.HALF_UP) : value;
        String strValue = value.toString();

        int intNum = 0;//整数个数
        int partNum = 0;//小数个数
        String[] arr = strValue.split("\\.");
        intNum = arr[0].length();
        String resValue = arr[0];
        if (arr.length > 1) {
            String temp = StringUtil.removeTrailingZeros(arr[1]);
            partNum = temp.length();
            resValue = resValue + temp;
        }

        int len = intNum + partNum;
        if (len % 2 != 0) {//非偶数,补齐
            len++;
            resValue = "0" + resValue;
        }

        String lenIdentifier = PackUtils.getItemLenIdentifier(len, partNum);
        return lenIdentifier + resValue;
    }

    /**
     * 获取电压的报文内容
     * @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');
        }
    }
}
