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

import net.northking.cctp.upperComputer.constants.KeyBoardCodeEnum;
import net.northking.cctp.upperComputer.deviceManager.IOSDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.screen.IosScreenResponseThread;
import net.northking.cctp.upperComputer.deviceManager.thread.IosDeviceInitThread;
import net.northking.cctp.upperComputer.driver.ios.NKAgent;
import net.northking.cctp.upperComputer.driver.ios.command.data.UiNodeData;
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.ProcessCmdUtils;
import net.northking.cctp.upperComputer.utils.SessionUtils;
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 net.northking.cctp.upperComputer.webSocket.function.IosFunctionByAgent;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
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 abstract class AbstractIosMessageHandlerThread extends AbstractMessageHandler {

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

    protected PhoneEntity phoneEntity;

    protected IosFunctionByAgent function;

    protected GetNodeTreeThread nodeTreeThread;

    protected StopWatch handleWatch = new StopWatch();

    protected Float startX;

    protected Float startY;

    protected Float endX;

    protected Float endY;

    protected boolean shiftDown = false;

    protected boolean ctrlDown = false;

    protected boolean altDown = false;

    protected boolean capsDown = false;

    protected String tenantId;

    protected String logPath; //记录日志的临时位置

    protected IosPerfThread iosPerfThread;

    protected IosLogThread iosLogThread;

    protected List<String> capsUpLetters = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

    protected List<String> capsDownLetters = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");

    public AbstractIosMessageHandlerThread(PhoneEntity phoneEntity, Session session) throws ParamMistakeException {
        this.phoneEntity = phoneEntity;
        this.session = session;
        this.serial = phoneEntity.getUdid();
        setName("[" + phoneEntity.getUdid() + "-handleMsg]");
        this.function = new IosFunctionByAgent(phoneEntity.getUdid());
        initDeviceRequireParam();
    }



    @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 getNodeTreeOnce(CmdRequest request) {
        IosDeviceInitThread iosInitThread = IOSDeviceManager.getInstance().getIosInitThread(phoneEntity.getUdid());
        if (null == iosInitThread || iosInitThread.isInterrupted() || !iosInitThread.isAlive()) {
            logger.debug("设备【{}】掉线了........................", phoneEntity.getUdid());
            SessionUtils.sendFailureMessage(session,request,"设备已经掉线");
        }
        logger.debug("开始获取设备【{}】一次的uiNode......",phoneEntity.getUdid());
        UiNodeData uiNodeData = iosInitThread.getNkAgent().uiTreeNode();
        logger.debug("获取结束，nodeData空：{}", uiNodeData == null);
        SessionUtils.sendSuccessData(session, request, uiNodeData, "获取节点树成功");
    }

    @Override
    public void clearAndCloseDeviceAgentConnection() {
        //通知前端设备现在处于掉线的状态,前端开始转圈
        notifyDeviceOfflineToWeb();
    }

    @Override
    public void reConnectDeviceAgent() {
        notifyDeviceOnlineToWeb();
        //发送前端重连成功消息的标志
        IosScreenResponseThread screenResponseThread = IOSDeviceManager.getInstance().getScreenThread(phoneEntity.getUdid());
        if (null != screenResponseThread) {
            screenResponseThread.setSendDeviceStatus(true);  //发送连接成功消息
        }
    }


    @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 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;
    }

    /**
     * 设置摁下的是否是shift,ctrl,alt
     *
     * @param key
     * @param down 摁下为true，抬起为false
     */
    protected void setKeyCodeStatus(String key, boolean down) {
        if (key.equals(KeyBoardCodeEnum.KEYCODE_SHIFT_LEFT.getWebValue())) {
            shiftDown = down;
        } else if (key.equals(KeyBoardCodeEnum.KEYCODE_ALT_LEFT.getWebValue())) {
            altDown = down;
        } else if (key.equals(KeyBoardCodeEnum.KEYCODE_CTRL_LEFT.getWebValue())) {
            ctrlDown = down;
        } else if (capsUpLetters.contains(key)) {  //包含大写字母
            if (shiftDown) {  //如果是按了shift
                logger.debug("没摁大写锁定");
                capsDown = false;
            } else {
                logger.debug("摁了大写锁定");
                capsDown = true;
            }
        } else if (capsDownLetters.contains(key)) {  //小写字母
            if (shiftDown) {  //如果按了shift
                logger.debug("没摁大写锁定");
                capsDown = true;
            } else {
                logger.debug("摁了大写锁定");
                capsDown = false;
            }
        } else if (key.equals(KeyBoardCodeEnum.KEYCODE_CAPS_LOCK.getWebValue())) {
            logger.debug("摁大写锁定。。。。。。。。。。");
            capsDown = !capsDown;
        }
    }

    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 clipboardCopy(CmdRequest request) {

    }

    @Override
    public void clipboardPast(CmdRequest request) {

    }


    @Override
    public void inputType(CmdRequest request) {

    }


    @Override
    public void touchMove(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);
        if (!handleWatch.isStarted()) {
            handleWatch.reset();
            handleWatch.start();
        }
        endX = point.getX();
        endY = point.getY();
        logger.debug("滑动实际位置x:{},y:{}", point.getX(), point.getY());
        SessionUtils.sendSuccessData(session, request, null, "滑动成功");
    }

    private void initDeviceRequireParam() throws ParamMistakeException {
        logger.info("获取手机【{}】的实际宽高............................", phoneEntity.getUdid());
        catchParam.setRealWidth(phoneEntity.getScreenWidth() * phoneEntity.getScale());
        catchParam.setRealHeight(phoneEntity.getScreenHeight() * phoneEntity.getScale());
        catchParam.setScale(phoneEntity.getScale());
        logger.info("手机【{}】的实际宽:{}高:{}............................", phoneEntity.getUdid(), catchParam.getRealWidth(), catchParam.getRealHeight());
    }

    @Override
    public void touchDown(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("开始计时。。。。。。。。");
        if (handleWatch.isStarted()) {
            handleWatch.reset();
        }
        handleWatch.start();
        startX = point.getX();
        startY = point.getY();
        logger.debug("摁下实际位置x:{},y:{}", point.getX(), point.getY());
        SessionUtils.sendSuccessData(session, request, null, "摁下成功");
    }

    protected Point calculatePoint(Map<String, Object> data) {
        Double x = Double.parseDouble(data.get("x") + "");
        Double y = Double.parseDouble(data.get("y") + "");
        Double realX = x.doubleValue() / catchParam.getWidth() * catchParam.getRealWidth();
        Double realY = y.doubleValue() / catchParam.getHeight() * catchParam.getRealHeight();
        realX = realX / catchParam.getScale();
        realY = realY / catchParam.getScale();
        return new Point(realX.floatValue(), realY.floatValue());
    }


    @Override
    public void changeScreenQuality(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck quality = ParamCheck.build().name("quality").type("int").withMin(0).withMax(100);
        ParamCheck frameRate = ParamCheck.build().name("framerate").type("int").withMin(0).withMax(100);
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, quality, frameRate);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        int qualityUse = (int) params.get("quality");
        catchParam.setQuality(qualityUse);
        int frameRateUse = (int) params.get("framerate");
        catchParam.setFrameRate(frameRateUse);
        logger.debug("改变屏幕质量=====>width：{} height:{} quality:{} frameRate:{}", catchParam.getWidth(), catchParam.getHeight(), qualityUse, frameRateUse);
        IosScreenResponseThread screenResponseThread = IOSDeviceManager.getInstance().getScreenThread(phoneEntity.getUdid());
        screenResponseThread.changeQuality(qualityUse / 100f,frameRateUse);
    }

    @Override
    public void changeScreenSize(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck width = ParamCheck.build().name("width").type("int").withMin(0).withMax(catchParam.getRealWidth());
        ParamCheck height = ParamCheck.build().name("height").type("int").withMin(0).withMax(catchParam.getRealHeight());
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, width, height);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        int widthUse = (int) params.get("width");
        catchParam.setWidth(widthUse);
        int heightUse = (int) params.get("height");
        catchParam.setHeight(heightUse);
        logger.debug("改变宽高屏幕=====>width：{} height:{} quality:{} frameRate:{}", widthUse, heightUse, catchParam.getQuality(), catchParam.getFrameRate());
        IosScreenResponseThread screenResponseThread = IOSDeviceManager.getInstance().getScreenThread(phoneEntity.getUdid());
        screenResponseThread.changeSize(widthUse, heightUse);
    }

    @Override
    public void handleScreenOn(CmdRequest request) {
        Map<String, Object> data = request.getData();
        ParamCheck width = ParamCheck.build().name("width").type("int").withMin(0).withMax(catchParam.getRealWidth());
        ParamCheck height = ParamCheck.build().name("height").type("int").withMin(0).withMax(catchParam.getRealHeight());
        ParamCheck quality = ParamCheck.build().name("quality").type("int").withMin(0).withMax(100);
        ParamCheck framerate = ParamCheck.build().name("framerate").type("int").withMin(0).withMax(100);
        ParamCheck rotation = ParamCheck.build().name("rotation").type("int").rangeSelection().withIntValue(Arrays.asList(0, 1, 2, 3));
        Map<String, Object> params = null;
        try {
            params = checkParam(data, false, width, height, quality, framerate, rotation);
//            params = checkParam(data, false, width, height, quality, framerate);
        } catch (Exception e) {
            logger.error("参数校验失败！", e);
            if (e instanceof ParamMistakeException) {
                SessionUtils.sendFailureMessage(session, request, e.getMessage());
                return;
            }
        }
        int widthUse = (int) params.get("width");
        catchParam.setWidth(widthUse);
        int heightUse = (int) params.get("height");
        catchParam.setHeight(heightUse);
        int qualityUse = (int) params.get("quality");
        catchParam.setQuality(qualityUse);
        int frameRateUse = (int) params.get("framerate");
        catchParam.setFrameRate(frameRateUse);
        int rotationUse = (int) params.get("rotation");
        catchParam.setRotation(rotationUse);
        logger.debug("开启屏幕=====>width：{} height:{} quality:{} frameRate:{},rotation:{}", widthUse, heightUse, qualityUse, frameRateUse, rotationUse);
        IosScreenResponseThread screenResponseThread = IOSDeviceManager.getInstance().getScreenThread(phoneEntity.getUdid());
        if (null == screenResponseThread || screenResponseThread.isInterrupted() || !screenResponseThread.isAlive()) {
            //读取手机端响应线程
            screenResponseThread = new IosScreenResponseThread(phoneEntity);
            screenResponseThread.start();
            screenResponseThread.startSendScreenToWeb(session, catchParam);
            screenResponseThread.setScreenOnRequest(session,request);
            IOSDeviceManager.getInstance().saveDeviceScreenThread(phoneEntity.getUdid(), screenResponseThread);
        } else {
            screenResponseThread.startSendScreenToWeb(session, catchParam);
            screenResponseThread.setScreenOnRequest(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();
    }
}
