package com.zjty.autotest.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Queues;
import com.google.common.collect.Sets;
import com.zjty.autotest.common.action.LabelType;
import com.zjty.autotest.pojo.report.ElementDetail;
import com.zjty.autotest.pojo.report.Measure;
import com.zjty.autotest.pojo.report.Report;
import com.zjty.autotest.pojo.test.ElementEntry;
import com.zjty.autotest.pojo.test.ElementFeature;
import com.zjty.autotest.pojo.test.Input;
import com.zjty.autotest.pojo.test.Project;
import com.zjty.autotest.util.FileUtil;
import com.zjty.autotest.util.WebDriverUtil;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import org.apache.logging.log4j.util.Strings;
import org.jsoup.nodes.Element;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.MoveTargetOutOfBoundsException;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Sleeper;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.net.www.protocol.file.FileURLConnection;
import sun.net.www.protocol.ftp.FtpURLConnection;

import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;

/**
 * @author C
 */
@SuppressWarnings("FieldCanBeLocal")
@Slf4j
@Service
public class SeleniumExecutor {

    @Value("${selenium.executor.wait-time}")
    private Long waitTime;

    @Value("${screenshot-path}")
    private String screenshotPath;

    @Value("${selenium.executor.fast-mode}")
    private Boolean fastMode;

    private WebDriver driver;

    private List<Input> inputs = Lists.newArrayList();

    private Set<String> historyUrls = Sets.newHashSet();

    private Set<ElementFeature> historyFeatures = Sets.newHashSet();

    private Set<ElementFeature> currentHistoryFeatures = Sets.newHashSet();

    private Set<String> totalHistoryFeatures = Sets.newHashSet();

    private Queue<String> urlQueue = Queues.newLinkedBlockingQueue();

    private Queue<ElementEntry> clickElementQueue = Queues.newLinkedBlockingQueue();

    private Queue<ElementEntry> inputElementQueue = Queues.newLinkedBlockingQueue();

    private WebDriverWait webDriverWait;

    private Actions actions;

    private Boolean isRunning = false;

    /**
     * 当前进行的窗口页
     */
    private String currentWindow;

    /**
     * 当前测试的url
     */
    private String currentUrl;

    public Report execute(Project project) {
        isRunning = true;
        historyUrls.clear();
        urlQueue.clear();
        clickElementQueue.clear();
        driver = WebDriverUtil.getWebDriver(project.getBrowser());
        driver.manage().window().maximize();
        webDriverWait = new WebDriverWait(driver, waitTime);
        actions = new Actions(driver);
        inputs = project.getInputs();
        List<Measure> measures = Lists.newArrayList();
        String os = Strings.EMPTY;
        currentUrl = project.getUrl();
        currentWindow = driver.getWindowHandle();
        try {
            while (nonNull(currentUrl)) {
                Measure measure = testUrl(currentUrl);
                if (nonNull(measure)) {
                    measures.add(measure);
                }
                currentUrl = urlQueue.poll();
            }
            driver.quit();
        } catch (Exception e) {
            log.error("发生预料外的异常.测试结束:" + e);
        }
        return new Report(
                null,
                project.getId(),
                project.getName(),
                project.getBrowser(),
                os,
                measures
        );
    }

    public void quit() {
        isRunning = false;
    }

