package net.northking.cctp.element.mobile.ios.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.element.core.DeviceDriver;
import net.northking.cctp.element.core.IExecuteContext;
import net.northking.cctp.element.core.IStepTarget;
import net.northking.cctp.element.core.exception.ExecuteException;
import net.northking.cctp.element.core.exception.ParamMistakeException;
import net.northking.cctp.element.mobile.ios.constants.CommandId;
import net.northking.cctp.element.mobile.ios.constants.UpperParamKey;
import net.northking.cctp.element.mobile.ios.constants.UsingType;
import net.northking.cctp.element.mobile.ios.entity.ElementHandleParam;
import net.northking.cctp.element.mobile.ios.entity.PointMessage;
import net.northking.cctp.mobile.driver.constans.AutomationRequestCmd;
import net.northking.cctp.mobile.driver.driver.MobileDriver;
import net.northking.cctp.mobile.driver.entity.CmdAutomationRequest;
import net.northking.cctp.mobile.driver.entity.CmdAutomationResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class AutomationHandleUtil {

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

    /**
     * 是否存在元素
     *
     * @param param
     * @return
     */
    public static boolean ifElement(ElementHandleParam param) throws Exception{
        PointMessage point = findElementByTargets(param.getDeviceDriver(), param.getTargets(), param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
        if (point == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 点击元素
     *
     * @param param
     * @return
     */
    public static boolean clickElement(ElementHandleParam param) throws Exception{
        return clickElementByTargets(param.getDeviceDriver(), param.getTargets(), param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
    }

    private static boolean clickElementByTargets(DeviceDriver deviceDriver, List<IStepTarget> targets, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        boolean success = false;
        for (IStepTarget target : targets) {
            if (UsingType.SELECTOR.equals(target.getUsing())) {
                success = nodeTreeHandleElement(deviceDriver, target, waitTimeout, swipe, swipeCount, CommandId.NODE_CLICK);
                if (success) {
                    return success;
                }
            } else if (UsingType.OCR.equals(target.getUsing())) {
                success = ocrHandleElement(deviceDriver, target, waitTimeout, swipe, swipeCount, CommandId.POINT_CLICK);
                if (success) {
                    return success;
                }
            } else if (UsingType.HZOCR.equals(target.getUsing())) {
                success = hzOcrHandleElement(deviceDriver, target, waitTimeout, swipe, swipeCount, CommandId.POINT_CLICK);
                if (success) {
                    return success;
                }
            } else if (UsingType.POINT.equals(target.getUsing())) {
                success = pointHandleElement(deviceDriver, target, waitTimeout, CommandId.POINT_CLICK);
                if (success) {
                    return success;
                }
            } else if (UsingType.IMAGE.equals(target.getUsing())) {
                success = imageHandleElement(deviceDriver, target, waitTimeout, swipe, swipeCount, CommandId.POINT_CLICK);
                if (success) {
                    return success;
                }
            } else {
                logger.warn("不支持的查找元素方式：{}", target.getUsing());
            }
        }
        throw new ExecuteException("未查找到控件");
    }

    private static boolean imageHandleElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount, CommandId command) throws Exception {
        Boolean success = false;
        Map<String, Object> paramMap = getImageParam(target.getValue(), swipe, swipeCount);
        if (null == paramMap) {
            return false;
        }
        paramMap.put(UpperParamKey.COMMAND_ID, command.getCode());
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.HANDLE_ELEMENT_BY_IMAGE, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据image操作的结果：{}", o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }

    private static Map<String, Object> getImageParam(String param, String swipe, Integer swipeCount) {
        JSONObject value = JSON.parseObject(param, JSONObject.class);
        String imageUrl = value.getString("imgUri");
        if (StringUtils.isBlank(imageUrl)) {
            logger.warn("图片地址为空..............");
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.IMG_URL, imageUrl);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        return paramMap;
    }

    private static boolean pointHandleElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, CommandId command) throws Exception{
        Boolean success = false;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = getPointParam(target.getValue());
        if (null == paramMap) {
            return false;
        }
        paramMap.put(UpperParamKey.COMMAND_ID, command.getCode());
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.HANDLE_ELEMENT_BY_POINT, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据point点击的结果：{}", o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;

    }

    private static Map<String, Object> getPointParam(String param) {
        JSONObject value = JSON.parseObject(param, JSONObject.class);
        Integer x = null;
        Integer y = null;
        Integer screenWidth = null;
        Integer screenHeight = null;
        try {
            x = value.getInteger("pointX");
            y = value.getInteger("pointY");
            screenWidth = value.getInteger("screenWidth");
            screenHeight = value.getInteger("screenHeight");
        } catch (Exception e) {
            logger.error("坐标参数不对", e);
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.X, x);
        paramMap.put(UpperParamKey.Y, y);
        paramMap.put(UpperParamKey.SCREEN_WIDTH, screenWidth);
        paramMap.put(UpperParamKey.SCREEN_HEIGHT, screenHeight);
        return paramMap;
    }

    private static boolean ocrHandleElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount, CommandId command) throws Exception{
        Boolean success = false;
        Map<String, Object> paramMap = getOcrParam(target.getValue(), swipe, swipeCount);
        if (null == paramMap) {
            return false;
        }
        paramMap.put(UpperParamKey.COMMAND_ID, command.getCode());
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.HANDLE_ELEMENT_BY_OCR, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据ocr点击的结果：{}", o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }

    private static boolean hzOcrHandleElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount, CommandId command) throws Exception{
        Boolean success = false;
        Map<String, Object> paramMap = getOcrParam(target.getValue(), swipe, swipeCount);
        if (null == paramMap) {
            return false;
        }
        paramMap.put(UpperParamKey.USING_TYPE, target.getUsing());
        paramMap.put(UpperParamKey.COMMAND_ID, command.getCode());
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.HANDLE_ELEMENT_BY_OCR, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据ocr点击的结果：{}", o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }

    private static Map<String, Object> getOcrParam(String param, String swipe, Integer swipeCount) {
        JSONObject value = JSON.parseObject(param, JSONObject.class);
        Integer x = null;
        Integer y = null;
        Integer screenWidth = null;
        Integer screenHeight = null;
        Integer width = null;
        Integer height = null;
        try {
            x = value.getInteger("x");
            y = value.getInteger("y");
            screenWidth = value.getInteger("screenWidth");
            screenHeight = value.getInteger("screenHeight");
            width = value.getInteger("width");
            height = value.getInteger("height");
        } catch (Exception e) {
            logger.error("坐标参数不对", e);
            return null;
        }
        String ocrText = value.getString("ocrText");
        if (StringUtils.isBlank(ocrText)) {
            logger.warn("查找的文本为空................");
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.WIDTH, width);
        paramMap.put(UpperParamKey.HEIGHT, height);
        paramMap.put(UpperParamKey.X, x);
        paramMap.put(UpperParamKey.Y, y);
        paramMap.put(UpperParamKey.SCREEN_WIDTH, screenWidth);
        paramMap.put(UpperParamKey.SCREEN_HEIGHT, screenHeight);
        paramMap.put(UpperParamKey.OCR_TEXT, ocrText);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        paramMap.put(UpperParamKey.INDEX, value.get("index"));
        return paramMap;
    }

    private static Map<String, Object> getClickTextOcrParam(String swipe, Integer swipeCount, String text, Integer index) {
        if (StringUtils.isBlank(text)) {
            logger.warn("查找的文本为空................");
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.OCR_TEXT, text);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        paramMap.put(UpperParamKey.INDEX, index);
        return paramMap;
    }

    /**
     * 根据node节点操作元素
     *
     * @param deviceDriver
     * @param target
     * @param waitTimeout
     * @param swipe
     * @param swipeCount
     * @param command
     * @return
     */
    private static boolean nodeTreeHandleElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount, CommandId command) throws Exception{
        Boolean success = false;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        JSONObject object = JSON.parseObject(target.getValue(), JSONObject.class);
        String xpath = object.getString(UsingType.Key.SELECTOR_KEY);
        logger.info("拿到的nodeTree:{}", xpath);
        paramMap.put(UpperParamKey.NODE_TREE, xpath);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        paramMap.put(UpperParamKey.COMMAND_ID, command.getCode());
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.HANDLE_ELEMENT_BY_NODE, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据nodeTree操作元素的结果：{}", o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }

    private static boolean clickElementByTargets(DeviceDriver deviceDriver, PointMessage point, Integer waitTimeout) throws Exception{
        Boolean success = false;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.POINT, point);
        CmdAutomationRequest request = CmdAutomationRequest.builder(AutomationRequestCmd.CLICK_POINT, token, paramMap);
        Object result = sendUpperMessageAndWaitReturn(deviceDriver, request, token, waitTimeout);
        logger.debug("根据坐标点击的结果：{}", result);
        if (null != request) {
            success = JSONObject.parseObject(JSONObject.toJSONString(result), Boolean.class);
        } else {
            throw new ExecuteException("点击元素失败");
        }
        return success;
    }

    private static Object sendUpperMessageAndWaitReturn(DeviceDriver deviceDriver, CmdAutomationRequest request, String token, Integer waitTimeout) throws Exception {
        MobileDriver mobileDriver = (MobileDriver) deviceDriver;
        logger.warn("发送token:{}的消息..........................", token);
        request.getData().put(UpperParamKey.WAIT_TIMEOUT, waitTimeout);
        mobileDriver.send(JSON.toJSONString(request));
        mobileDriver.getSocketClient().semaphore = new Semaphore(0);
        if (mobileDriver.getSocketClient().semaphore.tryAcquire(waitTimeout, TimeUnit.SECONDS)) {
            CmdAutomationResponse response = mobileDriver.getSocketClient().getResponse();
            if (token.equals(response.getStepToken())) {
                logger.warn("收到token:{}的消息..........................", token);
                if (response.isSuccess()) {
                    Object data = response.getData();
                    if (null == data) {
                        logger.debug("未获取到有效数据，原因：{}", response.getMessage());
                    }
                    return data;
                } else {
                    throw new ExecuteException(response.getMessage());
                }
            } else {
                logger.error("收到回来的消息token:{}，发过去的token:{}。对不上，收到的内容：{}", response.getStepToken(), token, JSON.toJSONString(response));
            }
        } else {
            logger.warn("等待token:{},消息返回超时..........................", token);
        }
        return null;
    }

    /**
     * 根据targets里面的内容查询对应的元素
     *
     * @param deviceDriver
     * @param targets
     * @return
     */
    private static PointMessage findElementByTargets(DeviceDriver deviceDriver, List<IStepTarget> targets, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        PointMessage point = null;
        for (IStepTarget target : targets) {
            switch (target.getUsing()) {
                case UsingType.SELECTOR:
                    point = nodeTreeFindElement(deviceDriver, target, waitTimeout, swipe, swipeCount);
                    break;
                case UsingType.OCR:
                    point = ocrFindElement(deviceDriver, target, waitTimeout, swipe, swipeCount);
                    break;
                case UsingType.HZOCR:
                    point = hzOcrFindElement(deviceDriver, target, waitTimeout, swipe, swipeCount);
                    break;
                case UsingType.POINT:
                    point = pointFindElement(deviceDriver, target, waitTimeout);
                    break;
                case UsingType.IMAGE:
                    point = imageFindElement(deviceDriver, target, waitTimeout, swipe, swipeCount);
                    break;
                default:
                    logger.warn("不支持的查找元素方式：{}", target.getUsing());
                    break;
            }
        }
        return point;
    }

    /**
     * 以图找图查找元素的位置
     *
     * @param deviceDriver
     * @param target
     * @param waitTimeout
     * @param swipe
     * @param swipeCount
     * @return
     */
    private static PointMessage imageFindElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        PointMessage point = null;
        Map<String, Object> paramMap = getImageParam(target.getValue(), swipe, swipeCount);
        if (null == paramMap) {
            return null;
        }
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.SEARCH_ELEMENT_BY_IMAGE, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据image查找的结果：{}", o);
        if (null != o) {
            point = JSONObject.parseObject(JSONObject.toJSONString(o), PointMessage.class);
        }
        return point;
    }

    /**
     * 根据ocr查找元素位置
     *
     * @param deviceDriver
     * @param target
     * @param waitTimeout
     * @param swipe
     * @param swipeCount
     * @return
     */
    private static PointMessage ocrFindElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        PointMessage point = null;
        Map<String, Object> paramMap = getOcrParam(target.getValue(), swipe, swipeCount);
        if (null == paramMap) {
            return null;
        }
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.SEARCH_ELEMENT_BY_OCR, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据ocr查找的结果：{}", o);
        if (null != o) {
            point = JSONObject.parseObject(JSONObject.toJSONString(o), PointMessage.class);
        }
        return point;
    }

    /**
     * 根据杭银ocr查找元素位置
     *
     * @param deviceDriver
     * @param target
     * @param waitTimeout
     * @param swipe
     * @param swipeCount
     * @return
     */
    private static PointMessage hzOcrFindElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        PointMessage point = null;
        Map<String, Object> paramMap = getOcrParam(target.getValue(), swipe, swipeCount);
        if (null == paramMap) {
            return null;
        }
        paramMap.put(UpperParamKey.USING_TYPE, target.getUsing());
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.SEARCH_ELEMENT_BY_OCR, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据ocr查找的结果：{}", o);
        if (null != o) {
            point = JSONObject.parseObject(JSONObject.toJSONString(o), PointMessage.class);
        }
        return point;
    }

    /**
     * 通过坐标的方式查找元素位置
     *
     * @param deviceDriver
     * @param target
     * @param waitTimeout
     * @return
     */
    private static PointMessage pointFindElement(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout) throws Exception{
        PointMessage point = null;
        Map<String, Object> paramMap = getPointParam(target.getValue());
        if (null == paramMap) {
            return null;
        }
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.SEARCH_ELEMENT_BY_POINT, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据point查找的结果：{}", o);
        if (null != o) {
            point = JSONObject.parseObject(JSONObject.toJSONString(o), PointMessage.class);
        }
        return point;
    }

    /**
     * 通过节点的方式查找元素位置
     *
     * @param mobileDriver
     * @param target
     * @param waitTimeout
     * @param swipe
     * @param swipeCount
     * @return
     */
    private static PointMessage nodeTreeFindElement(DeviceDriver mobileDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        PointMessage point = null;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        JSONObject object = JSON.parseObject(target.getValue(), JSONObject.class);
        String xpath = object.getString(UsingType.Key.SELECTOR_KEY);
        logger.info("拿到的xpath:{}", xpath);
        paramMap.put(UpperParamKey.NODE_TREE, xpath);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.SEARCH_ELEMENT_BY_NODE, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(mobileDriver, builder, token, waitTimeout);
        logger.debug("根据nodeTree查找的结果：{}", o);
        if (null != o) {
            point = JSONObject.parseObject(JSONObject.toJSONString(o), PointMessage.class);
        }
        return point;
    }

    /**
     * 标准滑动
     *
     * @param param
     * @return
     */
    public static Boolean standardSwipe(ElementHandleParam param) throws Exception{
        Boolean success = false;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.SWIPE_DIRECTION, param.getSwipeDirection());
        paramMap.put(UpperParamKey.SWIPE_SIZE, param.getSwipeSize());
        paramMap.put(UpperParamKey.COMMAND_ID, CommandId.POINT_SWIPE.getCode());
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.SWIPE, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(param.getDeviceDriver(), builder, token, param.getWaitTimeout());
        logger.debug("标准滑动的结果：{}", o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        } else {
            throw new ExecuteException("滑动超时");
        }
        if (!success) {
            throw new ExecuteException("滑动失败");
        }
        return success;
    }

    /**
     * 控件滑动
     *
     * @param param
     * @return
     */
    public static Boolean elementSwipe(ElementHandleParam param) throws Exception{
        PointMessage point = findElementByTargets(param.getDeviceDriver(), param.getTargets(), param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
        if (point == null) {
            logger.error("查找不到控件");
            throw new ExecuteException("查找不到控件");
        }
        Boolean success = null;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        Integer x = point.getX();
        Integer y = point.getY();
        if (point.isExchange()) {
            x = x / point.getScale();
            y = y / point.getScale();
        }
        paramMap.put(UpperParamKey.X, x);
        paramMap.put(UpperParamKey.Y, y);
        paramMap.put(UpperParamKey.SWIPE_DIRECTION, param.getSwipeDirection());
        paramMap.put(UpperParamKey.SWIPE_SIZE, param.getSwipeSize());
        paramMap.put(UpperParamKey.SEARCH_SWIPE, param.getSwipe());
        paramMap.put(UpperParamKey.SWIPE_COUNT, param.getSwipeCount());
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.SWIPE, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(param.getDeviceDriver(), builder, token, param.getWaitTimeout());
        logger.debug("控件滑动的结果：{}", o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        } else {
            throw new ExecuteException("滑动超时");
        }
        if (!success) {
            throw new ExecuteException("滑动失败");
        }
        return success;

    }

    public static Boolean elementInput(ElementHandleParam param) throws Exception{
        boolean success = false;
        String xpath = null;
        for (IStepTarget target : param.getTargets()) {
            if (UsingType.SELECTOR.equals(target.getUsing())) {
                JSONObject object = JSON.parseObject(target.getValue(), JSONObject.class);
                xpath = object.getString(UsingType.Key.SELECTOR_KEY);
                logger.info("拿到的nodeTree:{}", xpath);
                break;
            }
        }
        if (StringUtils.isBlank(xpath)) {
            throw new ExecuteException("只支持xpath的方式输入");
        }
        boolean clickSuccess = clickElement(param);
        if (!clickSuccess) {
            throw new ExecuteException("未找到控件");
        }
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.CLEAR, param.isClear());
        paramMap.put(UpperParamKey.INPUT_TEXT, param.getInputTextValue());
        paramMap.put(UpperParamKey.COMMAND_ID, CommandId.INPUT_TEXT.getCode());
        paramMap.put(UpperParamKey.NODE_TREE, xpath);
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.INPUT_TEXT, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(param.getDeviceDriver(), builder, token, param.getWaitTimeout());
        logger.debug("控件输入的结果：{}", o);
        if (null != o) {
            success = (boolean) o;
        } else {
            throw new ExecuteException("输入超时");
        }
        if (!success) {
            throw new ExecuteException("输入失败");
        }
        return success;
    }

    public static String getElementValue(ElementHandleParam param) throws Exception{
        String result = "";
        List<IStepTarget> targets = param.getTargets();
        for (IStepTarget item : targets) {
            if (UsingType.SELECTOR.equalsIgnoreCase(item.getUsing())) {  //xpath的方式
                result = nodeTreeGetElementValue(param.getDeviceDriver(), item, param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
                if (StringUtils.isNotBlank(result)) {
                    return result;
                }
            } else if (UsingType.OCR.equalsIgnoreCase(item.getUsing())) {  //ocr方式
                result = ocrGetElementValue(param.getDeviceDriver(), item, param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
                if (StringUtils.isNotBlank(result)) {
                    return result;
                }
            } else if (UsingType.HZOCR.equalsIgnoreCase(item.getUsing())) {  //杭银ocr方式
                result = ocrGetElementValue(param.getDeviceDriver(), item, param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
                if (StringUtils.isNotBlank(result)) {
                    return result;
                }
            } else {
                logger.warn("不支持的获取元素值方式：{}", item.getUsing());
            }
        }

        if (StringUtils.isBlank(result)) {
            throw new ExecuteException("无法获取当前元素的文本");
        }
        return result;
    }

    private static String nodeTreeGetElementValue(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        String result = null;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        JSONObject object = JSON.parseObject(target.getValue(), JSONObject.class);
        String xpath = object.getString(UsingType.Key.SELECTOR_KEY);
        logger.info("拿到的xpath:{}", xpath);
        paramMap.put(UpperParamKey.NODE_TREE, xpath);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.GET_ELEMENT_VALUE_BY_NODE, token, paramMap);
        result = (String) sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据nodeTree查找的结果：{}", result);
        return result;
    }

    private static String ocrGetElementValue(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        String result = null;
        JSONObject value = JSON.parseObject(target.getValue(), JSONObject.class);
        Integer x = null;
        Integer y = null;
        Integer screenWidth = null;
        Integer screenHeight = null;
        Integer width = null;
        Integer height = null;
        try {
            x = value.getInteger("x");
            y = value.getInteger("y");
            screenWidth = value.getInteger("screenWidth");
            screenHeight = value.getInteger("screenHeight");
            width = value.getInteger("width");
            height = value.getInteger("height");
        } catch (Exception e) {
            logger.error("坐标参数不对", e);
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.USING_TYPE, target.getUsing());
        paramMap.put(UpperParamKey.WIDTH, width);
        paramMap.put(UpperParamKey.HEIGHT, height);
        paramMap.put(UpperParamKey.X, x);
        paramMap.put(UpperParamKey.Y, y);
        paramMap.put(UpperParamKey.SCREEN_WIDTH, screenWidth);
        paramMap.put(UpperParamKey.SCREEN_HEIGHT, screenHeight);
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.GET_ELEMENT_VALUE_BY_OCR, token, paramMap);
        result = (String) sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据ocr查找的结果：{}", result);
        return result;
    }

    public static boolean longPressElement(ElementHandleParam param) throws Exception{
        PointMessage point = findElementByTargets(param.getDeviceDriver(), param.getTargets(), param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
        if (point == null) {
            logger.error("查找不到控件");
            throw new ExecuteException("查找不到控件");
        }
        /**
         * 设置偏移量
         */
        point.setxMove(param.getxMove());
        point.setyMove(param.getyMove());
        boolean success = longPressElementByPoint(param.getDeviceDriver(), point, param.getWaitTimeout());
        return success;
    }

    private static boolean longPressElementByPoint(DeviceDriver deviceDriver, PointMessage point, Integer waitTimeout) throws Exception{
        Boolean success = false;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.POINT, point);
        CmdAutomationRequest request = CmdAutomationRequest.builder(AutomationRequestCmd.LONG_PRESS, token, paramMap);
        Object result = sendUpperMessageAndWaitReturn(deviceDriver, request, token, waitTimeout);
        logger.debug("根据坐标点击的结果：{}", result);
        if (null != request) {
            success = JSONObject.parseObject(JSONObject.toJSONString(result), Boolean.class);
        } else {
            throw new ExecuteException("点击元素失败");
        }
        return success;
    }

    public static String getVerificationCode(ElementHandleParam param) throws Exception{
        String result = "";
        List<IStepTarget> targets = param.getTargets();
        for (IStepTarget target : targets) {
            for (IStepTarget item : targets) {
                if (UsingType.SELECTOR.equalsIgnoreCase(item.getUsing())) {  //xpath的方式
                    result = nodeTreeGetVerificationCode(param.getDeviceDriver(), target, param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
                    if (StringUtils.isNotBlank(result)) {
                        return result;
                    }
                } else if (UsingType.OCR.equalsIgnoreCase(item.getUsing())) {  //ocr方式
                    result = ocrGetVerificationCode(param.getDeviceDriver(), target, param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
                    if (StringUtils.isNotBlank(result)) {
                        return result;
                    }
                } else if (UsingType.HZOCR.equalsIgnoreCase(item.getUsing())) {  //杭银ocr方式
                    result = ocrGetVerificationCode(param.getDeviceDriver(), target, param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
                    if (StringUtils.isNotBlank(result)) {
                        return result;
                    }
                } else {
                    logger.warn("不支持的获取元素值方式：{}", target.getUsing());
                }
            }
        }
        if (StringUtils.isBlank(result)) {
            throw new ExecuteException("无法获取验证码");
        }
        return result;
    }

    private static String ocrGetVerificationCode(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        String result = null;
        JSONObject value = JSON.parseObject(target.getValue(), JSONObject.class);
        Integer x = null;
        Integer y = null;
        Integer screenWidth = null;
        Integer screenHeight = null;
        Integer width = null;
        Integer height = null;
        try {
            x = value.getInteger("x");
            y = value.getInteger("y");
            screenWidth = value.getInteger("screenWidth");
            screenHeight = value.getInteger("screenHeight");
            width = value.getInteger("width");
            height = value.getInteger("height");
        } catch (Exception e) {
            logger.error("坐标参数不对", e);
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.USING_TYPE, target.getUsing());
        paramMap.put(UpperParamKey.WIDTH, width);
        paramMap.put(UpperParamKey.HEIGHT, height);
        paramMap.put(UpperParamKey.X, x);
        paramMap.put(UpperParamKey.Y, y);
        paramMap.put(UpperParamKey.SCREEN_WIDTH, screenWidth);
        paramMap.put(UpperParamKey.SCREEN_HEIGHT, screenHeight);
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.GET_VERIFICATION_CODE_BY_OCR, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据ocr查找的结果：{}", o);
        if (null != o) {
            result = JSONObject.parseObject(JSONObject.toJSONString(o), String.class);
        }
        return result;
    }

    private static String nodeTreeGetVerificationCode(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        String result = null;
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        JSONObject object = JSON.parseObject(target.getValue(), JSONObject.class);
        String xpath = object.getString(UsingType.Key.SELECTOR_KEY);
        logger.info("拿到的xpath:{}", xpath);
        paramMap.put(UpperParamKey.NODE_TREE, xpath);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.GET_VERIFICATION_CODE_BY_NODE, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据nodeTree获取验证码的结果：{}", o);
        if (null != o) {
            result = JSONObject.parseObject(JSONObject.toJSONString(o), String.class);
        }
        return result;
    }


    public static boolean clickText(ElementHandleParam param) throws Exception{
        boolean success = clickTextByOcr(param.getDeviceDriver(), param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount(),
                CommandId.POINT_CLICK, param.getText(), param.getIndex(), param.getContext());
        return success;
    }

    public static boolean clickTextNew(ElementHandleParam param) throws Exception{
        boolean success = clickTextByOcrNew(param.getDeviceDriver(), param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount(),
                CommandId.POINT_CLICK, param.getText(), param.getIndex(), param.getContext());
        return success;
    }

    private static boolean clickTextByOcr(DeviceDriver deviceDriver, Integer waitTimeout, String swipe, Integer swipeCount, CommandId command,
                                          String text, Integer index, IExecuteContext context) throws Exception{
        Boolean success = false;
        if (text.length() > 20) {
            throw new ParamMistakeException("点击的文本过长");
        }
        String value = CommonUtils.handleVariable(context, text);
        Map<String, Object> paramMap = getClickTextOcrParam(swipe,swipeCount,value,index);
        if (null == paramMap) {
            return false;
        }
        paramMap.put(UpperParamKey.COMMAND_ID, command.getCode());
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.CLICK_TEXT_BY_OCR, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据ocr点击的结果：{}",o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }

    private static boolean clickTextByOcrNew(DeviceDriver deviceDriver, Integer waitTimeout, String swipe, Integer swipeCount, CommandId command,
                                          String text, Integer index, IExecuteContext context) throws Exception{
        Boolean success = false;
        if (text.length() > 20) {
            throw new ParamMistakeException("点击的文本过长");
        }
        String value = CommonUtils.handleVariable(context, text);
        Map<String, Object> paramMap = getClickTextOcrParam(swipe,swipeCount,value,index);
        if (null == paramMap) {
            return false;
        }
        paramMap.put(UpperParamKey.COMMAND_ID, command.getCode());
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.CLICK_TEXT_BY_OCR_NEW, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据新ocr点击的结果：{}",o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }

    public static boolean ifText(ElementHandleParam param) throws Exception{
        Boolean success = false;
        Map<String, Object> paramMap = getClickTextOcrParam(param.getSwipe(),param.getSwipeCount(),param.getText(),param.getIndex());
        if (null == paramMap) {
            return false;
        }
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.IF_TEXT, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(param.getDeviceDriver(), builder, token, param.getWaitTimeout());
        logger.debug("是否存在文本的结果：{}",o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }

    public static boolean handleApp(ElementHandleParam param) throws Exception{
        Boolean success = false;
        Map<String, Object> paramMap = getHandleAppParam(param.getAppPackage(), param.getType());
        if (null == paramMap) {
            return false;
        }
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.HANDLE_APP, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(param.getDeviceDriver(), builder, token, param.getWaitTimeout());
        logger.debug("应用处理的结果：{}",o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }

    private static Map<String, Object> getHandleAppParam(String appPackage, String type) {
        if (StringUtils.isBlank(appPackage)) {
            logger.warn("启动的应用包名为空................");
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.APP_PACKAGE, appPackage);
        paramMap.put(UpperParamKey.TYPE, type);
        return paramMap;
    }

    public static boolean pressKeyHome(ElementHandleParam param) throws Exception{
        Boolean success = false;
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.PRESS_HOME_KEY, token, new HashMap<>());
        Object o = sendUpperMessageAndWaitReturn(param.getDeviceDriver(), builder, token, param.getWaitTimeout());
        logger.debug("点击home键的结果：{}",o);
        if (null != o) {
            success = JSONObject.parseObject(JSONObject.toJSONString(o), Boolean.class);
        }
        return success;
    }


    public static boolean inputPasswordByOcr(ElementHandleParam param) throws Exception{
        boolean result = false;
        List<IStepTarget> targets = param.getTargets();
        for (IStepTarget target : targets) {
            for (IStepTarget item : targets) {
              if (UsingType.OCR.equalsIgnoreCase(item.getUsing())) { //ocr方式
                    result = inputPasswordByOcr(param.getDeviceDriver(), target, param.getWaitTimeout(), param.getSwipe(),
                            param.getSwipeCount(), param.getText());
                        return result;
                } else {
                    logger.warn("不支持的密码输入方式：{}", target.getUsing());
                }
            }
        }
        return result;
    }

    private static boolean inputPasswordByOcr(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe,
                                              Integer swipeCount, String text) throws Exception{
        boolean success = false;
        Map<String, Object> paramMap = getInputPasswordByOcrParam(target.getValue(), swipe, swipeCount, text);
        if (null == paramMap) {
            return false;
        }
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.INPUT_PASSWORD_BY_OCR, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("密码输入（ocr）的结果：{}",o);
        if (null != o) {
            success = (boolean) o;
        }
        return success;
    }

    private static Map<String, Object> getInputPasswordByOcrParam(String param, String swipe, Integer swipeCount, String text) throws Exception{
        JSONObject value = JSON.parseObject(param, JSONObject.class);
        Integer x = null;
        Integer y = null;
        Integer screenWidth = null;
        Integer screenHeight = null;
        Integer width = null;
        Integer height = null;
        try {
            x = value.getInteger("x");
            y = value.getInteger("y");
            screenWidth = value.getInteger("screenWidth");
            screenHeight = value.getInteger("screenHeight");
            width = value.getInteger("width");
            height = value.getInteger("height");
        } catch (Exception e) {
            logger.error("坐标参数不对",e);
            return null;
        }
        if (StringUtils.isBlank(text)) {
            logger.warn("输入的文本为空................");
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.WIDTH, width);
        paramMap.put(UpperParamKey.HEIGHT, height);
        paramMap.put(UpperParamKey.X, x);
        paramMap.put(UpperParamKey.Y, y);
        paramMap.put(UpperParamKey.SCREEN_WIDTH, screenWidth);
        paramMap.put(UpperParamKey.SCREEN_HEIGHT, screenHeight);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        paramMap.put(UpperParamKey.INPUT_TEXT, text);
        return paramMap;
    }

    public static String getElementMoneyText(ElementHandleParam param) throws Exception{
        String result = "";
        List<IStepTarget> targets = param.getTargets();
        for (IStepTarget target : targets) {
            if (UsingType.OCR.equalsIgnoreCase(target.getUsing()) || UsingType.HZOCR.equalsIgnoreCase(target.getUsing())) {  //ocr方式
                result = getElementMoneyText(param.getDeviceDriver(), target, param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
                if (StringUtils.isNotBlank(result)) {
                    return result;
                }
            } else {
                logger.warn("不支持的获取元素值方式：{}", target.getUsing());
            }
        }
        return result;
    }

    private static String getElementMoneyText(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        String result = null;
        JSONObject value = JSON.parseObject(target.getValue(), JSONObject.class);
        Integer x = null;
        Integer y = null;
        Integer screenWidth = null;
        Integer screenHeight = null;
        Integer width = null;
        Integer height = null;
        try {
            x = value.getInteger("x");
            y = value.getInteger("y");
            screenWidth = value.getInteger("screenWidth");
            screenHeight = value.getInteger("screenHeight");
            width = value.getInteger("width");
            height = value.getInteger("height");
        } catch (Exception e) {
            logger.error("坐标参数不对", e);
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.USING_TYPE, target.getUsing());
        paramMap.put(UpperParamKey.WIDTH, width);
        paramMap.put(UpperParamKey.HEIGHT, height);
        paramMap.put(UpperParamKey.X, x);
        paramMap.put(UpperParamKey.Y, y);
        paramMap.put(UpperParamKey.SCREEN_WIDTH, screenWidth);
        paramMap.put(UpperParamKey.SCREEN_HEIGHT, screenHeight);
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        String token = UUID.randomUUID().toString();
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.GET_ELEMENT_MONEY_TEXT, token, paramMap);
        result = (String) sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据ocr查找的金额结果：{}", result);
        return result;
    }

    public static Boolean screenShot(ElementHandleParam param) throws Exception {
        String screenShotUrl = "";
        String token = UUID.randomUUID().toString();
        String tenantId = (String) param.getContext().getContextVariable("__tenantId");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.TENANT_ID, tenantId);
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        logger.debug("tenantId：{}",tenantId);
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.SCREEN_SHOT, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(param.getDeviceDriver(), builder, token, param.getWaitTimeout());
        logger.debug("屏幕截图的结果：{}",o);
        if (null != o) {
            screenShotUrl = (String) o;
            param.getContext().setVariable("mobileStepSnapshot",screenShotUrl);
            return true;
        }
        return false;
    }

    public static String getElementValueByOcr(ElementHandleParam param) throws Exception{
        String result = "";
        List<IStepTarget> targets = param.getTargets();
        for (IStepTarget target : targets) {
            result = getElementValueByOcr(param.getDeviceDriver(), target, param.getWaitTimeout(), param.getSwipe(), param.getSwipeCount());
            if (StringUtils.isNotBlank(result)) {
                return result;

            }
        }
        return result;
    }

    private static String getElementValueByOcr(DeviceDriver deviceDriver, IStepTarget target, Integer waitTimeout, String swipe, Integer swipeCount) throws Exception{
        String result = "";
        String token = UUID.randomUUID().toString();
        Map<String, Object> paramMap = new HashMap<>();
        JSONObject object = JSON.parseObject(target.getValue(), JSONObject.class);
        String xpath = object.getString(UsingType.Key.SELECTOR_KEY);
        logger.info("拿到的xpath:{}", xpath);
        paramMap.put(UpperParamKey.NODE_TREE, xpath);
        paramMap.put(UpperParamKey.IS_SWIPE, swipe);
        paramMap.put(UpperParamKey.SWIPE_COUNT, swipeCount);
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.GET_ELEMENT_VALUE_BY_PATH_OCR, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(deviceDriver, builder, token, waitTimeout);
        logger.debug("根据nodeTree查找,ocr识别的结果：{}", o);
        if (null != o) {
            result = (String) o;
        }
        return result;
    }

    public static Boolean pressAndSwipe(ElementHandleParam param) throws Exception{
        boolean success = false;
        String token = UUID.randomUUID().toString();
        String firstPointStr = param.getFirstPoint();
        String firstPoint = null;
        List<JSONObject> firstPointList = JSONObject.parseArray(firstPointStr, JSONObject.class);
        for (JSONObject jsonObject : firstPointList) {
            if (UsingType.SELECTOR.equals(jsonObject.getString("using"))) {
                firstPoint = jsonObject.getString("value");
                break;
            }
        }
        logger.debug("第一个点的定位xpath：{}", firstPoint);
        if (StringUtils.isBlank(firstPoint)) {
            throw new ExecuteException("左上角的点没有定位条件");
        }
        String secondPointStr = param.getSecondPoint();
        String secondPoint = null;
        List<JSONObject> secondPointList = JSONObject.parseArray(secondPointStr, JSONObject.class);
        for (JSONObject jsonObject : secondPointList) {
            if (UsingType.SELECTOR.equals(jsonObject.getString("using"))) {
                secondPoint = jsonObject.getString("value");
                break;
            }
        }
        logger.debug("第二个点的定位xpath：{}", secondPoint);
        if (StringUtils.isBlank(secondPoint)) {
            throw new ExecuteException("左上角的右边第一个点没有定位条件");
        }
        String thirdPointStr = param.getThirdPoint();
        String thirdPoint = null;
        List<JSONObject> thirdPointList = JSONObject.parseArray(thirdPointStr, JSONObject.class);
        for (JSONObject jsonObject : thirdPointList) {
            if (UsingType.SELECTOR.equals(jsonObject.getString("using"))) {
                thirdPoint = jsonObject.getString("value");
                break;
            }
        }
        logger.debug("第三个点的定位xpath：{}", thirdPoint);
        if (StringUtils.isBlank(secondPoint)) {
            throw new ExecuteException("左上角的下边第一个点没有定位条件");
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(UpperParamKey.FIRST_POINT, firstPoint);
        paramMap.put(UpperParamKey.SECOND_POINT, secondPoint);
        paramMap.put(UpperParamKey.THIRD_POINT, thirdPoint);
        paramMap.put(UpperParamKey.POINT_NUM, param.getPointNum());
        paramMap.put(UpperParamKey.SWIPE_POINT, param.getPassingPoints());
        paramMap.put(UpperParamKey.WAIT_TIMEOUT, param.getWaitTimeout());
        logger.info("参数：{}", JSON.toJSONString(paramMap));
        CmdAutomationRequest builder = CmdAutomationRequest.builder(AutomationRequestCmd.PRESS_AND_SWIPE, token, paramMap);
        Object o = sendUpperMessageAndWaitReturn(param.getDeviceDriver(), builder, token, param.getWaitTimeout());
        logger.debug("滑动解锁的结果：{}",o);
        if (null != o) {
            success = (boolean) o;
        }
        if (!success) {
            throw new ExecuteException("滑动解锁失败");
        }
        return success;
    }
}
