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

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.utils.ByteUtils;
import tech.glinfo.enbao.common.utils.MapUtils;
import tech.glinfo.enbao.common.utils.R;
import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.common.validator.ValidatorUtils;
import tech.glinfo.enbao.modules.appuser.entity.AppUserEntity;
import tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity;
import tech.glinfo.enbao.modules.infrared.form.InfraredControlForm;
import tech.glinfo.enbao.modules.infrared.service.OtherInfraredControlService;
import tech.glinfo.enbao.modules.infrared.util.ProtocolUtil;
import tech.glinfo.enbao.modules.mq.MqProducer;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceEntity;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;
import tech.glinfo.enbao.modules.sh.service.ShDeviceService;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;


/**
 * 用户遥控器
 *
 * @author linzhenjie
 * @email linzhenjie@gltech.com
 * @date 2021-07-27 10:33:36
 */
@RestController
@RequestMapping("/infraredControl")
@Api(value = "用户遥控器")
public class InfraredControlController {

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

    @Autowired
    private OtherInfraredControlService otherInfraredControlService;

    @Autowired
    private ShDeviceService shDeviceService;

    @Autowired
    private MqProducer mqProducer;

    private static Map<String, String> temp = new HashMap<>();
    static {
        temp.put("17", "0000");
        temp.put("18", "0001");
        temp.put("19", "0011");
        temp.put("20", "0010");
        temp.put("21", "0110");
        temp.put("22", "0111");
        temp.put("23", "0101");
        temp.put("24", "0100");
        temp.put("25", "1100");
        temp.put("26", "1101");
        temp.put("27", "1001");
        temp.put("28", "1000");
        temp.put("29", "1010");
        temp.put("30", "1011");
    }

    private static Map<String, String> model = new HashMap<>();
    static {
        model.put("自动", "10");
        model.put("制冷", "00");
        model.put("抽湿", "01");
        model.put("制热", "11");
        model.put("送风", "01");
    }

    private static Map<String, String> wind = new HashMap<>();
    static {
        wind.put("自动", "101");
        wind.put("低风", "100");
        wind.put("中风", "010");
        wind.put("高风", "001");
        wind.put("固定风", "000");
    }

    @Login
    @GetMapping("list")
    @ApiOperation("查询用户遥控器")
    @ApiLog("查询用户遥控器")
    public R list(@RequestParam Map<String, Object> params, @LoginUser AppUserEntity user) {
        String deviceId = (String) params.get("deviceId");

        if (StringUtils.isNotBlank(deviceId)) {
            return otherInfraredControlService.list(Integer.valueOf(deviceId), user.getId());
        }else {
            return otherInfraredControlService.list(null, user.getId());
        }
    }

    @Login
    @GetMapping("info/{id}")
    @ApiOperation("遥控器信息")
    @ApiLog("遥控器信息")
    public R info(@PathVariable("id") Integer id) {

        InfraredControlEntity entity = otherInfraredControlService.getById(id);
        return R.ok().put("info", entity);
    }


    @Login
    @PostMapping("save")
    @ApiOperation("保存用户遥控器")
    @ApiLog("保存用户遥控器")
    public R save(@LoginUser AppUserEntity user, @RequestBody InfraredControlForm form) throws InvocationTargetException, IllegalAccessException {
        //表单校验
        ValidatorUtils.validateEntity(form);
        InfraredControlEntity entity = new InfraredControlEntity();
        BeanUtils.copyProperties(entity, form);
        entity.setUserId(user.getId());
        boolean save = otherInfraredControlService.save(entity);
        //新增设备遥控==开关的
        if(form.getDeviceId() != null) {
            //空调
            if("空调".equals(form.getDeviceType()) || "电视".equals(form.getDeviceType())) {
                String deviceType = form.getDeviceType();
                String model = form.getModel();
                Integer deviceId = form.getDeviceId();
                String rtype = form.getRtype();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        otherInfraredControlService.saveInfraredCode(deviceType, model, deviceId, rtype);
                    }
                }).start();
            }
        }

        return save ? R.ok(new MapUtils().put("id", entity.getId())) : R.error("新增失败");
    }

    @Login
    @PostMapping("update")
    @ApiOperation("修改用户遥控器")
    @ApiLog("修改用户遥控器")
    public R update(@RequestBody InfraredControlForm form) throws InvocationTargetException, IllegalAccessException {
        //表单校验
//        ValidatorUtils.validateEntity(form);
        if(StringUtils.isBlank(form.getRemark())){
            return R.error("遥控器名称必录！");
        }
        InfraredControlEntity entity = new InfraredControlEntity();
        BeanUtils.copyProperties(entity, form);
        return otherInfraredControlService.updateById(entity) ? R.ok() : R.error("更新失败");
    }


    @Login
    @PostMapping("delete")
    @ApiOperation("用户遥控器")
    @ApiLog("用户遥控器")
    public R delete(@RequestBody Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        InfraredControlEntity entity = otherInfraredControlService.getById(id);
        //删除红外缓存
        if(entity.getDeviceId() != null) {
            otherInfraredControlService.deleteInfraredCode(entity.getDeviceId(), entity.getDeviceType());
        }
        return otherInfraredControlService.removeById(id)? R.ok() : R.error("删除失败");
    }


    @Login
    @PostMapping("controllerT")
    public R controllerT(@RequestBody Map<String, Object> params) {
        String frequency = (String) params.get("frequency");//频率
        String datas = (String) params.get("datas");//数据
        Integer deviceId = (Integer) params.get("deviceId");//设备Id

        if(StringUtils.isBlank(frequency, datas, deviceId)) {
            return R.error("缺少参数");
        }

        ShDeviceEntity device = shDeviceService.getById(deviceId);
        if(device == null) {
            return R.error("设备不存在，请核实！");
        }

        if(device.getOnlineStatus() != 2) {
            return R.error("设备离线，无法发送！");
        }

        //转换
        StringBuffer sb = new StringBuffer();
        StringBuffer sb1 = new StringBuffer();
        String[] codes = datas.split(",");
        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(device.getNumbering());
        protocol.setDeviceType("02");
        logger.info("######数据长度：{}", codes.length);
        if(codes.length > 300) { //大于300需要走压缩
            String cmds = ProtocolUtil.getCmds(codes, frequency);
            logger.info("压缩后的数据：{}", cmds);
            protocol.setCmd("1B");
            protocol.setContent(cmds);
        } else {
            protocol.setCmd("19");
            for (String in : codes) {
                sb1.append(in).append(",");
                sb.append(ByteUtils.int2Hex(Integer.valueOf(in), 4));
            }
            logger.info(sb1.toString());
            logger.info(sb.toString());
            String content = StringUtils.appendString(sb.toString(), 1200, false, "0");
            logger.info(content);

//        InfraredControlCodeEntity controlCodeEntity = infraredControlCodeService.getOne(new QueryWrapper<InfraredControlCodeEntity>().eq("brand_id", controlUserEntity.getBrandId()).eq("remark", name).last("LIMIT 1"));
//        if (controlCodeEntity != null) {
            StringBuffer body = new StringBuffer();
            body.append(StringUtils.appendString(ByteUtils.int2Hex(Integer.valueOf(frequency)), 4, true, "0"));
            body.append(StringUtils.appendString(ByteUtils.int2Hex((sb.length()/2)),4, true, "0"));
            body.append(content);
            protocol.setContent(body.toString());
        }
        mqProducer.sendT(JSON.toJSONString(protocol));
        return R.ok();
    }


}
