package com.ruoyi.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.domain.TestUseCase;
import com.ruoyi.domain.vo.CaseResultVO;
import com.ruoyi.domain.vo.CountVO;
import com.ruoyi.domain.vo.TestUsecaseVO;
import com.ruoyi.domain.vo.UseCaseUrlVO;
import com.ruoyi.mapper.TestUseCaseMapper;
import com.ruoyi.service.TestUseCaseService;
import com.ruoyi.web.request.TestUseCaseByScenarioRequest;
import com.ruoyi.web.request.TestUseCaseIdListRequest;
import com.ruoyi.web.request.TestUserCaseRequest;
import com.ruoyi.web.response.TestUserCaseListResponse;
import com.ruoyi.web.response.UseCaseResponse;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author wangfei
* @description 针对表【t_test_usecase(测试用例)】的数据库操作Service实现
* @createDate 2024-02-18 13:41:28
*/
@Service
@Transactional
public class TestUseCaseServiceImpl extends ServiceImpl<TestUseCaseMapper, TestUseCase> implements TestUseCaseService{

    private String describeCaseList = "http://10.12.48.77:8090/DescribeCaseList";

    @Autowired
    private TestUseCaseMapper testUseCaseMapper;

    /**
     * 查询测试用例列表
     *
     * @param testUserCaseRequest 测试用例库
     * @return 测试用例集合
     */
    @Override
    public List<TestUseCase> selectseCaseList(TestUserCaseRequest testUserCaseRequest){
        if(testUserCaseRequest.getSearchKeywords() != null && (testUserCaseRequest.getSearchKeywords().contains("%") ||testUserCaseRequest.getSearchKeywords().contains("_")  )){
            testUserCaseRequest.setSearchKeywords(testUserCaseRequest.getSearchKeywords().toString().replaceAll("%","/%").replaceAll("_","/_"));
        }
        return testUseCaseMapper.selectseCaseList(testUserCaseRequest);
    }

    @Override
    public List<String> selectCaseIdList(TestUseCaseIdListRequest request) {
        List<TestUsecaseVO> list = testUseCaseMapper.selectListByTaskId(request.getModelTestId());
        return list.stream().map(TestUsecaseVO::getCaseId).collect(Collectors.toList());
    }

