package tech.glinfo.enbao.modules.sh.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import tech.glinfo.enbao.common.annotation.ApiLog;
import tech.glinfo.enbao.common.annotation.Login;
import tech.glinfo.enbao.common.annotation.LoginUser;
import tech.glinfo.enbao.common.contants.AppContants;
import tech.glinfo.enbao.common.utils.*;
import tech.glinfo.enbao.common.validator.ValidatorUtils;
import tech.glinfo.enbao.modules.appuser.entity.AppUserEntity;
import tech.glinfo.enbao.modules.mq.MqProducer;
import tech.glinfo.enbao.modules.mq.SpeakerService;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceDataEntity;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceEntity;
import tech.glinfo.enbao.modules.sh.entity.ShDevicePasswordEntity;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;
import tech.glinfo.enbao.modules.sh.form.ShDeviceForm;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceRecordService;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceService;
import tech.glinfo.enbao.modules.sh.service.ShDeviceDataService;
import tech.glinfo.enbao.modules.sh.service.ShDevicePasswordService;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

/**
 * @author linyetong
 * @date 2019/12/25 10:06
 */

@RestController
@RequestMapping("/shDevice")
@Api(value = "物共享设备", description = "物共享设备接口")
public class ShDeviceController {

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

    @Autowired
    private OtherShDeviceService otherShDeviceService;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private OtherShDeviceRecordService otherShDeviceRecordService;

    @Autowired
    private ShDevicePasswordService shDevicePasswordService;

    @Autowired
    private ShDeviceDataService shDeviceDataService;

    @Autowired
    private SpeakerService speakerService;

    @Autowired
    private RedisUtils redisUtils;
    @Value("${virtdevice.host}")
    private String host;


    @Login
    @PostMapping("save")
    @ApiOperation("配网成功")
    @ApiLog("配网成功")
    public R save(@RequestBody Map<String, Object> params, @LoginUser AppUserEntity user) {
        return otherShDeviceService.save(params, user);
    }

    @Login
    @PostMapping("update")
    @ApiOperation("修改")
    @ApiLog("修改")
    public R update(@RequestBody Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        String numberingFlag = (String) params.get("numberingFlag");
        String spareOne = (String) params.get("spareOne");
        ShDeviceEntity device = new ShDeviceEntity();
        device.setId(id);
        device.setNumberingFlag(numberingFlag);
        device.setSpareOne(spareOne);
        otherShDeviceService.updateById(device);
        return R.ok();
    }

    @Login
    @GetMapping("list")
    @ApiOperation("个人发布")
    @ApiLog("个人发布")
    public R list(@RequestParam Map<String, Object> params, @LoginUser AppUserEntity user) {

        return otherShDeviceService.list(params, user);
    }


    @Login
    @PostMapping("delete")
    @ApiOperation("设备删除【id:设备id】")
    @ApiLog("设备删除")
    public R delete(@RequestBody Map<String, Object> params, @LoginUser AppUserEntity user) {

        return otherShDeviceService.delete(params, user);
    }


    @Login
    @GetMapping("getDeviceId/{numbering}")
    @ApiOperation("扫描设备二维码")
    @ApiLog("扫描设备二维码")
    public R getDeviceId(@PathVariable("numbering") String numbering) {
        return otherShDeviceService.getDeviceId(numbering);
    }
    @Login
    @PostMapping("controller")
    @ApiOperation("设备控制")
    @ApiLog("设备控制")
    public R controller(@RequestBody ProtocolContent form) {
        ValidatorUtils.validateEntity(form);
        ShDeviceEntity entity = otherShDeviceService.getById(form.getDeviceId());
        if (entity == null) {
            return R.error("设备不存在");
        }
        if (entity.getOnlineStatus() != 2) {
            return R.error("设备不在线");
        }

        form.setReceiveId(entity.getNumbering());
        mqProducer.sendT(JSON.toJSONString(form));
        return R.ok();
    }