    private Measure testUrl(String currentUrl) {
        Measure measure = new Measure();
        measure.setUrl(currentUrl);
        measure.setResponseTime(-1);
        //如果该网页是未曾进入过的网页则加入历史记录并进行遍历测试
        if (!historyUrls.contains(currentUrl)) {
            historyUrls.add(currentUrl);
            log.info("当前URL：{} ", currentUrl);
            boolean connectAble = checkConnect(currentUrl);
            boolean success;
            if (connectAble) {
                //打开网页 记录响应时间
                long responseTime = load(currentUrl);
                measure.setResponseTime((int) responseTime);
                log.info("响应时间 {} ms  开始进行遍历...", responseTime);
                log.info("剩余URL队列：{}", urlQueue);
                StringBuilder message = new StringBuilder();
                Set<String> messages = Sets.newHashSet();
                String error = checkJsError();
                if (nonNull(error)) {
                    messages.add(error);
                }
                //获取当前网页的所有元素并放入元素队列
                log.info("获取完毕...input共{}个元素...click共{}个元素...", inputElementQueue.size(), clickElementQueue.size());
                //当前页面的历史元素记录重置
                currentHistoryFeatures.clear();
                //开始遍历操作元素队列中的元素 返回各个元素测试信息
                List<ElementDetail> elementDetails = traversal();
                measure.setElementDetails(elementDetails);
                //如果全部元素通过则是通过
                success = isNull(error) && elementDetails.stream()
                        .filter(Objects::nonNull)
                        .allMatch(ElementDetail::getSuccess);
                //如果未通过 则提供截图
                if (!success) {
                    String screenshotName = alterUrlName(currentUrl) + ".png";
                    screenshot(screenshotName);
                    measure.setScreenshot(String.format("/%s", screenshotName));
                }
                measure.setSuccess(success);
                //总合信息
                messages.addAll(elementDetails.stream()
                        .filter(Objects::nonNull)
                        .map(ElementDetail::getMessage)
                        .filter(Strings::isNotEmpty)
                        .collect(Collectors.toList()));
                for (String msg : messages) {
                    message.append(msg);
                    message.append(";");
                }
                measure.setMessage(message.toString());
                log.info("遍历完毕...");
            } else {
                measure.setSuccess(false);
                measure.setMessage("无法访问的URL;");
                measure.setElementDetails(Lists.newArrayList());
            }
        }
        return measure;
    }

    @SuppressWarnings("Duplicates")
    private List<ElementDetail> traversal() {
        List<ElementDetail> elementDetails = Lists.newArrayList();
        while (!inputElementQueue.isEmpty()) {
            if (isRunning) {
                ElementEntry elementEntry = inputElementQueue.poll();
                ElementFeature feature = elementEntry.getFeature();
                if (!currentHistoryFeatures.contains(feature)) {
                    ElementDetail elementDetail = actInput(elementEntry);
                    if (!isSkipped(elementDetail)) {
                        elementDetails.add(elementDetail);
                    }
                }
            } else {
                break;
            }
        }
        while (!clickElementQueue.isEmpty()) {
            if (isRunning) {
                ElementEntry elementEntry = clickElementQueue.poll();
                ElementFeature feature = elementEntry.getFeature();
                if (fastMode) {
                    if (!totalHistoryFeatures.contains(feature.getText())) {
                        ElementDetail elementDetail = actClick(elementEntry);
                        if (!isSkipped(elementDetail)) {
                            elementDetails.add(elementDetail);
                        }
                    }
                } else {
                    if (!currentHistoryFeatures.contains(feature)) {
                        ElementDetail elementDetail = actClick(elementEntry);
                        if (!isSkipped(elementDetail)) {
                            elementDetails.add(elementDetail);
                        }
                    }
                }
            } else {
                log.info("测试已主动关闭...");
                break;
            }
        }
        return elementDetails;
    }

    private ElementDetail actInput(ElementEntry elementEntry) {
        WebElement element = elementEntry.getElement();
        ElementFeature feature = elementEntry.getFeature();
        String type = String.format("<%s>%s", feature.getTag(), feature.getText());
        String message = Strings.EMPTY;
        long responseTime = -1L;
        boolean success = false;
        try {
            if (nonNull(elementEntry.getFrame())) {
                driver.switchTo().frame(elementEntry.getFrame());
            }
            if (isEnabled(element) && isDisPlayed(element)) {
                log.info("元素 ----- feature:[{}]", feature);
                long startTime = System.currentTimeMillis();
                log.info("input操作");
                if (!inputs.isEmpty()) {
                    Input input = inputs.remove(0);
                    element.sendKeys(input.getValue());
                    element.submit();
                }
                success = true;
                long endTime = System.currentTimeMillis();
                //响应时间
                responseTime = endTime - startTime;
                //检查页面变化 有变化则重新读取URL和元素
                boolean urlChanged = checkPage();
                boolean elementStaled = ExpectedConditions.stalenessOf(element).apply(driver);
                boolean pageChanged = urlChanged || elementStaled;
                if (pageChanged) {
                    inputElementQueue.clear();
                    clickElementQueue.clear();
                }
            }
        } catch (Exception e) {
            message = "不可输入的元素";
            success = false;
            log.error("error:" + e);
        }
        if (nonNull(elementEntry.getFrame())) {
            driver.switchTo().defaultContent();
        }
        historyFeatures.add(feature);
        currentHistoryFeatures.add(feature);
        totalHistoryFeatures.add(feature.getText());
        return new ElementDetail(type, (int) responseTime, success, message);
    }