    /**
     * 通过测试场景获取所绑定的测试用例
     * @param request
     * @return
     */
    @Override
    public List<String> selectCaseByScenario(TestUseCaseByScenarioRequest request) {
        // 根据场景名遍历查询所绑定用例
        List<String> resultList = new ArrayList<>();
        request.getScenarioNameList()
                .forEach(scenarioName -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("scenario", scenarioName);
                    JSONObject jsonObject = callThirdPartyInterface(describeCaseList, map);
                    List<String> list = jsonObject.getList("case_list", CaseResultVO.class)
                            .stream().map(CaseResultVO::getId).collect(Collectors.toList());
                    resultList.addAll(list);
                });
        return resultList;
    }

    /**
     * 调用第三方接口
     * @param url
     * @param map
     * @return
     */
    @Override
    public JSONObject callThirdPartyInterface(String url, Map<String, Object> map) {
        String result = HttpUtil.post(url, JSONObject.toJSONString(map));
        return JSONObject.parseObject(result);
    }

    /**
     * 科恩获取测试用例
     * @param request
     * @return
     * @throws IOException
     */
    @Override
    public TestUserCaseListResponse getUseCaseList(String request) throws IOException {

        TestUserCaseListResponse userCaseResponse = new TestUserCaseListResponse();

        OkHttpClient client = new OkHttpClient().newBuilder().build();

        MediaType mediaType = MediaType.parse("application/json");

        // 创建请求体
        RequestBody body = RequestBody.create(mediaType, "{\"query\":\"query useCases($offset:OffsetConnectionInput$orderBy:OrderByInput$filter:Map$search:String$searchFields:Map){useCases(offset:$offset orderBy:$orderBy filterFields:$filter search:$search searchFields:$searchFields){nodes{id displayID class name description remediation requirements riskLevel method{name}scenario{name}}totalCount}}\",\"variables\":"+ request +"}");

        Request requestKE = new Request.Builder()
                .url("http://10.12.48.80:8089/api/query")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                // TODO 连接
                .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjAsInRva2VuaWQiOjYxLCJ0eXBlIjoiYXBpIiwidXNlcm5hbWUiOiJhZG1pbiJ9.48Ggjx-FtOcecf73vAHn0XglwgLXZlfXxhXiLDHWWQE")
//                .addHeader("Host", "10.12.48.80:8089")
//                .addHeader("Origin", "http://10.12.48.80:8089")
//                .addHeader("Referer", "http://10.12.48.80:8089/api/graphql/playground")
//                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();

        Response response = client.newCall(requestKE).execute();
        String string = response.body().string();
        JSONObject jsonObject = JSONObject.parseObject(string);
        // 获取测试用例
        List<UseCaseUrlVO> list = jsonObject.getJSONObject("data").getJSONObject("useCases").getList("nodes", UseCaseUrlVO.class);

        for (UseCaseUrlVO useCaseUrlVO : list) {
            if (useCaseUrlVO.getMethod() != null) {
                useCaseUrlVO.setTestMethod(useCaseUrlVO.getMethod().getName());
            }
            if (useCaseUrlVO.getScenario() != null) {
                useCaseUrlVO.setTestScenario(useCaseUrlVO.getScenario().getName());
            }
        }
        userCaseResponse.setUseCases(list);
        // 获取总条数
        Integer totalCount = (Integer) jsonObject.getJSONObject("data").getJSONObject("useCases").get("totalCount");
        userCaseResponse.setTotalCount(totalCount);

        return userCaseResponse;
    }

    /**
     * 科恩获取首页信息
     * @param request
     * @return
     * @throws IOException
     */
    @Override
    public UseCaseResponse getUseCaseMsg(String request) throws IOException {

        OkHttpClient client = new OkHttpClient().newBuilder().build();

        MediaType mediaType = MediaType.parse("application/json");

        RequestBody body = RequestBody.create(mediaType, "{\"query\":\"query regulationStatistics($name:String!){regulationStatistics:regulationByName(name:$name){id name description useCaseCount testMethodCount testScenarioCount useCases{fieldValuesWithCount(fields:[\\\"testType\\\" \\\"riskLevel\\\"])}}}\",\"variables\":"+request+"}");

        Request requestKE = new Request.Builder()
                .url("http://10.12.48.80:8089/api/query")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                // TODO 连接
                .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjAsInRva2VuaWQiOjYxLCJ0eXBlIjoiYXBpIiwidXNlcm5hbWUiOiJhZG1pbiJ9.48Ggjx-FtOcecf73vAHn0XglwgLXZlfXxhXiLDHWWQE")
//                .addHeader("Host", "10.12.48.80:8089")
//                .addHeader("Origin", "http://10.12.48.80:8089")
//                .addHeader("Referer", "http://10.12.48.80:8089/api/graphql/playground")
//                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();

        Response response = client.newCall(requestKE).execute();
        String string = response.body().string();
        JSONObject jsonObject = JSONObject.parseObject(string);

        UseCaseResponse caseResponse = jsonObject.getJSONObject("data").getObject("regulationStatistics",UseCaseResponse.class);

        List<CountVO> riskLevel = jsonObject.getJSONObject("data").getJSONObject("regulationStatistics").getJSONObject("useCases").getJSONObject("fieldValuesWithCount").getList("riskLevel",CountVO.class);

        List<CountVO> testType = jsonObject.getJSONObject("data").getJSONObject("regulationStatistics").getJSONObject("useCases").getJSONObject("fieldValuesWithCount").getList("testType",CountVO.class);

        caseResponse.setRiskLevel(riskLevel);
        caseResponse.setTestType(testType);

        return caseResponse;
    }

    /**
     * 科恩根据章节查询用例列表
     * @param request
     * @return
     * @throws IOException
     */
    @Override
    public List<UseCaseUrlVO> getUseCaseByChapter(String request) throws IOException {

        OkHttpClient client = new OkHttpClient().newBuilder().build();

        MediaType mediaType = MediaType.parse("application/json");

        RequestBody body = RequestBody.create(mediaType, "{\"query\":\"query regulationItemDetail($regulationItemID:ID!){node(id:$regulationItemID){...on RegulationItem{id serialNumber testMethod requirements useCases{id displayID name description scenario{name}method{name}}}}}\",\"variables\":"+request+"}");

        Request requestKE = new Request.Builder()
                .url("http://10.12.48.80:8089/api/query")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                // TODO 连接
                .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjAsInRva2VuaWQiOjYxLCJ0eXBlIjoiYXBpIiwidXNlcm5hbWUiOiJhZG1pbiJ9.48Ggjx-FtOcecf73vAHn0XglwgLXZlfXxhXiLDHWWQE")
//                .addHeader("Host", "10.12.48.80:8089")
//                .addHeader("Origin", "http://10.12.48.80:8089")
//                .addHeader("Referer", "http://10.12.48.80:8089/api/graphql/playground")
//                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();

        Response response = client.newCall(requestKE).execute();
        String string = response.body().string();
        JSONObject jsonObject = JSONObject.parseObject(string);

        // 获取测试用例
        List<UseCaseUrlVO> list = new ArrayList<>();
        if (jsonObject.getJSONObject("data").getJSONObject("node") != null) {
            list = jsonObject.getJSONObject("data").getJSONObject("node").getList("useCases", UseCaseUrlVO.class);

            for (UseCaseUrlVO useCaseUrlVO : list) {
                if (useCaseUrlVO.getMethod() != null) {
                    useCaseUrlVO.setTestMethod(useCaseUrlVO.getMethod().getName());
                }
                if (useCaseUrlVO.getScenario() != null) {
                    useCaseUrlVO.setTestScenario(useCaseUrlVO.getScenario().getName());
                }
            }
        }

        return list;
    }

    @Override
    public List<String> selectCaseListByScenario(String request) throws IOException {

        OkHttpClient client = new OkHttpClient().newBuilder().build();

        MediaType mediaType = MediaType.parse("application/json");

        // 创建请求体
        RequestBody body = RequestBody.create(mediaType, "{\"query\":\"query useCases($offset:OffsetConnectionInput$orderBy:OrderByInput$filter:Map$search:String$searchFields:Map){useCases(offset:$offset orderBy:$orderBy filterFields:$filter search:$search searchFields:$searchFields){nodes{id displayID class name description remediation requirements riskLevel method{name}scenario{name}}totalCount}}\",\"variables\":"+ request +"}");

        Request requestKE = new Request.Builder()
                .url("http://10.12.48.80:8089/api/query")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                // TODO 连接
                .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjAsInRva2VuaWQiOjYxLCJ0eXBlIjoiYXBpIiwidXNlcm5hbWUiOiJhZG1pbiJ9.48Ggjx-FtOcecf73vAHn0XglwgLXZlfXxhXiLDHWWQE")
//                .addHeader("Host", "10.12.48.80:8089")
//                .addHeader("Origin", "http://10.12.48.80:8089")
//                .addHeader("Referer", "http://10.12.48.80:8089/api/graphql/playground")
//                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();

        Response response = client.newCall(requestKE).execute();
        String string = response.body().string();
        JSONObject jsonObject = JSONObject.parseObject(string);
        // 获取测试用例

        return jsonObject.getJSONObject("data").getJSONObject("useCases").getJSONArray("nodes")
                .stream()
                .map(node -> ((JSONObject) node).getString("id"))
                .distinct()  // 去除重复项
                .collect(Collectors.toList());
    }


}