package org.matrix.autotest.swaggerData.swaggerController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.autotest.swaggerData.swaggerEntity.InterfaceInformation;
import org.matrix.autotest.swaggerData.swaggerEntity.Parameter;
import org.matrix.database.entity.Environment;
import org.matrix.database.service.IEnvironmentService;
import org.matrix.exception.GlobalException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author mry
 */
@RestController
@RequestMapping("/swaggers")
@CrossOrigin
@Api(tags = "Swagger接口读取与解析")
public class SwaggerController {

    private final IEnvironmentService service;

    public SwaggerController(IEnvironmentService service) {
        this.service = service;
    }

    public String loadJson(String url) {
        BufferedReader reader;
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            InputStream inputStream = uc.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                json.append(inputLine);
            }
            reader.close();
        } catch (IOException e) {
            throw new GlobalException("请求swagger数据失败");
        }
        return json.toString();
    }

    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "快速添加接口")
    public List<InterfaceInformation> parameter(Long projectId, Long id) {
        service.setIsDefaultByWrapper(false,
                Wrappers.lambdaQuery(Environment.class).eq(Environment::getProjectId, projectId));
        service.setIsDefaultByWrapper(true,
                Wrappers.lambdaQuery(Environment.class).eq(Environment::getId, id));
        Environment environment = service.getById(id);
        String url = String.format("%s/v2/api-docs", environment.getIp());
        //获得json字符串
        String json = loadJson(url);
        JSONObject swaggerJson = JSONObject.parseObject(json);
        //localhost:8765
        Object host = swaggerJson.get("host");
        //"/"
        Object basePath = swaggerJson.get("basePath");
        Object paths = swaggerJson.get("paths");
        //将paths转成map集合
        @SuppressWarnings(value = "unchecked")
        Map<String, String> pathsMaps = (Map<String, String>) paths;
        //获取key
        Set<String> methodUrls = pathsMaps.keySet();
        List<InterfaceInformation> list = new ArrayList<>();
        //循环获取每个methodUrl
        for (String methodUrl : methodUrls) {
            //将paths转成JSON
            JSONObject objPaths = (JSONObject) paths;
            //通过JSON获取到methodUrl,用来获取methodUrl内部的信息
            Object objMethodUrls = objPaths.get(methodUrl);
            JSONObject objUrlsJson = (JSONObject) objMethodUrls;
            @SuppressWarnings(value = "unchecked")
            Map<String, String> objMethodUrlsMaps = (Map<String, String>) objMethodUrls;
            Set<String> requests = objMethodUrlsMaps.keySet();
            for (String request : requests) {
                //拿到请求内部的信息
                Object objRequest = objUrlsJson.get(request);
                @SuppressWarnings(value = "unchecked")
                Map<String, String> objRequestMaps = (Map<String, String>) objRequest;
                Object parameters = objRequestMaps.get("parameters");
                Object tags = objRequestMaps.get("tags");
                Object summary = objRequestMaps.get("summary");
                List<Parameter> parameterAllList = new ArrayList<>();
                if (parameters != null) {
                    @SuppressWarnings(value = "all")
                    List<String> parameterLists = (List<String>) parameters;
                    Parameter parameter = new Parameter();
                    InterfaceInformation interfaceInformation = new InterfaceInformation();
                    for (Object parameterList : parameterLists) {
                        @SuppressWarnings(value = "unchecked")
                        Map<String, String> parameterMaps = (Map<String, String>) parameterList;
                        //传参格式
                        parameter.setIn(parameterMaps.get("in"));
                        //拿到参数名称
                        parameter.setName(parameterMaps.get("name"));
                        //拿到参数类型
                        parameter.setType(parameterMaps.get("type"));
                        parameterAllList.add(parameter);
                    }
                    interfaceInformation.setHost(String.valueOf(host));
                    interfaceInformation.setParameterAllList(parameterAllList);
                    interfaceInformation.setBasePath(String.valueOf(basePath));
                    interfaceInformation.setRequest(request);
                    interfaceInformation.setSummary(String.valueOf(summary));
                    interfaceInformation.setMethodUrl(methodUrl);
                    interfaceInformation.setTags(String.valueOf(tags));
                    list.add(interfaceInformation);
                }
            }
        }
        return list;
    }

}
