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.utils.ByteUtils;
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.ShDeviceRecordEntity;
import tech.glinfo.enbao.modules.sh.entity.ShInstructionParsingEntity;
import tech.glinfo.enbao.modules.sh.service.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//智能开关
@Component("switchParse")
public class SwitchParse implements IParse {

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

    @Autowired
    private OtherShDeviceService otherShDeviceService;

    @Autowired
    private ShDeviceRecordService shDeviceRecordService;

    @Autowired
    private ShDeviceDataService shDeviceDataService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private TimeParseUtils timeParseUtils;

    @Autowired
    private MqProducer mqProducer;

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

        new Thread(() -> {
            //检测有没待下发指令
            String send = redisUtils.get("device:sendtemp1:" + device.getNumbering());
            if(send != null) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mqProducer.sendT(send);
                redisUtils.delete("device:sendtemp1:" + device.getNumbering());
            }
            //检测有没待下发指令
            String send1 = redisUtils.get("device:sendtemp2:" + device.getNumbering());
            if(send1 != null) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mqProducer.sendT(send1);
                redisUtils.delete("device:sendtemp2:" + device.getNumbering());
            }
        }).start();

        ws.put("deviceId", String.valueOf(device.getId()));
        if("08".equals(datas.get("cmd"))) {//登录包
            redisUtils.set(datas.get("mac").toUpperCase(), datas.toString(), 180);//3分钟有效
            //校验设备时钟
            new Thread(() -> {
                logger.info("start checkDeviceTime");
                timeParseUtils.checkDeviceTime1(datas.get("receiveId"), datas.get("content"), "02");
            }).start();

            return datas;
        }else if("06".equals(datas.get("cmd"))) {//实时数据上报
            String content = datas.get("content");
            //开关状态
            String eqh = content.substring(2, 4);
            String eq = String.valueOf(Integer.valueOf(eqh, 16));
            //查询解析指令集
            List<ShInstructionParsingEntity> cmds = otherShDeviceService.getDeviceInstructionList(device.getProductId(), datas.get("cmd"));
            if (cmds != null && cmds.size() > 0) {
                int length = 0;
                //解析设备报文内容
                String content1 = datas.get("content");
                Map<String, Object> map = new HashMap<>();
                for (ShInstructionParsingEntity cmd : cmds) {
                    String hex = content1.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();
                }
                otherShDeviceService.updateDeviceData(JSON.toJSONString(map), device.getId());
            } else {
                ws = datas;
            }
        }else if("18".equals(datas.get("cmd"))) {//开关响应
            String content = datas.get("content");
            logger.info("开关响应 : {}", content);
            //开关状态
            /*if (content.equals("00")) {
                //保存开关记录
                logger.info("receiveId : {}", datas.get("receiveId"));
                String action = redisUtils.get(datas.get("receiveId") + "action1");
                String action2 = redisUtils.get(datas.get("receiveId") + "action2");
                if (StringUtils.isNotBlank(action)) {
                    ShDeviceRecordEntity recordEntity = new ShDeviceRecordEntity();
                    recordEntity.setDeviceId(device.getId());
                    recordEntity.setAction(Integer.parseInt(action));
                    shDeviceRecordService.save(recordEntity);
                    redisUtils.delete(datas.get("receiveId") + "action1");
                }

                if (StringUtils.isNotBlank(action2)) {
                    ShDeviceRecordEntity recordEntity = new ShDeviceRecordEntity();
                    recordEntity.setDeviceId(device.getId());
                    recordEntity.setAction(Integer.parseInt(action2));
                    shDeviceRecordService.save(recordEntity);
                    redisUtils.delete(datas.get("receiveId") + "action2");
                }

            }*/
            ws.put("action", content);

        }else if("1A".equals(datas.get("cmd"))) {//温控响应
            String content = datas.get("content");
            logger.info("设置温控响应 : {}", content);
            String content1 = redisUtils.get(device.getNumbering() + "temp");
            //设备响应成功之后修改数据，不用等30秒，页面体验好些
            if ("00".equals(content)) {
                if (content1 != null) {
                    ShDeviceDataEntity entity = shDeviceDataService.getOne(new QueryWrapper<ShDeviceDataEntity>().eq("device_id", device.getId()));
                    if (entity != null) {
                        JSONObject jsonObj = new JSONObject(entity.getValue());
                        jsonObj.put("highTemp1", ByteUtils.signHex2IntString(content1.substring(0, 2)));
                        jsonObj.put("highTempStatus1", ByteUtils.signHex2IntString(content1.substring(2, 4)));
                        jsonObj.put("lowTemp1", ByteUtils.signHex2IntString(content1.substring(4, 6)));
                        jsonObj.put("lowTempStatus1", ByteUtils.signHex2IntString(content1.substring(6, 8)));
                        jsonObj.put("highTemp2", ByteUtils.signHex2IntString(content1.substring(8, 10)));
                        jsonObj.put("highTempStatus2", ByteUtils.signHex2IntString(content1.substring(10, 12)));
                        jsonObj.put("lowTemp2", ByteUtils.signHex2IntString(content1.substring(12, 14)));
                        jsonObj.put("lowTempStatus2", ByteUtils.signHex2IntString(content1.substring(14, 16)));
                        entity.setValue(jsonObj.toString());
                        shDeviceDataService.updateById(entity);
                    }
                }
            }
            redisUtils.delete(device.getNumbering() + "temp");

        }else if("20".equals(datas.get("cmd"))) {//事件上报
            //保存开关记录
            String content = datas.get("content");
            String type = content.substring(2, 4);
            String action = content.substring(6, 8);
            ShDeviceRecordEntity recordEntity = new ShDeviceRecordEntity();
            recordEntity.setDeviceId(device.getId());
            if (type.equals("01")) {
                //开关1  1:开 2:关
                recordEntity.setAction(action.equals("01") ? 1 : 2);
            }else {
                //开关2  3:开 4:关
                recordEntity.setAction(action.equals("01") ? 3 : 4);
            }

            shDeviceRecordService.save(recordEntity);

        }
        return ws;
    }

}
