package tech.glinfo.enbao.modules.upgrade.service;

import com.alibaba.fastjson.JSON;
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.stereotype.Service;
import tech.glinfo.enbao.common.utils.ByteUtils;
import tech.glinfo.enbao.common.utils.Constant;
import tech.glinfo.enbao.common.utils.RedisUtils;
import tech.glinfo.enbao.modules.mq.MqProducer;
import tech.glinfo.enbao.modules.upgrade.utils.UpgradeUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@Service
public class UpgradeService {

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

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MqProducer mqProducer;

    @Value("${upload.path}")
    private String uploadFolder;

    private static final int SKIP_LENGTH = 12288;

    /**
     * 接收设备反馈和处理
     */
    public void defeedback(String message) {
        Map<String, String> datas = (Map<String, String>) JSON.parse(message);
        //指令
        String cmd = datas.get("cmd");
        String content = datas.get("content");//内容
        if (cmd != null && content != null && "00".equals(content)) {
            String deviceNo = datas.get("receiveId");
            //把设备类型
            String type = redisUtils.get(Constant.UPGRADE_REDIS_KEY + deviceNo + ":type");
            //进入升级模式
            if (cmd.equals("F0")) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //发送升级文件信息
                byte[] bytes = null;
                try {
                    //TODO 文件名称应该从数据库里面读取
                    bytes = UpgradeUtils.InputStream2ByteArray(uploadFolder + File.separator + "Air_purifier_APP_V1.01_20200226.bin");
                } catch (IOException e) {
                    logger.error("读取升级文件出错了:{}", e.getMessage());
                    return;
                }

                int length = bytes.length - SKIP_LENGTH;
//                System.out.println("length:" + length);
                byte[] nbytes = new byte[length];
                System.arraycopy(bytes, SKIP_LENGTH, nbytes, 0, length);
                String hexString = ByteUtils.bytes2HexString(nbytes);
//                System.out.println(hexString);
                //放入缓存
                redisUtils.set(Constant.UPGRADE_REDIS_KEY + deviceNo + ":content", hexString);
                mqProducer.sendUpgrade(UpgradeUtils.sendF1(nbytes, deviceNo, type));
            } else if (cmd.equals("F1") || cmd.equals("F2")) {//开始发送文件数据
                String gb = redisUtils.get(Constant.UPGRADE_REDIS_KEY + deviceNo + ":content");
                byte[] bytes = ByteUtils.hexStrToBinaryStr(gb);
                Integer no = redisUtils.get(Constant.UPGRADE_REDIS_KEY + deviceNo + ":no", Integer.class);
                if (no == null) {
                    no = 1;
                }
                int length = bytes.length;
                if((no-1) * Constant.UPGRADE_DATA_LENGTH > length) {//已经发完了
                    mqProducer.sendUpgrade(UpgradeUtils.sendF3(deviceNo, type));
                } else {
                    mqProducer.sendUpgrade(UpgradeUtils.sendF2(bytes, length, no, deviceNo, type));

                    redisUtils.set(Constant.UPGRADE_REDIS_KEY + deviceNo + ":no", no++);
                }
            } else if (cmd.equals("F3")) {
                //升级完成，删除缓存
                redisUtils.delete(Constant.UPGRADE_REDIS_KEY + deviceNo + ":status",
                        Constant.UPGRADE_REDIS_KEY + deviceNo + ":type",
                        Constant.UPGRADE_REDIS_KEY + deviceNo + ":no",
                        Constant.UPGRADE_REDIS_KEY + deviceNo + ":content");
            }
        }
    }
}