    @Login
    @PostMapping("controller1")
    @ApiOperation("设备控制1")
    @ApiLog("设备控制1")
    public R controller1(@RequestBody Map<String, Object> params, @LoginUser AppUserEntity user) {
        Object id = params.get("id");
        if (id == null) {
            return R.error("缺少参数");

        }
        Integer type = (Integer) params.get("type");

        ShDeviceEntity entity = otherShDeviceService.getById((Integer) id);
        if (entity == null) {
            return R.error("设备不存在");
        }
        if (entity.getOnlineStatus() != 2) {
            return R.error("设备不在线");
        }
        //暂时不校验用户相关==比如是否为物主，是否为该站点管理员
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(entity.getNumbering());
        String date = (String) params.get("date");
        protocol.setDeviceType("01");
        protocol.setCmd("12");//设置设备使用期限
        if (type != null && 2 == type) {//设置为当前时间
            protocol.setContent(DateUtils.getHexByDate(new Date()));
        } else if (StringUtils.isNotEmpty(date)) {
            protocol.setContent(DateUtils.getHexByDate(DateUtils.stringToDate(date, "yyyy-MM-dd HH:mm")));
        } else {//永久使用
            if (!entity.getUserId().equals(user.getId())) {
                return R.error("设备所属人才能清除使用期限");
            }
            protocol.setContent("FFFFFFFFFFFFFF");
        }
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @GetMapping("info/{id}")
    @ApiOperation("设备信息")
//    @ApiLog("设备信息")
    public R info(@PathVariable("id") String id) {
        return otherShDeviceService.info(id);
    }

    @Login
    @GetMapping("deviceInfo")
    @ApiOperation("设备信息")
//    @ApiLog("设备信息")
    public R deviceInfo(@RequestParam Map<String, Object> params) {
        return R.ok().put("device", otherShDeviceService.deviceInfo(params));
    }


    @Login
    @PostMapping("open")
    @ApiOperation("远程开门")
    @ApiLog("远程开门")
    public R open(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        if(mac == null) {
            return R.error("缺少参数");
        }
        String open = redisUtils.get(mac + ":open");
        if(open == null) {
            return R.error("指令已失效");
        }
        //暂时不校验用户相关==比如是否为物主，是否为该站点管理员
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setContent("01");
        protocol.setDeviceType("06");
        protocol.setCmd("1F");//设置设备使用期限
        mqProducer.sendT(JSON.toJSONString(protocol));
//        redisUtils.set(mac + "open", "2", 1);
        return R.ok();
    }


    @Login
    @PostMapping("smartLockOpen")
    @ApiOperation("指纹门锁远程开门")
    @ApiLog("指纹门锁远程开门")
    public R smartLockOpen(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        if(mac == null) {
            return R.error("缺少参数");
        }
        String open = redisUtils.get(mac + ":open");
        //暂时不校验用户相关==比如是否为物主，是否为该站点管理员
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType("10");
        protocol.setCmd("23");
        if(open == null) {
            protocol.setContent("02000000");
            mqProducer.sendT(JSON.toJSONString(protocol));
            return R.error("指令已失效");
        }

        protocol.setContent("01000000");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @GetMapping("lockIndex")
    @ApiOperation("智能锁主页")
    @ApiLog("智能锁主页")
    public R lockIndex(@RequestParam Map<String, Object> params) {
        Integer deviceId = Integer.parseInt((String) params.get("deviceId"));
        if (StringUtils.isBlank(deviceId)) {
            return R.error("缺少参数");
        }

        PageUtils page = otherShDeviceRecordService.queryPage(params);
        ShDeviceEntity device = otherShDeviceService.getById(deviceId);
        //临时密码
        Integer count = shDevicePasswordService.count(new QueryWrapper<ShDevicePasswordEntity>().eq("device_id", deviceId).eq("type", 2).eq("status", 1));
        ShDevicePasswordEntity passwordEntity = shDevicePasswordService.getOne(new QueryWrapper<ShDevicePasswordEntity>().eq("device_id", deviceId).eq("type", 1).orderByDesc("id").last("LIMIT 1"));
        ShDeviceDataEntity dataEntity = shDeviceDataService.getOne(new QueryWrapper<ShDeviceDataEntity>().eq("device_id", deviceId));
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("device", device);
        map.put("count", count);
        if(passwordEntity != null) {
            map.put("password", passwordEntity.getPassword());
            map.put("status", passwordEntity.getStatus());
        }
        map.put("data", dataEntity);
        return R.ok().put("result", map);
    }

    @Login
    @GetMapping("index")
    @ApiOperation("设备主页")
    @ApiLog("设备主页")
    public R index(@RequestParam Map<String, Object> params) {
        Integer deviceId = Integer.parseInt((String) params.get("deviceId"));
        if (StringUtils.isBlank(deviceId)) {
            return R.error("缺少参数");
        }

        ShDeviceEntity device = otherShDeviceService.getById(deviceId);
        ShDeviceDataEntity dataEntity = shDeviceDataService.getOne(new QueryWrapper<ShDeviceDataEntity>().eq("device_id", deviceId));
        Map<String, Object> map = new HashMap<>();
        map.put("device", device);

        map.put("data", dataEntity);
        return R.ok().put("result", map);
    }

    @Login
    @PostMapping("switchController")
    @ApiOperation("智能开关、插座控制")
    @ApiLog("智能开关、插座控制")
    public R switchController(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        String action = (String) params.get("action");
        String type = (String) params.get("type");
        Integer flag = (Integer) params.get("flag");
        if(StringUtils.isBlank(mac, action)) {
            return R.error("缺少参数");
        }

        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType(type);
        protocol.setCmd("18");
        if (flag == null) {
            redisUtils.set(mac + "action", action.substring(0, 2), 50);
            protocol.setContent(action + "000000000001");
        }else {
            if (flag == 1) {
                protocol.setContent(action + "000000000001");
                redisUtils.set(mac + "action1", action.substring(0, 2).equals("01") ? 1 : 2, 50);
            }else {
                protocol.setContent(action + "000000000002");
                redisUtils.set(mac + "action2", action.substring(2, 4).equals("01") ? 3 : 4, 50);
            }
        }
        mqProducer.sendT(JSON.toJSONString(protocol));

        return R.ok();
    }


    @Login
    @PostMapping("humidifierController")
    @ApiOperation("加湿器控制")
    @ApiLog("加湿器控制")
    public R humidifierController(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        Integer workingGear = (Integer) params.get("workingGear");
        Integer UVLampStatus = (Integer) params.get("UVLampStatus");
        Integer targetHumidity = (Integer) params.get("targetHumidity");
        if(StringUtils.isBlank(mac, workingGear, UVLampStatus, targetHumidity)) {
            return R.error("缺少参数");
        }
        int workingStatus;
        if (workingGear == 0) {
            workingStatus = 0;
        }else {
            workingStatus = 1;
        }
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        String content = ByteUtils.int2Hex(workingStatus) + //工作状态
                ByteUtils.int2Hex(UVLampStatus) + //紫外线状态
                ByteUtils.int2Hex(workingGear) + //工作档位
                "00" + //自定义档位
                ByteUtils.int2Hex(targetHumidity) + //目标湿度
                "000000";
        protocol.setContent(content);
        protocol.setDeviceType("08");
        protocol.setCmd("18");
        mqProducer.sendT(JSON.toJSONString(protocol));
//        redisUtils.set(mac + "action", action);
        return R.ok();
    }

    @Login
    @PostMapping("curtainController")
    @ApiOperation("窗帘控制")
    @ApiLog("窗帘控制")
    public R curtainController(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        Integer action = (Integer) params.get("action");
//        Integer position = (Integer) params.get("position");
        if(StringUtils.isBlank(mac, action)) {
            return R.error("缺少参数");
        }
        int position;
        int action1 = 1;
        if (action == 1) {
            position = 0;//关闭
        }else if (action == 2) {
            position = 50;//暂停
            action1 = 0;
        }else{
            position = 100;//开启
        }

        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setContent(ByteUtils.int2Hex(action1) + ByteUtils.int2Hex(position) + "000000000000");
        protocol.setDeviceType("05");
        protocol.setCmd("18");
        mqProducer.sendT(JSON.toJSONString(protocol));
        redisUtils.set(mac + "position", position, 50);
        return R.ok();
    }

    @Login
    @PostMapping("airerController")
    @ApiOperation("晾衣架控制")
    @ApiLog("晾衣架控制")
    public R airerController(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        String type = (String) params.get("type");
        Integer operatingStatus = (Integer) params.get("operatingStatus");
        Integer light = (Integer) params.get("light");
        Integer UVState = (Integer) params.get("UVState");
        Integer fanStatus = (Integer) params.get("fanStatus");
        Integer dryingHeatingState = (Integer) params.get("dryingHeatingState");
        if(StringUtils.isBlank(mac, operatingStatus, light, UVState, fanStatus, dryingHeatingState)) {
            return R.error("缺少参数");
        }

        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        if (StringUtils.isBlank(type)) {
            protocol.setContent(ByteUtils.int2Hex(operatingStatus) + ByteUtils.int2Hex(light) +
                    ByteUtils.int2Hex(UVState) + ByteUtils.int2Hex(fanStatus) + ByteUtils.int2Hex(dryingHeatingState) + "010000");
        }else {
            protocol.setContent(ByteUtils.int2Hex(operatingStatus) + ByteUtils.int2Hex(light) +
                    ByteUtils.int2Hex(UVState) + ByteUtils.int2Hex(fanStatus) + ByteUtils.int2Hex(dryingHeatingState) + "0100" + type);
        }

        protocol.setDeviceType("07");
        protocol.setCmd("18");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }


    @Login
    @PostMapping("wasteController")
    @ApiOperation("垃圾处理器控制")
    @ApiLog("垃圾处理器控制")
    public R wasteController(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        String action = (String) params.get("action");

        if(StringUtils.isBlank(mac, action)) {
            return R.error("缺少参数");
        }

        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        //测试用，开时开启紫外线灯
        protocol.setContent(action + action + "000000000000");
        protocol.setDeviceType("04");
        protocol.setCmd("18");
        mqProducer.sendT(JSON.toJSONString(protocol));
//        redisUtils.set(mac + "waste", action);
        return R.ok();
    }

    @Login
    @PostMapping("wasteLightController")
    @ApiOperation("垃圾处理器紫外线控制")
    @ApiLog("垃圾处理器紫外线控制")
    public R wasteLightController(@RequestBody ProtocolContent form) {
        ValidatorUtils.validateEntity(form);
        ShDeviceEntity entity = otherShDeviceService.getById(form.getDeviceId());
        if (entity == null) {
            return R.error("设备不存在");
        }
        if (entity.getOnlineStatus() != 2) {
            return R.error("设备不在线");
        }
        form.setReceiveId(entity.getNumbering());
        mqProducer.sendT(JSON.toJSONString(form));
        return R.ok();
    }

    @Login
    @PostMapping("wasteController1")
    @ApiOperation("设备控制1")
    @ApiLog("设备控制1")
    public R wasteController1(@RequestBody Map<String, Object> params, @LoginUser AppUserEntity user) {
        Object id = params.get("id");
        if (id == null) {
            return R.error("缺少参数");

        }
        Integer type = (Integer) params.get("type");

        String deviceType = (String) params.get("deviceType");

        ShDeviceEntity entity = otherShDeviceService.getById((Integer) id);
        if (entity == null) {
            return R.error("设备不存在");
        }
        if (entity.getOnlineStatus() != 2) {
            return R.error("设备不在线");
        }
        //暂时不校验用户相关==比如是否为物主，是否为该站点管理员
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(entity.getNumbering());
        String date = (String) params.get("date");
        protocol.setDeviceType(deviceType);
        protocol.setCmd("12");//设置设备使用期限
        if (type != null && 2 == type) {//设置为当前时间
            protocol.setContent(DateUtils.getHexByDate(new Date()));
        } else if (StringUtils.isNotEmpty(date)) {
            protocol.setContent(DateUtils.getHexByDate(DateUtils.stringToDate(date, "yyyy-MM-dd HH:mm")));
        } else {//永久使用
            if (!entity.getUserId().equals(user.getId())) {
                return R.error("设备所属人才能清除使用期限");
            }
            protocol.setContent("FFFFFFFFFFFFFF");
        }
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @PostMapping("wasteController2")
    @ApiOperation("垃圾处理器控制")
    @ApiLog("垃圾处理器控制")
    public R wasteController2(@RequestBody Map<String, Object> params) {
//        ByteUtils.int2Hex(position)
        String mac = (String) params.get("mac");
        Integer high = (Integer) params.get("high");
        Integer low = (Integer) params.get("low");
        Integer switchStatus1 = (Integer) params.get("switchStatus1");
        Integer switchStatus2 = (Integer) params.get("switchStatus2");

        if(StringUtils.isBlank(mac, high, low, switchStatus1, switchStatus2)) {
            return R.error("缺少参数");
        }

        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setContent(ByteUtils.int2Hex(high) + ByteUtils.int2Hex(switchStatus1) + ByteUtils.int2Hex(low) + ByteUtils.int2Hex(switchStatus2) + "00000000");
        protocol.setDeviceType("04");
        protocol.setCmd("1A");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }


    @Login
    @PostMapping("switchTempSetting")
    @ApiOperation("开关温度设定")
    @ApiLog("开关温度设定")
    public R switchTempSetting(@RequestBody Map<String, Object> params) {
        logger.info("params = " + params);
        Integer id = (Integer) params.get("id");//设备编号
        String tempH1 = (String) params.get("tempH1");//开关1高温预警设定温度
        String switchH1 = (String) params.get("switchH1");//开关1高温预警开关状态
        String tempL1 = (String) params.get("tempL1");//开关1低温预警设定温度
        String switchL1 = (String) params.get("switchL1");//开关1低温预警开关状态
        String tempH2 = (String) params.get("tempH2");//开关2高温预警设定温度
        String switchH2 = (String) params.get("switchH2");//开关2高温预警开关状态
        String tempL2 = (String) params.get("tempL2");//开关2低温预警设定温度
        String switchL2 = (String) params.get("switchL2");//开关2低温预警开关状态

        //判断是否为空
        if(StringUtils.isBlank(id, tempH1, switchH1, tempL1, switchL1, tempH2, switchH2,
                tempL2, switchL2)) {
            return R.error("缺少参数");
        }
        ShDeviceEntity deviceEntity = otherShDeviceService.getById(id);
        if (deviceEntity == null) {
            return R.error("设备不存在");
        }
        if (deviceEntity.getOnlineStatus() != 2) {
            return R.error("设备不在线");
        }

        //发送指令
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(deviceEntity.getNumbering());
        protocol.setContent(ByteUtils.signInt2HexString(tempH1, 2) + ByteUtils.signInt2HexString(switchH1, 2) + ByteUtils.signInt2HexString(tempL1, 2) + ByteUtils.signInt2HexString(switchL1, 2) +
                ByteUtils.signInt2HexString(tempH2, 2) + ByteUtils.signInt2HexString(switchH2, 2) + ByteUtils.signInt2HexString(tempL2, 2) + ByteUtils.signInt2HexString(switchL2, 2));
        protocol.setDeviceType("02");
        protocol.setCmd("1A");
        mqProducer.sendT(JSON.toJSONString(protocol));

        redisUtils.set(deviceEntity.getNumbering() + "temp", protocol.getContent(), 50);
        return R.ok();
    }

    @Login
    @PostMapping("outletTempSetting")
    @ApiOperation("插座温度设定")
    @ApiLog("插座温度设定")
    public R outletTempSetting(@RequestBody Map<String, Object> params) {
        logger.info("params = " + params);
        Integer id = (Integer) params.get("id");//设备编号
        String tempH = (String) params.get("tempH");//开关1高温预警设定温度
        String switchH = (String) params.get("switchH");//开关1高温预警开关状态
        String tempL = (String) params.get("tempL");//开关1低温预警设定温度
        String switchL = (String) params.get("switchL");//开关1低温预警开关状态

        //判断是否为空
        if(StringUtils.isBlank(id, tempH, switchH, tempL, switchL)) {
            return R.error("缺少参数");
        }
        ShDeviceEntity deviceEntity = otherShDeviceService.getById(id);
        if (deviceEntity == null) {
            return R.error("设备不存在");
        }
        if (deviceEntity.getOnlineStatus() != 2) {
            return R.error("设备不在线");
        }

        //发送指令
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(deviceEntity.getNumbering());
        protocol.setContent(ByteUtils.signInt2HexString(tempH, 2) + ByteUtils.signInt2HexString(switchH, 2) + ByteUtils.signInt2HexString(tempL, 2) + ByteUtils.signInt2HexString(switchL, 2) + "00000000");
        protocol.setDeviceType("03");
        protocol.setCmd("1A");
        mqProducer.sendT(JSON.toJSONString(protocol));
        redisUtils.set(deviceEntity.getNumbering() + "temp", protocol.getContent());
        return R.ok();
    }

    @Login
    @PostMapping("updateDeviceData1")
    @ApiOperation("更新设备数据")
    @ApiLog("更新设备数据")
    public R updateDeviceData1(@RequestBody Map<String, Object> params) {
        Integer deviceId = (Integer) params.get("deviceId");
        String name = (String) params.get("name");
        String val = (String) params.get("val");
        ShDeviceDataEntity entity = shDeviceDataService.getOne(new QueryWrapper<ShDeviceDataEntity>().eq("device_id", deviceId));
        if (entity != null) {
            JSONObject jsonObj = new JSONObject(entity.getValue());
            jsonObj.put(name, val);
            entity.setValue(jsonObj.toString());
            return shDeviceDataService.updateById(entity) ? R.ok() : R.error("更新数据失败");
        }
        return R.error("没有设备数据");
    }

    @Login
    @PostMapping("updateDeviceInfo")
    @ApiOperation("更新设备信息")
    @ApiLog("更新设备信息")
    public R updateDeviceInfo(@RequestBody Map<String, Object> params) {
        Integer deviceId = (Integer) params.get("deviceId");
        String one = (String) params.get("one");
        String two = (String) params.get("two");
        ShDeviceEntity entity = new ShDeviceEntity();
        entity.setId(deviceId);
        entity.setSpareOne(one);
        entity.setSpareTwo(two);
        boolean rtn = otherShDeviceService.updateById(entity);
        return rtn?R.ok():R.error("更新失败");
    }

    @Login
    @PostMapping("faceLockController")
    @ApiOperation("智能人脸锁控制")
    @ApiLog("智能人脸锁控制")
    public R faceLockController(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        Integer type = (Integer) params.get("type");
        ProtocolContent protocol = new ProtocolContent();
        ShDeviceEntity devcie = otherShDeviceService.deviceInfo(new MapUtils().put("numbering", mac));
        if(devcie == null) {
            return R.error("设备不存在！");
        }
        if (type == 1) {
             protocol.setContent(DateUtils.getHexByDate(DateUtils.stringToDate("2020-04-05 12:10", "yyyy-MM-dd HH:mm")));
         } else {
             protocol.setContent("FFFFFFFFFFFFFF");
         }
        protocol.setReceiveId(mac);
        protocol.setDeviceType("11");
        protocol.setCmd("12");
        String json = JSON.toJSONString(protocol);
        redisUtils.set("device:sendcmd:"+mac, json);
        return R.ok();
    }

    @Login
    @PostMapping("faceLockReadServiceLife")
    @ApiOperation("智能人脸锁读取使用期限")
    @ApiLog("智能人脸锁读取使用期限")
    public R faceLockReadServiceLife(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType("11");
        protocol.setContent("");
        protocol.setCmd("04");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @PostMapping("faceLockSetTime")
    @ApiOperation("智能人脸锁设置时间")
    @ApiLog("智能人脸锁设置时间")
    public R faceLockSetTime(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType("11");
        protocol.setContent(DateUtils.getHexByDate(new Date()));
        protocol.setCmd("11");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @PostMapping("faceLockReadTime")
    @ApiOperation("智能人脸锁读取时间")
    @ApiLog("智能人脸锁读取时间")
    public R faceLockReadTime(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType("11");
        protocol.setContent("");
        protocol.setCmd("03");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @PostMapping("faceLockSendPwd")
    @ApiOperation("智能人脸锁发送密码")
    @ApiLog("智能人脸锁发送密码")
    public R faceLockSendPwd(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        Integer id = (Integer) params.get("id");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType("11");
        ShDevicePasswordEntity passwordEntity = shDevicePasswordService.getOne(new QueryWrapper<ShDevicePasswordEntity>().eq("device_id", id).eq("status", 1).last("LIMIT 1"));
        if (passwordEntity != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("0101FF");
            Date date;
            if (passwordEntity.getExpiredTime() != null) {
                date = passwordEntity.getExpiredTime();
            }else {
                date = DateUtils.addDateMinutes(new Date(), 5);
            }
            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(passwordEntity.getType() == 1 ? "" : "00");
            protocol.setContent(sb.toString());
            protocol.setCmd("1D");
            mqProducer.sendT(JSON.toJSONString(protocol));
            redisUtils.set("lockpwd" + id, passwordEntity.getId(), 60);
            if (passwordEntity.getExpiredTime() == null) {
                passwordEntity.setExpiredTime(date);
                shDevicePasswordService.updateById(passwordEntity);
            }
            return R.ok();
        }
        return R.error("没有密码可下发");
    }

    @Login
    @PostMapping("faceLockOpen")
    @ApiOperation("智能人脸锁远程开锁")
    @ApiLog("智能人脸锁远程开锁")
    public R faceLockOpen(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        if(!redisUtils.hasKey(AppContants.DEVICE_OPEN_EVENT + mac)) {
            return R.error("该指令已超时！");
        }
        Integer id = (Integer) params.get("id");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType("11");
        protocol.setContent("01000000");
        protocol.setCmd("23");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }


    @Login
    @PostMapping("outletLightController")
    @ApiOperation("插座灯光控制")
    @ApiLog("插座灯光控制")
    public R outletLightController(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        Integer status = (Integer) params.get("status");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType("03");
        protocol.setContent("00" + ByteUtils.int2Hex(status) + "000000000002");
        protocol.setCmd("18");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @PostMapping("switchLightController")
    @ApiOperation("开关灯光控制")
    @ApiLog("开关灯光控制")
    public R switchLightController(@RequestBody Map<String, Object> params) {
        String mac = (String) params.get("mac");
        Integer status = (Integer) params.get("status");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(mac);
        protocol.setDeviceType("02");
        protocol.setContent("0000" + ByteUtils.int2Hex(status) + "0000000004");
        protocol.setCmd("18");
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @PostMapping("speakerController")
    @ApiOperation("智能音箱控制")
    @ApiLog("智能音箱控制")
    public R speakerController(@RequestBody Map<String, Object> params) {
        Integer deviceId = (Integer) params.get("deviceId");
        ShDeviceEntity entity = otherShDeviceService.getById(deviceId);
        if(entity == null) {
            return R.error("设备不存在！");
        }
        if(entity.getOnlineStatus() != 2) {
            return R.error("设备不在线，无法控制！");
        }

        String cmd = (String) params.get("cmd");
        String content = (String) params.get("content");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(entity.getNumbering());
        protocol.setDeviceType("0F");
        protocol.setContent(content);
        protocol.setCmd(cmd);
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }

    @Login
    @PostMapping("speakerPlay")
    @ApiOperation("智能音箱播放")
    @ApiLog("智能音箱播放")
    public R speakerPlay(@RequestBody Map<String, Object> params) {
        ShDeviceEntity entity = otherShDeviceService.getById((Integer) params.get("deviceId"));
        if(entity == null) {
            return R.error("设备不存在！");
        }
        if(entity.getOnlineStatus() != 2) {
            return R.error("设备不在线，无法控制！");
        }

        Integer id = (Integer) params.get("id");//AppContants.SPEAKER_FILE_SEND + deviceNo + "-id-"+id
        if(redisUtils.hasKey(AppContants.SPEAKER_FILE_SEND + entity.getNumbering() + "-id-"+id)) {
            return R.error("该歌曲正在下载，请稍等！");
        }

        String name = (String) params.get("name");
        String fileType = name.substring(name.lastIndexOf("."));
        String fileName = StringUtils.appendString(id+"", 4, true, "0") + fileType;
        //播放
        speakerService.delOrPlayMusic(entity.getNumbering(), fileName, "01");
        return R.ok();
    }

    @Login
    @GetMapping("personalDevice")
    @ApiOperation("个人设备列表")
    @ApiLog("个人设备列表")
    public R personalDevice(@LoginUser AppUserEntity user) {
        List<ShDeviceEntity> list = otherShDeviceService.list(
                new QueryWrapper<ShDeviceEntity>().eq("user_id", user.getId())
                        .in("product_id", 2, 8, 9, 10, 6, 14, 15)
                        .orderByDesc("id"));
        List<ShDeviceEntity> list1 = new ArrayList<>();
        List<ShDeviceEntity> list2 = new ArrayList<>();
        for (ShDeviceEntity map : list) {
            Integer type =  map.getProductId();
            if (type == 2 || type == 8 || type == 9 || type == 10) {
                list2.add(map);
            }else {
                list1.add(map);
            }
        }

        return R.ok().put("lockList", list1).put("otherList", list2);
    }

}
