package tech.glinfo.enbao.modules.infrared.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.glinfo.enbao.common.contants.AppContants;
import tech.glinfo.enbao.common.utils.*;
import tech.glinfo.enbao.modules.infrared.dao.InfraredControlDao;
import tech.glinfo.enbao.modules.infrared.dao.OtherInfraredControlDao;
import tech.glinfo.enbao.modules.infrared.entity.InfraredControlEntity;
import tech.glinfo.enbao.modules.infrared.service.OtherInfraredControlService;
import tech.glinfo.enbao.modules.infrared.util.ProtocolUtil;
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.util.List;
import java.util.Map;


@Service("otherInfraredControlService")
public class OtherInfraredControlServiceImpl extends ServiceImpl<OtherInfraredControlDao, InfraredControlEntity> implements OtherInfraredControlService {

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

    //红外码库接口地址
    public static final String INFRAREDURL = "https://cir.zwgongxiang.com/";
    @Autowired
    private ShDeviceService shDeviceService;

    @Autowired
    private RedisUtils redisUtils;


    @Override
    public R list(Integer deviceId, Integer userId) {
        List<Map<String, Object>> list = this.baseMapper.list(deviceId, userId);
        return R.ok().put("list", list);
    }

    @Override
    public void saveInfraredCode(String deviceType, String model, Integer deviceId, String rtype) {
        //电视==电视是根据按键索引来获取红外数据
        if("电视".equals(deviceType)) {
            getDataFormIndex("电源", true, model, deviceId);
        } else if("空调".equals(deviceType)) {
            if(!"1".equals(rtype) && !"2".equals(rtype)) {//rtype不等于1和2是根据键值来获取红外数据
                getDataFormIndex("电源", false, model, deviceId);
            } else {
                String close = "&par=1-1-8-0-0-";//关机指令参数
                String open = "&par=0-1-8-0-0-";//开机指令参数
                if("1".equals(rtype)) {
                    close += '0';
                    open += '0';
                } else {
                    open += 'X';
                    close += 'X';
                }
                String openData = HttpUtil.doGet(INFRAREDURL + "keyevent.php?mac=d6a5e6f31f794be0&kfid=" + model + open);
                JSONObject openDataJson = JSON.parseObject(openData);
                if(openDataJson.containsKey("irdata")) {
                    String irdata = openDataJson.getString("irdata");
                    int first = irdata.indexOf(",");
                    String frequency = irdata.substring(0, first);
                    String data = irdata.substring(first + 1, irdata.length() - 1);
                    //打开空调
                    packageData(AppContants.INFRARED_AIR_KEY + deviceId + "_1", deviceId, frequency, data);
                }
                String closeData = HttpUtil.doGet(INFRAREDURL + "keyevent.php?mac=d6a5e6f31f794be0&kfid=" + model + close);
                JSONObject closeDataJson = JSON.parseObject(closeData);
                if(closeDataJson.containsKey("irdata")) {
                    String irdata = closeDataJson.getString("irdata");
                    int first = irdata.indexOf(",");
                    String frequency = irdata.substring(0, first);
                    String data = irdata.substring(first + 1, irdata.length() - 1);
                    //关闭空调
                    packageData(AppContants.INFRARED_AIR_KEY + deviceId + "_2", deviceId, frequency, data);
                }
            }
        }
    }

    @Override
    public void deleteInfraredCode(Integer deviceId, String deviceType) {
        if("电视".equals(deviceType)) {
            redisUtils.delete(AppContants.INFRARED_TV_KEY + deviceId);
        } else if("空调".equals(deviceType)) {
            redisUtils.delete(AppContants.INFRARED_AIR_KEY + deviceId);
            redisUtils.delete(AppContants.INFRARED_AIR_KEY + deviceId + "_1");
            redisUtils.delete(AppContants.INFRARED_AIR_KEY + deviceId + "_2");
        }
    }

    /**
     * 根据键值索引来获取红外数据
     * @param key 中文按键
     * @param flag true为电视，false为空调
     * @param model
     * @param deviceId
     */
    private void getDataFormIndex(String key, boolean flag, String model, Integer deviceId) {
        String keys = HttpUtil.doGet(INFRAREDURL + "getkeylist.php?mac=d6a5e6f31f794be0&kfid=" + model);
        if(keys != null) {
            JSONObject json = JSON.parseObject(keys);
            if(json.containsKey("keylist")) {
                JSONArray keylist = json.getJSONArray("keylist");
                int index = 0;
                for(int i=0; i<keylist.size();i++) {
                    if(key.equals(keylist.getString(i))) {
                        index = flag ? i+1 : i;
                        break;
                    }
                }
                if(index > 0) {
                    String datas = HttpUtil.doGet(INFRAREDURL + "keyevent.php?mac=d6a5e6f31f794be0&keyid="+index+"&kfid=" + model);
                    JSONObject dataJson = JSON.parseObject(datas);
                    if(dataJson.containsKey("irdata")) {
                        String irdata = dataJson.getString("irdata");
                        int first = irdata.indexOf(",");
                        String frequency = irdata.substring(0, first);
                        String data = irdata.substring(first + 1, irdata.length() - 1);
                        packageData((flag?AppContants.INFRARED_TV_KEY : AppContants.INFRARED_AIR_KEY) + deviceId, deviceId, frequency, data);
                    }
                }
            }
        }
    }

    private void packageData(String redisKey, Integer deviceId, String frequency, String datas) {
        ShDeviceEntity device = shDeviceService.getById(deviceId);
        //转换
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        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.parseInt(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) {
            String body = StringUtils.appendString(ByteUtils.int2Hex(Integer.parseInt(frequency)), 4, true, "0") +
                    StringUtils.appendString(ByteUtils.int2Hex((sb.length() / 2)), 4, true, "0") +
                    content;
            protocol.setContent(body);
        }
        redisUtils.set(redisKey, JSON.toJSONString(protocol));
    }
}