    private ElementDetail actClick(ElementEntry elementEntry) {
        WebElement element = elementEntry.getElement();
        ElementFeature feature = elementEntry.getFeature();
        String type = String.format("<%s>%s", feature.getTag(), feature.getText());
        String message = Strings.EMPTY;
        long responseTime = -1L;
        boolean success = false;
        try {
            if (nonNull(elementEntry.getFrame())) {
                driver.switchTo().frame(elementEntry.getFrame());
            }
            if (isEnabled(element) && isDisPlayed(element)) {
                log.info("元素 ----- feature:[{}]", feature);
                long startTime = System.currentTimeMillis();
                log.info("click操作");
                actions.moveToElement(element).click().perform();
                success = true;
                long endTime = System.currentTimeMillis();
                //响应时间
                responseTime = endTime - startTime;
                //检查窗口切换
                checkWindow();
                //检查页面变化 有变化则重新读取URL和元素
                boolean urlChanged = checkPage();
                boolean elementStaled = ExpectedConditions.stalenessOf(element).apply(driver);
                boolean pageChanged = urlChanged || elementStaled;
                if (pageChanged) {
                    log.warn("page changed.reload...");
                    load(currentUrl);
                    log.info("reload complete.");
                } else {
                    //页面无变化
                    //检查警告窗
                    Alert alert = ExpectedConditions.alertIsPresent().apply(driver);
                    if (nonNull(alert)) {
                        message = "出现警告窗：" + alert.getText();
                        alert.accept();
                        success = false;
                        log.error("出现警告窗:{}", alert.getText());
                    } else {
                        //通过读取浏览器日志来检查js异常
                        String jsMsg = checkJsError();
                        if (nonNull(jsMsg)) {
                            message = jsMsg;
                            success = false;
                            log.error("出现js异常:{}", jsMsg);
                        }
                    }

                }
            }
        } catch (TimeoutException e) {
            message = "元素超时";
            success = false;
            log.error("元素超时");
        } catch (MoveTargetOutOfBoundsException e) {
            message = "元素布局错误";
            success = false;
            log.error("元素布局错误");
        } catch (Exception e) {
            message = "出现预料之外的错误";
            success = false;
            e.printStackTrace();
            log.error("error:" + e);
        }
        if (nonNull(elementEntry.getFrame())) {
            driver.switchTo().defaultContent();
        }
        historyFeatures.add(feature);
        currentHistoryFeatures.add(feature);
        totalHistoryFeatures.add(feature.getText());
        return new ElementDetail(type, (int) responseTime, success, message);
    }

    private Boolean isSkipped(ElementDetail elementDetail) {
        return Objects.equals(elementDetail.getResponseTime(), -1) && Objects.equals(elementDetail.getMessage(), Strings.EMPTY);
    }

    /**
     * 检查页面是否变化包括跳转或刷新 如果跳转则将新url加入队列
     *
     * @return 页面是否有变化 若有则原来的元素都已过期 需要重新获取元素
     */
    private Boolean checkPage() {
        boolean urlChanged = checkURl();
        boolean pageChanged = false;
        if (urlChanged) {
            log.info("URL changed.");
            pageChanged = true;
            String practiseCurrentUrl = driver.getCurrentUrl();
            boolean newPage = !historyUrls.contains(practiseCurrentUrl)
                    && !Sets.newHashSet(urlQueue).contains(practiseCurrentUrl);
            if (newPage) {
                log.info("检测到新URL:{} 加入队列 ", driver.getCurrentUrl());
                urlQueue.add(driver.getCurrentUrl());
                urlQueue = queueDuplicateRemoval(urlQueue);
            }
        }
        return pageChanged;
    }

