package com.zjty.autotest.service.impl;

import com.alibaba.fastjson.JSON;
import com.zjty.autotest.mq.CacheManager;
import com.zjty.autotest.pojo.report.Measure;
import com.zjty.autotest.pojo.report.Report;
import com.zjty.autotest.pojo.sjq.*;
import com.zjty.autotest.pojo.test.Input;
import com.zjty.autotest.pojo.test.Project;
import com.zjty.autotest.service.AsyncService;
import com.zjty.autotest.service.AutoResultSetService;
import com.zjty.autotest.service.TestReportService;
import com.zjty.autotest.util.FileHtmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AsyncServiceImpl implements AsyncService {
    @Autowired
    private AutoResultSetService autoResultSetService;
    @Autowired
    private TestReportService testReportService;
    @Autowired
    private SeleniumExecutor seleniumExecutor;

    @Override
    @Async
    public void executeAsync(String id) {
        System.out.println("id:" + id);
        TestChannel testChannel = (TestChannel) CacheManager.getCache(id);
        if (testChannel != null) {
            try {
                Project project=new Project();
                project.setBrowser(testChannel.getBrowser());
                project.setName(testChannel.getName());
                project.setUrl(testChannel.getUrl());
                List<RuleSet> ruleSets = testChannel.getRuleSets();
                List<Input> inputs=new ArrayList<>();
                project.setInputs(null);
                if(ruleSets!=null) {
                    for (RuleSet ruleSet : ruleSets) {
                        Input input=new Input();
                        input.setKey(ruleSet.getDes());
                        input.setAttrName(ruleSet.getCommand());
                        input.setAttrValue(ruleSet.getTarget());
                        input.setValue(ruleSet.getValue());
                        inputs.add(input);
                    }
                    project.setInputs(inputs);
                }


                //调用黄承天代码
                Report report = seleniumExecutor.execute(project);
                List<Measure> measures = report.getMeasures();
                if(measures!=null) {
                    long count = measures.stream().filter(m -> !m.getSuccess()).count();
                    System.out.println(report);
                    EvaReport evaReport = new EvaReport();
                    evaReport.setBrowser(report.getBrowser());
                    if (count > 0) {
                        evaReport.setFailCount(testChannel.getName() + "系统未通过测试，" + "未通过测试点共" + count + "个");
                    }
                    evaReport.setFailCount(testChannel.getName() + "系统通过测试，" + "未通过测试点共0个");
                    evaReport.setProjectName(report.getProjectName());
                    evaReport.setCreateTime(new Date());
                    evaReport.setSystem("中标麒麟v7龙芯版");
                    evaReport.setUrl(testChannel.getUrl());
                    List<FailMessage> failMessages = new ArrayList<>();
                    List<Measure> measureList = measures.stream().filter(m -> !m.getSuccess()).collect(Collectors.toList());
                    for (Measure measure : measureList) {
                        FailMessage failMessage = new FailMessage();
                        failMessage.setUrl(measure.getUrl());
                        failMessage.setMessage(measure.getMessage());
                        failMessage.setPicture(measure.getScreenshot());
                        failMessages.add(failMessage);
                    }
                    evaReport.setFailMessages(failMessages);
                    evaReport.setPageRoutes(null);
                    HashMap<String, List<Measure>> map = new HashMap<>();
                    for (Measure measure : measures) {
                        if(map.get(measure.getUrl())!=null){
                            List<Measure> measures1 = map.get(measure.getUrl());
                            measures1.add(measure);
                            map.put(measure.getUrl(),measures1);
                        }else {
                            List<Measure> mss=new ArrayList<>();
                            mss.add(measure);
                            map.put(measure.getUrl(),mss);
                        }

                    }

                    List<PageContentTest> pageContents = new ArrayList<>();
                    Set<String> strings = map.keySet();
                    for (String url : strings) {
                        PageContentTest pageContentTest = new PageContentTest();
                        pageContentTest.setUrl(url);
                        List<Measure> measures1 = map.get(url);
                        List<PageContent> contents = new ArrayList<>();
                        for (Measure measure : measures1) {
                            PageContent pageContent = new PageContent();
                            pageContent.setParms(null);
                            pageContent.setMessage(measure.getMessage());
                            pageContent.setResponseTime(measure.getResponseTime());
                            pageContent.setSuccess(0);
                            if(measure.getSuccess()) {
                                pageContent.setSuccess(1);
                            }
                            contents.add(pageContent);
                        }
                        pageContentTest.setContents(contents);
                        pageContents.add(pageContentTest);
                    }
                    evaReport.setPageContents(pageContents);

                /*List<PageRoute> pageRoutes = new ArrayList<>();
                PageRoute pageRoute = new PageRoute();
                pageRoute.setPageName("https://www.baidu.com/");
                pageRoute.setAddress("/baidu");
                pageRoute.setMessage("");
                pageRoute.setResponseTime(300);
                pageRoute.setSuccess(0);
                pageRoute.setPicture("https://pics4.baidu.com/feed/500fd9f9d72a6059aecf87d92406529d013bbaca.jpeg?token=53433060d4d120e00d8ac6612d2303fd");
                PageRoute pageRoute1 = new PageRoute();
                pageRoute1.setPageName("https://www.baidu.com/");
                pageRoute1.setAddress("/baidu");
                pageRoute1.setMessage("不能访问");
                pageRoute1.setResponseTime(300);
                pageRoute1.setSuccess(1);
                pageRoute1.setPicture("https://pics4.baidu.com/feed/500fd9f9d72a6059aecf87d92406529d013bbaca.jpeg?token=53433060d4d120e00d8ac6612d2303fd");
                pageRoutes.add(pageRoute);
                pageRoutes.add(pageRoute1);*/
//                evaReport.setPageRoutes(pageRoutes);


                    if (testChannel.getCodeUrl() != null) {
                        if (testChannel.getCodeUrl() != null) {
                            //解压上传得代码

                            FileHtmlUtil.getFiles(testChannel.getCodeUrl(), null);
                            Map<String, List<FileType>> alls = FileHtmlUtil.getAlls();

                            //获取项目类型
                            FileHtmlUtil.getFileRoutes(testChannel.getCodeUrl());
                            int jspcount=FileHtmlUtil.jspNum;
                            int jscount=FileHtmlUtil.jsNum;
                            int vuecount=FileHtmlUtil.vueNum;
                            int angularcount=FileHtmlUtil.angularNum;
                            int htmlcount=FileHtmlUtil.count;
                            String fileRoutes=null;
                            if(jspcount>0){
                                fileRoutes="jsp";
                            }else if(vuecount>0){
                                fileRoutes="vue";
                            }else if(jscount>0){
                                fileRoutes="react";
                            }else if(angularcount>0){
                                fileRoutes="angular";
                            }
                            if (fileRoutes != null) {
//                                List<String> routerList = getRouterList(alls, fileRoutes);
//                                List<String> collect = routerList.stream().map(String::toLowerCase).distinct().collect(Collectors.toList());
//                                System.out.println(collect.toString());
                            }


                            FileHtmlUtil.clearAll();
                            //获取前端代码中得网页路由地址
                            //比对黄承天代码中访问得地址和路由地址，黄承天是否访问全了。
                        }
                        //比对黄承天代码中访问得地址和路由地址，黄承天是否访问全了。
                    }
                    System.out.println("修改状态");
                    //改变报告状态
                    String out = JSON.toJSONString(evaReport);
                    String in = JSON.toJSONString(testChannel);
                    System.out.println(id);
                    System.out.println("输出："+out);
                    System.out.println("输入："+in);
                    TestReport testReport = new TestReport();
                    testReport.setResultId(id);
                    testReport.setOutReport(out);
                    testReport.setInputReport(in);
                    testReport.setStatus(1);
                    testReportService.save(testReport);
                    CacheManager.removeCache(id);
                }
//                autoResultSetService.updateByid(id);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void doBusiness(String id) {
        System.out.println("doBusiness id:" + id);
        TestChannel testChannel = (TestChannel) CacheManager.getCache(id);
        if (testChannel != null) {
            try {

                EvaReport evaReport = new EvaReport();
                evaReport.setBrowser(testChannel.getBrowser());
                evaReport.setFailCount(testChannel.getName() + "系统未通过测试，" + "未通过测试点共" + "10" + "个");
                evaReport.setProjectName(testChannel.getName());
                evaReport.setCreateTime(new Date());
                evaReport.setSystem("中标麒麟v7龙芯版");
                evaReport.setUrl(testChannel.getUrl());
                List<FailMessage> failMessages = new ArrayList<>();
                FailMessage failMessage = new FailMessage();
                failMessage.setUrl("https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_1");
                failMessage.setMessage("抗击疫情打不开响应超时");
                failMessage.setPicture("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1584955247760&di=f073d6fd65cf71798843c6e4634358dd&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F78%2F52%2F01200000123847134434529793168.jpg");
                failMessages.add(failMessage);
                evaReport.setFailMessages(failMessages);
                List<PageRoute> pageRoutes = new ArrayList<>();
                PageRoute pageRoute = new PageRoute();
                pageRoute.setPageName("https://www.baidu.com/");
                pageRoute.setAddress("/baidu");
                pageRoute.setMessage("");
                pageRoute.setResponseTime(300);
                pageRoute.setSuccess(0);
                pageRoute.setPicture("https://pics4.baidu.com/feed/500fd9f9d72a6059aecf87d92406529d013bbaca.jpeg?token=53433060d4d120e00d8ac6612d2303fd");
                PageRoute pageRoute1 = new PageRoute();
                pageRoute1.setPageName("https://www.baidu.com/");
                pageRoute1.setAddress("/baidu");
                pageRoute1.setMessage("不能访问");
                pageRoute1.setResponseTime(300);
                pageRoute1.setSuccess(1);
                pageRoute1.setPicture("https://pics4.baidu.com/feed/500fd9f9d72a6059aecf87d92406529d013bbaca.jpeg?token=53433060d4d120e00d8ac6612d2303fd");
                pageRoutes.add(pageRoute);
                pageRoutes.add(pageRoute1);
                evaReport.setPageRoutes(pageRoutes);
                List<PageContentTest> pageContents = new ArrayList<>();
                PageContentTest pageContentTest = new PageContentTest();
                pageContentTest.setUrl("http://news.baidu.com/");
                List<PageContent> contents = new ArrayList<>();
                PageContent pageContent = new PageContent();
                pageContent.setParms("国内");
                pageContent.setMessage("");
                pageContent.setResponseTime(300);
                pageContent.setSuccess(0);
                PageContent pageContent1 = new PageContent();
                pageContent1.setParms("国外");
                pageContent1.setMessage("响应时间过长");
                pageContent1.setResponseTime(30000);
                pageContent1.setSuccess(1);
                contents.add(pageContent);
                contents.add(pageContent1);
                pageContentTest.setContents(contents);
                pageContents.add(pageContentTest);
                evaReport.setPageContents(pageContents);

                System.out.println("修改状态");
                //改变报告状态
                String out = JSON.toJSONString(evaReport);
                String in = JSON.toJSONString(testChannel);
                System.out.println(out);
                System.out.println(in);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
