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.entity.ShDeviceEntity;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceRecordEntity;
import tech.glinfo.enbao.modules.sh.entity.ShDlinkEntity;
import tech.glinfo.enbao.modules.sh.entity.ShInstructionParsingEntity;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceService;
import tech.glinfo.enbao.modules.sh.service.OtherShDlinkService;
import tech.glinfo.enbao.modules.sh.service.ShDeviceRecordService;

import java.util.*;

//智能开关
@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 RedisUtils redisUtils;

    @Autowired
    private TimeParseUtils timeParseUtils;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private OtherShDlinkService otherShDlinkService;

    @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:sendtemp:" + device.getNumbering());
            if(send != null) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mqProducer.sendT(send);
                redisUtils.delete("device:sendtemp:" + 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);
            ws.put("action", content);

        }else if("20".equals(datas.get("cmd"))) {//事件上报
            //保存开关记录
            String content = datas.get("content");
            String type = content.substring(2, 4);
            String action1 = content.substring(6, 8);
            String action2 = content.substring(8, 10);

            switch (type) {
                case "01": {
                    ShDeviceRecordEntity recordEntity = new ShDeviceRecordEntity();
                    recordEntity.setDeviceId(device.getId());
                    //开关1  1:开 2:关
                    recordEntity.setAction(action1.equals("01") ? 1 : 2);
                    shDeviceRecordService.save(recordEntity);
                    break;
                }
                case "02": {
                    ShDeviceRecordEntity recordEntity = new ShDeviceRecordEntity();
                    recordEntity.setDeviceId(device.getId());
                    //开关2  3:开 4:关
                    recordEntity.setAction(action2.equals("01") ? 3 : 4);
                    shDeviceRecordService.save(recordEntity);
                    break;
                }
                case "03": {
                    Date date = new Date();
                    ShDeviceRecordEntity recordEntity = new ShDeviceRecordEntity();
                    recordEntity.setDeviceId(device.getId());
                    //开关1  1:开 2:关
                    recordEntity.setAction(action1.equals("01") ? 1 : 2);
                    recordEntity.setCreateTime(date);
                    shDeviceRecordService.save(recordEntity);

                    ShDeviceRecordEntity recordEntity1 = new ShDeviceRecordEntity();
                    recordEntity1.setDeviceId(device.getId());
                    //开关2  3:开 4:关
                    recordEntity1.setAction(action2.equals("01") ? 3 : 4);
                    recordEntity1.setCreateTime(date);
                    shDeviceRecordService.save(recordEntity1);
                    break;
                }
            }
            sendCmd(device.getId(), action1.equals("01") ? "1" : "2", action2.equals("01") ? "1" : "2");

        }
        return ws;
    }

    private void sendCmd(Integer id, String statusO, String statusT) {
        String sss = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm");
        ShDlinkEntity dlinkEntity = otherShDlinkService.checkTime(sss.substring(sss.length()-5), id, statusO, statusT);
        if (dlinkEntity != null) {
            String key = "device:dlink:" + dlinkEntity.getStart() + "-" + dlinkEntity.getEnd() + ":" + dlinkEntity.getDeviceId();
            String json = redisUtils.get(key);
            logger.info("场景找到1" + json);
            if (StringUtils.isNotBlank(json)) {
                for (String s : json.split("-")) {
                    logger.info("场景找到2" + s);
                    mqProducer.sendT(s);
                }
            }
        }
    }

}