    private Boolean checkURl() {
        String practiseUrl = webDriverWait.until(WebDriver::getCurrentUrl);
        return !Objects.equals(currentUrl, practiseUrl);
    }

    private Queue<String> queueDuplicateRemoval(Queue<String> queue) {
        HashSet<String> set = Sets.newHashSet(queue);
        return Queues.newLinkedBlockingDeque(set);
    }

    @SuppressWarnings("unused")
    private String getMainUrl(String url) {
        int end = url.indexOf("?");
        return url.substring(0, end);
    }

    @SuppressWarnings("unused")
    private void inputValue(WebElement element, List<Input> inputs) {
        Predicate<Input> inputMatch = input -> Objects.equals(element.getAttribute(input.getAttrName()), input.getAttrValue());
        Optional<Input> inputOptional = inputs.stream().filter(inputMatch).findAny();
        if (inputOptional.isPresent()) {
            Input input = inputOptional.get();
            element.sendKeys(input.getValue());
        }
    }

    private void checkWindow() {
        Set<String> practise = webDriverWait.until(WebDriver::getWindowHandles);
        boolean windowChanged = practise.size() >= 2;
        if (windowChanged) {
            for (String newWindow : practise) {
                if (!Objects.equals(newWindow, currentWindow)) {
                    driver.switchTo().window(newWindow);
                    log.info("here comes a new window.");
                    String practiseCurrentUrl = driver.getCurrentUrl();
                    boolean newPage = !historyUrls.contains(practiseCurrentUrl)
                            && !Sets.newHashSet(urlQueue).contains(practiseCurrentUrl);
                    if (newPage) {
                        log.info("检测到新URL:{} 加入队列 ", driver.getCurrentUrl());
                        urlQueue.add(driver.getCurrentUrl());
                        urlQueue = queueDuplicateRemoval(urlQueue);
                    }
                    driver.close();
                    driver.switchTo().window(currentWindow);
                    break;
                }
            }
        }
    }

    private Long load(String currentUrl) {
        long startTime = System.currentTimeMillis();
        driver.get(currentUrl);
        long endTime = System.currentTimeMillis();
        long responseTime = endTime - startTime;
        getAllElements();
        return responseTime;
    }

