package org.ts.ddcs.DataSaveProcesser;

import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.DataTemplate.DataTemplateInterface;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.Tool.BytesHelp;
import org.ts.ddcs.Worker.DataProcess;
import org.ts.ddcs.Worker.DataProcessHolder;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressWarnings("all")
public class DataSaveProcesserSzy81 extends DataSaveProcesser {
    @Override
    public void Save(DataTemplateInterface dataTemplateInterface) {
        super.Save(dataTemplateInterface);
        try {
            String rtuCode = BytesHelp.byte2HexStr(dataTemplateInterface.RtuCode());
            LogHelper.info("SAVE:" + dataTemplateInterface.GetFeture() + " " + rtuCode);
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String dt = timeFormat.format(new Date());

            byte[] collectTime = dataTemplateInterface.CollectTime();
            String collectTimeStr = dt.substring(0,2)+ BytesHelp.byte2HexStr(collectTime);
            byte[] receiveTime = dataTemplateInterface.ReceiveTime();
            String receiveTimeStr =  dt.substring(0,2)+BytesHelp.byte2HexStr(receiveTime);
            Date ct = timeFormat.parse(collectTimeStr);
            Date rt = timeFormat.parse(receiveTimeStr);

            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            /**
             * 采集时间错误处理
             */
            JSONObject errorInfo = new JSONObject();
            if (ct.getTime() > rt.getTime()) {
                errorInfo.put("code", "1");
                //String key ="trouble";
//                RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
//                HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();

                //String  trouble =opsHash.get(rtuCode,"key");
//               String  collectTimeError = opsHash.get(rtuCode,"collectTimeError");
//                JSONObject errorInfo =  JSONObject.parseObject(collectTimeError);
//                if (errorInfo.getString("code").equals("")){
//

            } else {
                errorInfo.put("code", "0");
            }
            errorInfo.put("collectTime", collectTimeStr);
            errorInfo.put("receiveTime", receiveTimeStr);

            opsHash.put(rtuCode,"collectTimeError",errorInfo.toJSONString());

           // DataProcess.DownloadNotify(rtuCode);
        } catch (Exception e) {
            LogHelper.error(e);
        }
    }
}
