package com.mvc.netty;

import com.mvc.entity.TAiread;
import com.mvc.entity.TPackLog;
import com.mvc.netty.dealconstant.MsgIdentifier;
import com.mvc.netty.dealconstant.ResourcePath;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.utils.BeanUtil;
import com.mvc.utils.DateUtil;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

/**
 * 定时报
 */
@Component
public class RegularMessageParser implements MessageParser<TAiread> {

    private  static Logger log = LoggerFactory.getLogger(RegularMessageParser.class);

    @Resource
    private Environment env;

    /**
     *  解析数据报文
     * @param tPackLog
     * @param picsize
     * @return
     */
    @Override
    public TAiread parse(TPackLog tPackLog,String picsize) {
        String temp = tPackLog.getMessage();
        String value = null;
        String highStr = null;
        String widthStr = null;
        String sizeStr = null;

        TAiread rawdata = new TAiread();

        //初始化TRawdata
        rawdata.setAireadId(tPackLog.getPackId());
        rawdata.setSampleTime(tPackLog.getDatatime());
        rawdata.setRptTime(tPackLog.getRptTime());
        rawdata.setRevTime(tPackLog.getRevTime());
        rawdata.setStationCode(tPackLog.getStationCode());
        rawdata.setFunCode(tPackLog.getFunCode());

        //协议借用密码第一个字节表达设备类型(20=水表,21=压力表)(现在是非压力表即水表,后续加入其它类型要注意维护) 2022-09-13 guozhao
        String devType=StringUtils.isNotEmpty(tPackLog.getRptPwd())&&tPackLog.getRptPwd().substring(0,2).equals("21")?"2":"1";
        rawdata.setDeviceType(devType);

        String baseImagePath = env.getProperty(ResourceTag.ResourceUrlTag.getTag()) + ResourcePath.Image.getPath() + ResourcePath.Rawdata.getPath();
        String writepath = env.getProperty(ResourceTag.UploadPathTag.getTag()) + ResourcePath.Rawdata.getPath();
        try {
            baseImagePath += DateUtil.formateDate(rawdata.getSampleTime(), "yyyy-MM") + "/"+rawdata.getStationCode()+ "/";
            writepath += DateUtil.formateDate(rawdata.getSampleTime(), "yyyy-MM") + "/"+rawdata.getStationCode()+ "/";
        } catch (Exception e) {
            tPackLog.setFlag("2");
            String msg = String.format("----%s 处理失败 数据时间为空-------", tPackLog.getPackId());
            log.info(msg);
            return null;
        }
        rawdata.setSmallJpgUrl(baseImagePath);
        rawdata.setBigJpgUrl(writepath);
        rawdata.setSmallJpgPackGid(tPackLog.getPackGid());

        // 解析报文
        List<String> keys = MsgIdentifier.keys();
        while (!StringUtil.isNullOrEmpty(temp)) {
            boolean blnFind = false;
            for (String key: keys) {
                if (temp.toUpperCase().startsWith(key)) {
                    MsgIdentifier identifier = MsgIdentifier.getElement(key);
                    if (identifier != null) {
                        try {
                            if (identifier == MsgIdentifier.FF06) {     // 图片内容
                                temp = identifier.parsePic(highStr, widthStr, sizeStr, temp, rawdata,picsize);
                            } else if (identifier == MsgIdentifier.FF03) {      //图片高
                                temp = identifier.parse(temp);
                                highStr = identifier.getValue();
                                BeanUtil.fillTRawdata(rawdata, highStr, identifier);
                            } else if (identifier == MsgIdentifier.FF04) {      //图片宽
                                temp = identifier.parse(temp);
                                widthStr = identifier.getValue();
                                BeanUtil.fillTRawdata(rawdata, widthStr, identifier);
                            } else if (identifier == MsgIdentifier.FF05) {      //图片大小
                                temp = identifier.parse(temp);
                                sizeStr = identifier.getValue();
                            } else if(identifier == MsgIdentifier.FF22){//调试信息
                                temp=identifier.parseDebugInfo(temp);
                                value = identifier.getValue();
                                BeanUtil.fillTRawdata(rawdata, value, identifier);
                            } else if(identifier==MsgIdentifier.FF35){//AI图片占用字节描述2 2022-11-08 guozhao
                                /* 0x10(或0x20) - 1字节数据字节 =10时只有压缩前的2字节
                                1. 压缩前:2字节HEX码表示压缩前图片数据总长度
                                2. 压缩后:2字节HEX码表示压缩后图片数据总长度*/
                                temp=identifier.parseImageDescribe(temp);
                                sizeStr=identifier.getValue();
                            } else {
                                temp = identifier.parse(temp);
                                value = identifier.getValue();
                                BeanUtil.fillTRawdata(rawdata, value, identifier);
                            }
                            blnFind = true;
                            tPackLog.setFlag("1");
                        } catch (Exception e) {
                            String msg = String.format("----%s 处理失败 指令：%s-------", tPackLog.getPackId(), key);
                            log.error(msg);
                            tPackLog.setFlag("2");
                            e.printStackTrace();
                            blnFind = false;
                        }

                        break;
                    }
                }
            }
            if (blnFind == false) {
                String msg = String.format("----报文解析错误 %s-------", rawdata.getAireadId());
                log.error(msg);
                temp = "";
                break;
            }
        }

        return rawdata;
    }
}