    @SuppressWarnings("unused")
    private void sleep() {
        try {
            Sleeper.SYSTEM_SLEEPER.sleep(Duration.ofSeconds(waitTime));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void getAllElements() {
        clickElementQueue.clear();
        List<WebElement> webElements = webDriverWait.until(webDriver -> driver.findElements(By.xpath("//*")));
        for (WebElement webElement : webElements) {
            ElementFeature feature;
            if (fastMode) {
                feature = toFeatureFast(webElement);
            } else {
                feature = toFeature(webElement);
            }
            ElementEntry entry = new ElementEntry(feature, webElement, null);
            if (webElement.findElements(By.xpath(".//*")).isEmpty()) {
                if (isInput(feature)) {
                    inputElementQueue.add(entry);
                } else {
                    clickElementQueue.add(entry);
                }
            }
        }
    }

    private Boolean isInput(ElementFeature feature) {
        return Objects.equals(feature.getTag(), LabelType.INPUT);
    }

    private Boolean isEnabled(WebElement element) {
        return element.isEnabled();
    }

    private Boolean isDisPlayed(WebElement element) {
        return element.isDisplayed();
    }

    private String alterUrlName(String fileName) {
        // /\?*:"<>|
        return fileName.replace("/", Strings.EMPTY)
                .replace("\\", Strings.EMPTY)
                .replace("#", Strings.EMPTY)
                .replace("?", Strings.EMPTY)
                .replace("*", Strings.EMPTY)
                .replace(":", Strings.EMPTY)
                .replace("<", Strings.EMPTY)
                .replace(".", Strings.EMPTY)
                .replace(">", Strings.EMPTY)
                .replace("|", Strings.EMPTY);
    }

    private void screenshot(String name) {
        byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        String path;
        String suffix = "/";
        if (screenshotPath.endsWith(suffix)) {
            path = screenshotPath + name;
        } else {
            path = screenshotPath + suffix + name;
        }
        FileUtil.output(bytes, path);
    }

    @SuppressWarnings("unused")
    private Boolean elementMatch(WebElement webElement, Element element) {
        return element.attributes().asList().stream()
                .allMatch(attribute -> Objects.equals(attribute.getValue(), webElement.getAttribute(attribute.getKey())));
    }

    @SuppressWarnings("unused")
    private Map<ElementFeature, WebElement> removeHistoryElements(Map<ElementFeature, WebElement> elements) {
        Map<ElementFeature, WebElement> result = Maps.newHashMap(elements);
        elements.forEach((feature, element) -> {
            if (historyFeatures.contains(feature)) {
                result.remove(feature, element);
            }
        });
        return result;
    }

    private String checkJsError() {
        try {
            List<LogEntry> entries = webDriverWait.until(webDriver -> webDriver.manage().logs().get(LogType.BROWSER).getAll());
            return analyseLogError(entries.stream().findFirst().orElse(null));
        } catch (Exception e) {
            log.error("出现异常：checkJsError()" + e);
            return null;
        }
    }

    private String analyseLogError(LogEntry logEntry) {
        String typeError = "Uncaught TypeError:";
        String fileNotFound = "Failed to load resource: net::ERR_FILE_NOT_FOUND";
        String errorConnection = "Failed to load resource: net::ERR_CONNECTION_RESET";
        String resourceFailure = "Failed to load resource: ";
        String referenceError = "Uncaught ReferenceError: ";
        if (nonNull(logEntry) && nonNull(logEntry.getMessage())) {
            if (logEntry.getMessage().contains(typeError)) {
                return "JS类型错误";
            } else if (logEntry.getMessage().contains(fileNotFound)) {
                return "资源加载错误";
            } else if (logEntry.getMessage().contains(errorConnection)) {
                return "数据请求错误";
            } else if (logEntry.getMessage().contains(resourceFailure)) {
                return "加载依赖错误";
            } else if (logEntry.getMessage().contains(referenceError)) {
                return "依赖缺失";
            }
        }
        return null;
    }

    private ElementFeature toFeature(WebElement element) {
        return new ElementFeature(
                element.getTagName(),
                element.getText(),
                element.getRect()
        );
    }

    private ElementFeature toFeatureFast(WebElement element) {
        return new ElementFeature(
                element.getTagName(),
                element.getText(),
                null
        );
    }

    private Boolean checkConnect(String url) {
        boolean connect = false;
        String httpPrefix = "http";
        String filePrefix = "file";
        String ftpPrefix = "ftp";
        if (url.startsWith(httpPrefix)) {
            try {
                URL u = new URL(url);
                HttpURLConnection uConnection = (HttpURLConnection) u.openConnection();
                uConnection.connect();
                connect = true;
                uConnection.disconnect();
            } catch (Exception e) {
                connect = false;
            }
        } else if (url.startsWith(filePrefix)) {
            try {
                URL u = new URL(url);
                FileURLConnection uConnection = (FileURLConnection) u.openConnection();
                uConnection.connect();
                connect = true;
                uConnection.close();
            } catch (Exception e) {
                connect = false;
            }
        } else if (url.startsWith(ftpPrefix)) {
            try {
                URL u = new URL(url);
                FtpURLConnection uConnection = (FtpURLConnection) u.openConnection();
                uConnection.connect();
                connect = true;
                uConnection.close();
            } catch (Exception e) {
                connect = false;
            }
        }
        return connect;
    }

}
