package tech.glinfo.enbao.modules.mq;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.glinfo.enbao.common.utils.ByteUtils;
import tech.glinfo.enbao.common.utils.DateUtils;
import tech.glinfo.enbao.common.utils.RedisUtils;
import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Component
public class TimeParseUtils {

    private final static Logger logger = LoggerFactory.getLogger(TimeParseUtils.class);


    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private RedisUtils redisUtils;



    void checkDeviceTime1(String numbering, String content, String deviceType) {
        String hex = content.substring(2, 6);
        String year = String.valueOf(Integer.valueOf(hex, 16));
        String hex1 = content.substring(6, 8);
        String month = StringUtils.appendString(String.valueOf(Integer.valueOf(hex1, 16)),2, true, "0");
        String hex2 = content.substring(8, 10);
        String day = StringUtils.appendString(String.valueOf(Integer.valueOf(hex2, 16)),2, true, "0");
        String hex3 = content.substring(10, 12);
        String hour = StringUtils.appendString(String.valueOf(Integer.valueOf(hex3, 16)),2, true, "0");
        String hex4 = content.substring(12, 14);
        String minute = StringUtils.appendString(String.valueOf(Integer.valueOf(hex4, 16)),2, true, "0");
        String hex5 = content.substring(14, 16);
        String second = StringUtils.appendString(String.valueOf(Integer.valueOf(hex5, 16)),2, true, "0");
        String date = year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
        logger.info("device-time : " + date);
        try {
            Date date1 = DateUtils.stringToDate(date, DateUtils.DATE_TIME_PATTERN);
            long diff = new Date().getTime() - date1.getTime();//这样得到的差值是毫秒级别
            long min = diff / (1000 * 60);
            //校验相差20分钟
            if(min > 2 || min < -2) {
                logger.info("update-time : {}", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                sendCmd(numbering, deviceType);
                if("06".equals(deviceType)) {
                    redisUtils.set(numbering, "update-time", 60);//2分钟有效
                    int tryTimes = 2;//尝试两次
                    while (tryTimes > 0) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if(redisUtils.hasKey(numbering)) {
                            logger.info("try update-time again: {}", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                            sendCmd(numbering, deviceType);
                            tryTimes--;
                        } else {
                            break;
                        }
                    }
                }
            }
        }catch (Exception e) {
            sendCmd(numbering, deviceType);
            if("06".equals(deviceType)) {
                redisUtils.set(numbering, "update-time", 60);//2分钟有效
                int tryTimes = 2;//尝试两次
                while (tryTimes > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    if(redisUtils.hasKey(numbering)) {
                        logger.info("try update-time again: {}", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                        sendCmd(numbering, deviceType);
                        tryTimes--;
                    } else {
                        break;
                    }
                }
            }
        }

    }

    private void sendCmd(String numbering, String deviceType) {
        ProtocolContent protocol = new ProtocolContent();
        protocol.setCmd("11");
        protocol.setDeviceType(deviceType);
        protocol.setReceiveId(numbering);
        protocol.setContent(getContent((new Date())));
        mqProducer.sendT(JSON.toJSONString(protocol));
    }

    private String getContent(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);					//放入Date类型数据
        return ByteUtils.int2Hex(calendar.get(Calendar.YEAR)) +//获取年份
                ByteUtils.int2Hex(calendar.get(Calendar.MONTH) + 1) +                    //获取月份
                ByteUtils.int2Hex(calendar.get(Calendar.DATE)) +                    //获取日
                ByteUtils.int2Hex(calendar.get(Calendar.HOUR_OF_DAY)) +                //时（24小时制）
                ByteUtils.int2Hex(calendar.get(Calendar.MINUTE)) +                    //分
                ByteUtils.int2Hex(calendar.get(Calendar.SECOND));//秒
    }
}
