package tech.glinfo.enbao.modules.mq;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.json.JSONObject;
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.contants.Constants;
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.entity.ShDeviceDataEntity;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceEntity;
import tech.glinfo.enbao.modules.sh.entity.ShInstructionParsingEntity;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceService;
import tech.glinfo.enbao.modules.sh.service.ShDeviceDataService;

import java.util.*;

//智能空气净化器
@Component("filterParse")
public class FilterParse implements IParse {

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

    @Autowired
    private OtherShDeviceService otherShDeviceService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private ShDeviceDataService shDeviceDataService;

    @Override
    public Map<String, String> run(Object o, Map<String, String> datas) {
        ShDeviceEntity device = (ShDeviceEntity) o;
        Map<String, String> ws = new HashMap<>();

        String cmd1 = datas.get("cmd");
        //数据上报
        if ("01".equals(cmd1)) {
            //校验设备时钟
            new Thread(new Runnable() {
                @Override
                public void run() {
                    logger.info("start checkDeviceTime");
                    checkDeviceTime(device.getNumbering(), datas.get("content"));
                }
            }).start();
            //查询解析指令集
            List<ShInstructionParsingEntity> cmds = otherShDeviceService.getDeviceInstructionList(device.getProductId(), datas.get("cmd"));
            if (cmds != null && cmds.size() > 0) {
                int length = 0;
                //解析设备报文内容
                String content = datas.get("content");
                Map<String, Object> map = new HashMap<>();
                for (ShInstructionParsingEntity cmd : cmds) {
                    String hex = content.substring(length, length + cmd.getLength());
                    String hex1;
                    if (cmd.getType() == 1 || cmd.getType() == 2) {
                        hex1 = String.valueOf(Integer.valueOf(hex, 16));

                    }else {
                        hex1 = ByteUtils.signHex2IntString(hex);
                    }
                    map.put(cmd.getName(), hex1);
                    ws.put(cmd.getName(), hex1);
                    length += cmd.getLength();
                }
                //@TODO 由于当前设备没有上报灯光状态用updateFilterDeviceData，上报之后请切换到updateDeviceData
                otherShDeviceService.updateFilterDeviceData(map, device.getId());
            } else {
                ws = datas;
            }
        } else if ("84".equals(cmd1)) {//设备使用期限
            redisUtils.set(Constants.FILTER_UES_TIME + device.getNumbering(), datas.get("content"), 300);
        } else if ("93".equals(cmd1) || "95".equals(cmd1)) {
            if ("95".equals(cmd1)) {//灯光控制有问题
                ShDeviceDataEntity entity = shDeviceDataService.getOne(new QueryWrapper<ShDeviceDataEntity>().eq("device_id", device.getId()));
                JSONObject jsonObj = new JSONObject(entity.getValue());
                String light = jsonObj.has("light")?jsonObj.getString("light"):"0";
                jsonObj.put("light", light.equals("0")?"1":"0");
                entity.setValue(jsonObj.toString());
                shDeviceDataService.updateById(entity);
            }
        } else {
            ws = datas;
        }
        return ws;
    }

    private void checkDeviceTime(String numbering, String content) {
        String hex = content.substring(18, 22);
        String year = String.valueOf(Integer.valueOf(hex, 16));
        String hex1 = content.substring(22, 24);
        String month = StringUtils.appendString(String.valueOf(Integer.valueOf(hex1, 16)),2, true, "0");
        String hex2 = content.substring(24, 26);
        String day = StringUtils.appendString(String.valueOf(Integer.valueOf(hex2, 16)),2, true, "0");
        String hex3 = content.substring(26, 28);
        String hour = StringUtils.appendString(String.valueOf(Integer.valueOf(hex3, 16)),2, true, "0");
        String hex4 = content.substring(28, 30);
        String minute = StringUtils.appendString(String.valueOf(Integer.valueOf(hex4, 16)),2, true, "0");
        String hex5 = content.substring(30, 32);
        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);
        Date date1 = null;
        try {
            date1 = DateUtils.stringToDate(date, DateUtils.DATE_TIME_PATTERN);
        } catch (Exception e) {
            //时间转换出错直接校准更新时间
            updateTime(numbering);
        }
        if(date1 != null) {
            long diff = new Date().getTime() - date1.getTime();//这样得到的差值是毫秒级别
            long min = diff / (1000 * 60);
            //校验相差20分钟
            if (min > 10 || min < -10) {
                updateTime(numbering);
            }
        }
    }

    private void updateTime(String numbering) {
        logger.info("upate-time : {}", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        ProtocolContent protocol = new ProtocolContent();
        protocol.setCmd("11");
        protocol.setDeviceType("01");
        protocol.setReceiveId(numbering);
//                DateUtils.format()
        protocol.setContent(getContent((new Date())));
        mqProducer.sendT(JSON.toJSONString(protocol));
    }

    private String getContent(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);					//放入Date类型数据
        StringBuffer sb = new StringBuffer();
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.YEAR)));//获取年份
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.MONTH)+1));					//获取月份
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.DATE)));					//获取日

//        sb.append(calendar.get(Calendar.HOUR));					//时（12小时制）
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.HOUR_OF_DAY)));				//时（24小时制）
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.MINUTE)));					//分
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.SECOND)));					//秒
        return sb.toString();
    }
}
