package net.northking.cctp.upperComputer.webSocket.thread;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.upperComputer.constants.IosInputKeyBoardEnum;
import net.northking.cctp.upperComputer.constants.KeyBoardCodeEnum;
import net.northking.cctp.upperComputer.deviceManager.IOSDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import net.northking.cctp.upperComputer.deviceManager.common.PyMobileDevice;
import net.northking.cctp.upperComputer.deviceManager.thread.IosDeviceInitThread;
import net.northking.cctp.upperComputer.driver.ios.NKAgent;
import net.northking.cctp.upperComputer.entity.Attachment;
import net.northking.cctp.upperComputer.entity.PhoneEntity;
import net.northking.cctp.upperComputer.exception.ExecuteException;
import net.northking.cctp.upperComputer.exception.ParamMistakeException;
import net.northking.cctp.upperComputer.utils.HttpUtils;
import net.northking.cctp.upperComputer.utils.ProcessCmdUtils;
import net.northking.cctp.upperComputer.utils.SessionUtils;
import net.northking.cctp.upperComputer.utils.SpringUtils;
import net.northking.cctp.upperComputer.webSocket.entity.CmdRequest;
import net.northking.cctp.upperComputer.webSocket.entity.ParamCheck;
import net.northking.cctp.upperComputer.webSocket.entity.Point;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class IosMacMessageHandlerThread extends AbstractIosMessageHandlerThread {

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


    public IosMacMessageHandlerThread(PhoneEntity phoneEntity, Session session) throws ParamMistakeException {
        super(phoneEntity, session);
    }



    @Override
    public void closeADBDebug(CmdRequest request) {
    }


    @Override
    public void openADBDebug(CmdRequest request) {
    }


    @Override
    public void pullFileFromDevice(CmdRequest request) {
//        boolean pull = AndroidDeviceManager.getInstance().getAdb().pull(adbDevice, outputStream, "/scard/xxxx.apk");
    }


    @Override
    public void pushFileToDevice(CmdRequest request) {
    }


    @Override
    public void getFileList(CmdRequest request) {
    }


    @Override
    public void downloadLogcat(CmdRequest request) {
    }

    @Override
    public void startUiNode(CmdRequest request) {
        if (null == nodeTreeThread || nodeTreeThread.isInterrupted() || !nodeTreeThread.isAlive()) {
            try {
                IosDeviceInitThread iosInitThread = IOSDeviceManager.getInstance().getIosInitThread(phoneEntity.getUdid());
                if (null == iosInitThread || iosInitThread.isInterrupted() || !iosInitThread.isAlive()) {
                    SessionUtils.sendFailureMessage(session, request, "设备还未准备就绪，请稍后再试");
                    return;
                }
                NKAgent nkAgent = iosInitThread.getNkAgent();
                if (null == nkAgent) {
                    SessionUtils.sendFailureMessage(session, request, "设备还未准备就绪，请稍后再试");
                    return;
                }
                nodeTreeThread = new GetNodeTreeThread(session,phoneEntity.getUdid(),request);
            } catch (Exception e) {
                if (e instanceof ExecuteException) {
                    SessionUtils.sendFailureMessage(session, request, e.getMessage());
                } else {
                    SessionUtils.sendFailureMessage(session, request, "获取设备节点失败");
                }
                return;
            }
            nodeTreeThread.start();
        } else {
            nodeTreeThread.startGetNodeTree(request);
        }
    }

    @Override
    public void stopUiNode(CmdRequest request) {
        if (null != nodeTreeThread) {
            nodeTreeThread.stopGetNodeTree(request);
            return;
        }
        SessionUtils.sendSuccessData(session, request, null,"该设备尚未开启获取节点树");
    }



    @Override
    public void stopLogcat(CmdRequest request) {
        Map<String, Object> data = request.getData();
        if (iosLogThread != null && iosLogThread.isAlive()) {
            ParamCheck tenantIdCheck = ParamCheck.build().name("tenantId").type("string").length(32);
            Map<String, Object> params = null;
            try {
                params = checkParam(data, false, tenantIdCheck);
            } catch (Exception e) {
                logger.error("参数校验失败！", e);
                if (e instanceof ParamMistakeException) {
                    SessionUtils.sendFailureMessage(session, request, e.getMessage());
                    return;
                }
            }
            //若无值则记录临时日志文件地址
            tenantId = (String) params.get("tenantId");
            logPath = StringUtils.isBlank(logPath) ? iosLogThread.getLogFilePath() : logPath;
            String logFilePath = iosLogThread.stopLog(tenantId);
            if (logFilePath != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("filePath", logFilePath);
                SessionUtils.sendSuccessData(session, request, result, "结束日志成功");
            } else {
                SessionUtils.sendFailureMessage(session, request, "上传日志失败");
            }
        } else {
            SessionUtils.sendFailureMessage(session, request, "未找到开启日志信息");
        }
    }

    @Override
    public void startLogcat(CmdRequest request) {
        if (null != iosLogThread && iosLogThread.isAlive()) {
            //拿上一次日志的临时文件位置
            logPath = StringUtils.isBlank(logPath) ? iosLogThread.getLogFilePath() : logPath;
            iosLogThread.killLog();
        }
        iosLogThread = new IosLogThread(serial, session, request, logPath);
        iosLogThread.start();
        SessionUtils.sendContinuousData(session, request, null, "开启日志成功");
    }

    @Override
    public void startPerf(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck packageNameCheck = ParamCheck.build().name("packageName").type("string").length(Integer.MAX_VALUE);
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, packageNameCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        String packageName = (String) data.get("packageName");
        if (null != iosPerfThread && iosPerfThread.isAlive()) {
            iosPerfThread.stopThread();
            logger.debug("成功关闭原有性能线程");
        }
        iosPerfThread = new IosPerfThread(session, request);
        iosPerfThread.initData(serial, packageName);
        iosPerfThread.start();
        SessionUtils.sendContinuousData(session, request, null, "开启性能数据成功");
    }

    @Override
    public void stopPerf(CmdRequest request) {
        if (iosPerfThread != null && iosPerfThread.isAlive()) {
            logger.debug("关闭" + serial + "设备ios性能线程");
            try {
                iosPerfThread.stopThread();
                iosPerfThread.interrupt();
                iosPerfThread = null;
                SessionUtils.sendSuccessData(session, request, null, "停止性能数据成功");
            } catch (Exception e) {
                logger.error("关闭性能线程异常", e);
                SessionUtils.sendFailureMessage(session, request, "停止性能数据异常");
            }
        } else {
            logger.warn("性能线程未开启，设备id：{}", serial);
        }
    }

    @Override
    public void sendShellToDevice(CmdRequest request) {

    }

    @Override
    public void uninstallApp(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck packageNameCheck = ParamCheck.build().name("packageName").type("string").length(Integer.MAX_VALUE);
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, packageNameCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        String packageName = (String) params.get("packageName");
        String[] cmds = {"tidevice", "-u", phoneEntity.getUdid(), "uninstall", packageName};
        ProcessBuilder builder = new ProcessBuilder(Arrays.asList(cmds)).redirectErrorStream(true);
        try {
            Process process = builder.start();
            String line = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));
            StringBuilder stringBuilder = new StringBuilder();
            while (null != (line = in.readLine())) {
                logger.debug("卸载applist结果：{}", line);
                stringBuilder.append(line);
            }
            String result = stringBuilder.toString();
            if (result.endsWith("Complete")) {
                SessionUtils.sendSuccessData(session, request, null, "应用卸载成功");
            }
        } catch (IOException e) {
            logger.error("卸载应用[{}]失败", packageName, e);
            SessionUtils.sendFailureMessage(session, request, "卸载应用失败");
        }
    }

    @Override
    public void getAppList(CmdRequest request) {
        Map<String, Object> result = new HashMap<>();
        String[] cmds = {"tidevice", "-u", phoneEntity.getUdid(), "applist"};
        ProcessBuilder builder = new ProcessBuilder(Arrays.asList(cmds)).redirectErrorStream(true);
        try {
            Process process = builder.start();
            String line = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            List<Map<String, String>> appList = new ArrayList<>();
            while (null != (line = in.readLine())) {
                logger.debug("安装applist结果：{}", line);
                if (StringUtils.isNotBlank(line)) {
                    String[] split = line.split(" ");
                    Map<String, String> appMap = new HashMap<>();
                    appMap.put("value", split[0]);
                    appMap.put("label", split[1]);
                    appList.add(appMap);
                }
            }
            result.put("result", appList);
        } catch (IOException e) {
            logger.error("获取appList失败", e);
            SessionUtils.sendFailureMessage(session, request, "应用列表获取失败");
            return;
        }
        SessionUtils.sendSuccessData(session, request, result, "应用列表获取成功");
    }

    @Override
    public void inputKeyUp(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck keyCodeCheck = ParamCheck.build().name("key").type("string");
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, keyCodeCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        String key = (String) params.get("key");
        logger.debug("抬起键key：{}", key);
        if (IosInputKeyBoardEnum.containsKey(key)) {
            if (key.equalsIgnoreCase(IosInputKeyBoardEnum.BACKSPACE.getKeyCode())) {
                function.deleteOneKey();
            } else {
                function.inputText(key,false);
            }
        }
        SessionUtils.sendSuccessData(session, request, null, "抬起键[" + key + "]处理成功");
    }

    @Override
    public void inputKeyDown(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck keyCodeCheck = ParamCheck.build().name("key").type("string");
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, keyCodeCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        String key = (String) params.get("key");
        logger.debug("摁下键key：{}", key);
        setKeyCodeStatus(key, true);
        int code = KeyBoardCodeEnum.getCode(key, !shiftDown);
        logger.debug("转换后的code:{}", code);
        if (code < 0) {
            SessionUtils.sendFailureMessage(session, request, "键[" + key + "]不存在");
            return;
        }
//        int metaState = getMetaState();
//        KeyEventCommand command = new KeyEventCommand(KeyEventCommand.Action.DOWN, code);
//        if (metaState > 0) {
//            logger.debug("打开meta键：{}", metaState);
//            command.setMetaState(metaState);
//        }
//        asyncAgentSession.send(command);
        SessionUtils.sendSuccessData(session, request, null, "摁下键[" + key + "]处理成功");
    }

    private int getMetaState() {
        int meta = 0;
        if (shiftDown) {
            meta += 1;
        }
        if (altDown) {
            meta += 2;
        }
        if (ctrlDown) {
            meta += 4096;
        }
        if (capsDown) {
            meta += 1048576;
        }
        return meta;
    }

    @Override
    public void installApp(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck textCheck = ParamCheck.build().name("appUrl").type("string").length(Integer.MAX_VALUE);
        ParamCheck packageCheck = ParamCheck.build().name("packageName").type("string").length(Integer.MAX_VALUE);
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, textCheck, packageCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        String appUrl = (String) params.get("appUrl");
        String packageName = (String) params.get("packageName");
        logger.debug("appUrl:{},packageName:{}", appUrl, packageName);
        try {
            downloadAppToLocalAndInstall(appUrl, request, packageName);
        } catch (IOException e) {
            logger.error("应用安装失败", e);
            SessionUtils.sendFailureMessage(session, request, "应用安装失败");
            return;
        }

    }

    private void downloadAppToLocalAndInstall(String appUrl, CmdRequest request, String packageName) throws IOException {
        File fileDir = new File(UpperComputerManager.getInstance().getApplicationPath() + "/tempApp/");
        File appFile = new File(UpperComputerManager.getInstance().getApplicationPath() + "/tempApp/" + appUrl);
        if (!fileDir.exists()) {   //文件夹不存在
            fileDir.mkdirs();
        }
//        if (!appFile.exists()) {  //文件不存在
        String serverIp = SpringUtils.getProperties("nk.mobile-computer.serverAddr");
        String appDownloadPath = SpringUtils.getProperties("nk.mobile-computer.publicDownloadFile");
        appDownloadPath = appDownloadPath.replace("{appUrl}", appUrl);
        HttpUtils.downloadFileToLocal(serverIp + appDownloadPath, fileDir.getAbsolutePath(), appUrl);
//        }
        Long totalSpace = appFile.length();
        logger.info("应用总大小：{}", totalSpace);
        String[] cmds = new String[]{"tidevice", "-u", phoneEntity.getUdid(), "install", appFile.getAbsolutePath()};
        ProcessBuilder builder = new ProcessBuilder(Arrays.asList(cmds)).redirectErrorStream(true);
        Process process = builder.start();
        String line = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        Map<String, Object> result = new HashMap<>();
        boolean finished = false;
        while (null != (line = in.readLine())) {
            logger.debug("安装app【{}】结果：{}", appFile.getAbsolutePath(), line);
            //增加新解析方式 非json返回
            if (!line.startsWith("{")) {
                if (line.startsWith("-")) {
                    String valStr = line.substring(line.indexOf("(") + 1, line.indexOf("%"));
                    if (StringUtils.isNotBlank(valStr)) {
                        result.put("percent", Integer.parseInt(valStr));
                        SessionUtils.sendContinuousData(session, request, result, "应用安装进度");
                    }
                } else if (line.trim().equals("Complete")) {
                    result.put("percent", 100);
                    SessionUtils.sendContinuousData(session, request, result, "应用安装进度");
                    finished = true;
                }
                continue;
            }
            JSONObject value = null;
            try {
                value = JSONObject.parseObject(line, JSONObject.class);
            } catch (Exception e) {
                SessionUtils.sendFailureMessage(session, request, "应用安装失败");
                return;
            }
            int action = value.getIntValue("action");
            int percent = 0;
            int sendPercent = 0;
            if (action == 1) {  //传输
                percent = value.getIntValue("percent");
                if (percent % 2 == 0) {
                    sendPercent = percent / 2;
                    result.put("percent", sendPercent);
                    SessionUtils.sendContinuousData(session, request, result, "应用安装进度");
                }
            } else if (action == 2) {
                if (sendPercent != 50) {
                    sendPercent = 50;
                    result.put("percent", 50);
                    SessionUtils.sendContinuousData(session, request, result, "应用安装进度");
                }
            } else if (action == 3) {  //安装
                percent = value.getIntValue("percent");
                if (percent % 2 == 0) {
                    sendPercent += percent / 2;
                    result.put("percent", sendPercent);
                    SessionUtils.sendContinuousData(session, request, result, "应用安装进度");
                }
            } else if (action == 4) {
                if (sendPercent != 100) {
                    result.put("percent", 100);
                    SessionUtils.sendContinuousData(session, request, result, "应用安装进度");
                    finished = true;
                }
            }
        }
        if (finished) {
            SessionUtils.sendSuccessData(session, request, null, "应用安装完成");
            startApp(serial, packageName);
        } else {
            SessionUtils.sendFailureMessage(session, request, "应用安装失败");
        }
        //删除临时文件
        if (null != appFile && appFile.exists()) {
            appFile.delete();
        }
    }

    private void startApp(String serial, String PackageName) {
        Process proc = null;
        try {
            List<String> cmdList1 = new ArrayList<>();
            cmdList1.add("tidevice");
            cmdList1.add("-u");
            cmdList1.add(serial);
            cmdList1.add("launch");
            cmdList1.add(PackageName);
            logger.debug("执行启动应用命令，包名：{}", PackageName);
            proc = ProcessCmdUtils.execCmd(cmdList1);
//            Runtime runtime = Runtime.getRuntime();
//            String pro = "tidevice -u " + serial + " launch " + PackageName;
//            proc = runtime.exec(pro);
//            logger.info(pro);
            if (proc.waitFor() != 0) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void openBrowser(CmdRequest request) {

    }

    @Override
    public void setWifiStatus(CmdRequest request) {

    }

    @Override
    public void openSetting(CmdRequest request) {

    }

    @Override
    public void deviceOpenCamera(CmdRequest request) {

    }

    @Override
    public void restartDevice(CmdRequest request) {

    }

    @Override
    public void rotationScreen(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck textCheck = ParamCheck.build().name("rotation").type("int").rangeSelection().withIntValue(Arrays.asList(0, 1, 2, 3));
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, textCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        int rotation = (int) params.get("rotation");
//        if ((catchParam.getRotation() - rotation) % 2 == 0) {
//            logger.debug("一次翻了180°，不需要交换屏幕的宽高");
//        } else {
//            exchangeWithAndHeight();
//        }
//        catchParam.setRotation(rotation);
        Map<String, Object> param = new HashMap<>();
        param.put("x", 0);
        param.put("y", 0);
        switch (rotation) {
            case 0:
                param.put("z", 0);
                break;
            case 1:
                param.put("z", 90);
                break;
            case 2:
                param.put("z", 180);
                break;
            case 3:
                param.put("z", 270);
                break;
            default:
                SessionUtils.sendFailureMessage(session, request, "屏幕旋转方向参数传递错误");
                return;
        }
//        JSONObject jsonObject = function.rotationScreen(param);
//        logger.debug("旋转屏幕结果：{}", JSONObject.toJSONString(jsonObject));
    }


    @Override
    public void clipboardCopy(CmdRequest request) {

    }

    @Override
    public void clipboardPast(CmdRequest request) {

    }

    @Override
    public void inputSetText(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck textCheck = ParamCheck.build().name("text").type("string").length(Integer.MAX_VALUE);
        ParamCheck clearCheck = ParamCheck.build().name("clear").type("boolean");
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, textCheck, clearCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        String text = (String) params.get("text");
        boolean clear = (boolean) params.get("clear");
        boolean success = function.inputText(text, clear);
        if (success) {
            SessionUtils.sendSuccessData(session, request, null, "设置输入文本成功");
        } else {
            SessionUtils.sendFailureMessage(session, request,  "设置输入文本失败");
        }

    }

    @Override
    public void inputType(CmdRequest request) {

    }

    @Override
    public void inputKeyPress(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck keyCodeCheck = ParamCheck.build().name("key").type("string");
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, keyCodeCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        String key = (String) params.get("key");
        logger.debug("输入热键key：{}", key);
        switch (key) {
            case "home":
                function.pressHome();
                break;
            default:
                SessionUtils.sendFailureMessage(session, request, "热键[" + key + "]不存在");
                return;
        }
        SessionUtils.sendSuccessData(session, request, null, "热键处理成功");
    }

    @Override
    public void touchUp(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck xCheck = ParamCheck.build().name("x").type("double").withMin(0).withMax(catchParam.getWidth());
        ParamCheck yCheck = ParamCheck.build().name("y").type("double").withMin(0).withMax(catchParam.getHeight());
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, xCheck, yCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        Point point = calculatePoint(params);
        logger.debug("计算后操作的坐标：{}", JSON.toJSONString(point));
        if (handleWatch.isStarted()) {
            handleWatch.stop();
            long time = handleWatch.getTime();
            logger.debug("操作时间：{}ms", time);
            endX = point.getX();
            endY = point.getY();
            if (Math.abs(endX - startX) > 10 || Math.abs(endY - startY) > 10) {  //滑动
                function.swipe(startX, startY, endX, endY);
            } else {  //点击
                if (time < 2000) {//点击
                    function.click(startX, startY);
                } else {  //长按
                    function.longPress(startX,startY);
                }
            }
            handleWatch.reset();
        }
        logger.debug("抬起实际位置x:{},y:{}", point.getX(), point.getY());
        SessionUtils.sendSuccessData(session, request, null, "抬起成功");
    }

    @Override
    public void screenShot(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck tenantIdCheck = ParamCheck.build().name("tenantId").type("string").length(32);
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, tenantIdCheck);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        PyMobileDevice.SpecificAppleDeviceInfo specificAppleDeviceInfo = IOSDeviceManager.getInstance().getSpecificAppleDeviceInfo(phoneEntity.getUdid());
        byte[] screenShotData = PyMobileDevice.getInstance().takeScreenshot(specificAppleDeviceInfo, UpperComputerManager.getInstance().getApplicationPath() + "/tempApp/");
        if (null != screenShotData && screenShotData.length > 0) { //截图
            logger.debug("收到手机【{}】截图,大小：{}k", phoneEntity.getUdid(), screenShotData.length / 1024);
            String tenantId = (String) params.get("tenantId");
            //上传文件
            logger.debug("[{}]开始上传截图", phoneEntity.getUdid());
            String serverAddress = SpringUtils.getProperties("nk.mobile-computer.serverAddr");
            String pubUploadPath = SpringUtils.getProperties("nk.mobile-computer.publicUploadAddr");
            Attachment upload = null;
            try {
                upload = HttpUtils.upload(serverAddress + pubUploadPath, screenShotData, tenantId);
            } catch (Exception e) {
                logger.debug("[{}]上传截图失败", phoneEntity.getUdid(), e);
            }
            if (null != upload && StringUtils.isNotBlank(upload.getId())) {
                logger.debug("文件上传成功，返回id：{}", upload.getId());
                Map<String, Object> result = new HashMap<>();
                result.put("urlPath", upload.getUrlPath());
                result.put("id", upload.getId());
                SessionUtils.sendSuccessData(session, request, result, "截图成功");
            } else {
                SessionUtils.sendFailureMessage(session, request, "上传截图失败");
            }
        } else {
            SessionUtils.sendFailureMessage(session, request, "未读到截图数据");
        }


    }


    @Override
    public void stopAndExit() {
        IOSDeviceManager.getInstance().stopWebScreen(phoneEntity.getUdid(),session);
        if (null != iosPerfThread) {
            iosPerfThread.stopThread();
        }
        if (null != iosLogThread) {
            if (tenantId == null) {
                iosLogThread.killLog();
            } else {
                iosLogThread.stopLog(tenantId);
            }
        }
        if (null != nodeTreeThread) {
            nodeTreeThread.exitGetNodeTree();
        }
        if (StringUtils.isNotBlank(logPath)) {
            File logFile = new File(logPath);
            if (null != logFile && logFile.exists()) {
                logFile.delete();
                logger.debug("ios临时日志文件已删除");
            }
        }
        cmdQueues.clear();
        interrupt();
    }
}
