package tech.glinfo.enbao.modules.mq;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.*;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceRecordService;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceService;
import tech.glinfo.enbao.modules.sh.service.OtherShDlinkService;
import tech.glinfo.enbao.modules.sh.service.ShDevicePasswordService;

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


//智能锁
@Component("smartLockParse")
public class SmartLockParse implements IParse {

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

    @Autowired
    private OtherShDeviceService otherShDeviceService;

    @Autowired
    private OtherShDeviceRecordService otherShDeviceRecordService;

    @Autowired
    private ShDevicePasswordService shDevicePasswordService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private TimeParseUtils timeParseUtils;

    @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<>();

//        ws.put("deviceId", String.valueOf(device.getId()));
        if("91".equals(datas.get("cmd"))) {//登录包
            redisUtils.delete(datas.get("receiveId"));
        }
        else 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"), "10");
            }).start();

            return datas;
        }else if("01".equals(datas.get("cmd"))) {//数据上报
            //数据上报
            //查询解析指令集
            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 = String.valueOf(Integer.valueOf(hex, 16));
                    map.put(cmd.getName(), hex1);
                    ws.put(cmd.getName(), hex1);
                    length += cmd.getLength();
                }
                otherShDeviceService.updateDeviceData(JSON.toJSONString(map), device.getId());
            }

        } else if("20".equals(datas.get("cmd")) && datas.get("content").substring(0, 2).equals("04")) {//远程开锁请求
            redisUtils.set(datas.get("receiveId")+":open", 1, 60);//30S有效
            ws.put("open", "1");

        } else if("1D".equals(datas.get("cmd")) && datas.get("content").substring(0, 2).equals("01")) {//查询动态密码/临时密码

            //临时密码
            int count = shDevicePasswordService.count(new QueryWrapper<ShDevicePasswordEntity>().eq("device_id", device.getId()).eq("status", 1));
            ProtocolContent protocol = new ProtocolContent();
            protocol.setCmd("1D");
            protocol.setDeviceType("10");
            protocol.setReceiveId(device.getNumbering());
            if (count > 0) {
                ShDevicePasswordEntity passwordEntity = shDevicePasswordService.getOne(new QueryWrapper<ShDevicePasswordEntity>().eq("device_id", device.getId()).eq("status", 1).last("LIMIT 1"));
                StringBuilder sb = new StringBuilder();
                sb.append(ByteUtils.int2Hex(count));
                sb.append(ByteUtils.int2Hex(passwordEntity.getType() == 1 ? 2 : 1));
                sb.append("FF");
                Date date;
                Date date1 = new Date();
                if (passwordEntity.getExpiredTime() != null) {
                    date = passwordEntity.getExpiredTime();
                }else {
                    date = DateUtils.addDateMinutes(date1, 5);
                    passwordEntity.setExpiredTime(DateUtils.addDateMinutes(date1, 5));
                    shDevicePasswordService.updateById(passwordEntity);
                }
                sb.append(ByteUtils.int2Hex((int) (date.getTime() / 1000)));
                sb.append("00");
                if (passwordEntity.getType() == 1) {
                    sb.append(ByteUtils.int2Hex(8));
                }else {
                    sb.append(ByteUtils.int2Hex(6));
                }
//                sb.append(ByteUtils.strToHex(passwordEntity.getPassword()));
                sb.append(ByteUtils.strToHex(passwordEntity.getPassword()));
                sb.append(passwordEntity.getType() == 1 ? "" : "0000");
                protocol.setContent(sb.toString());
                redisUtils.set("lockpwd" + device.getId(), passwordEntity.getId(), 60);
            }else {
                protocol.setContent("0000000000000000000000000000000000");
            }
            //下发给MQ，IoT接收到MQ消息会下发给设备
            mqProducer.sendT(JSON.toJSONString(protocol));
        }else if("1D".equals(datas.get("cmd")) && datas.get("content").substring(0, 2).equals("02")) {
            String content = datas.get("content");
            String id = redisUtils.get("lockpwd" + device.getId());
            if (id != null) {
                ShDevicePasswordEntity one = shDevicePasswordService.getById(id);
                one.setId(Integer.parseInt(id));
                int sta = Integer.parseInt(content.substring(2, 4), 16);
                if (sta != 0) {
                    one.setStatus(2);
                    ws.put("dpwd", one.getPassword());
                }else {
                    one.setStatus(4);
                }
                shDevicePasswordService.updateById(one);
                redisUtils.delete("lockpwd" + device.getId());
            }

        }else if("20".equals(datas.get("cmd")) && datas.get("content").substring(0, 2).equals("01")) {
            String content = datas.get("content");
            int action = Integer.parseInt(content.substring(2, 4), 16);
            ShDeviceRecordEntity recordEntity = new ShDeviceRecordEntity();
            recordEntity.setDeviceId(device.getId());
            recordEntity.setAction(action);
            otherShDeviceRecordService.save(recordEntity);

            //场景检查
            sendCmd(device.getId());

           /* SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            long lt = new Long(s);

            //将时间戳转换为时间

            Date date = new Date(lt);

            //将时间调整为yyyy-MM-dd HH:mm:ss时间样式

            res = simpleDateFormat.format(date);*/

        }

        return ws;
    }

    private void sendCmd(Integer id) {
        String sss = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm");
        ShDlinkEntity dlinkEntity = otherShDlinkService.checkTime(sss.substring(sss.length()-5), id, null, null);
        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);
                }
            }
        }
    }

}
