package com.ozs.mdm.controller;

import com.alibaba.fastjson.JSONObject;
import com.ozs.mdm.dto.*;
import com.ozs.mdm.service.InterfaceDataSourcesService;
import com.ozs.mdm.service.util.ReturnUtil;
import com.ozs.mdm.util.R;
import com.ozs.mdm.util.S;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = { "数据中心-接口数据源管理" })
@RestController
public class InterfaceDataSourceManagementController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private InterfaceDataSourcesService interfaceDataSourcesService;

    @ApiOperation(value = "数据源管理查询列表（分页）", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "methodName", value = "请求方式（下拉列表）", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态（下拉列表）", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "projectName", value = "所属接口分类（下拉列表）", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, paramType = "query", dataType = "String") ,
            @ApiImplicitParam(name = "sort", value = "排序字段", dataType = "String", paramType = "query", required = false,defaultValue = "update_time"),
            @ApiImplicitParam(name = "order", value = "排序方式", dataType = "String", paramType = "query", required = false, defaultValue = "DESC"),
    })

    @GetMapping("/mdm/interfaceDataSources/listInterfaceDataSources")
    public R<List<MdmInfoDataSourceInterfaceDTO>> listInterfaceDataSources(@RequestParam(name="methodName",required = false) String methodName,
                                                                           @RequestParam(name="status",required = false) String status,
                                                                           @RequestParam(name="projectName",required = false) String projectName,
                                                                           @RequestParam(required = false, defaultValue = "1") Integer page,
                                                                           @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                                           @RequestParam(name = "sort", required = false,defaultValue = "update_time") String sort,
                                                                           @RequestParam(name = "order", required = false, defaultValue = "DESC") String order
                                                            ) {
        try {

            return interfaceDataSourcesService.listInterfaceDataSources(methodName, status,projectName, sort, order, page, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR, e.getMessage());
        }
    }

    @ApiOperation( value = "数据源管理单条数据源详细信息查看", notes = "详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceId", value = "接口id",
                    dataType = "String", paramType = "path",
                    required = true),
    })
    @GetMapping(value = "/mdm/interfaceDataSources/getInterfaceDataSourcesById/{interfaceId}", produces = "application/json;charset=UTF-8")
    public R<MdmInfoDataSourceInterfaceVO> getInterfaceDataSourcesById(@PathVariable(name = "interfaceId") String interfaceId) {
        try {
            R<MdmInfoDataSourceInterfaceVO> r = new R<>();
            if (null == interfaceId && interfaceId.equals("")) {
                return new R("-1", "interfaceId不能为空");
            }
            r.setData(interfaceDataSourcesService.getInterfaceDataSourcesById(interfaceId));
            return r;
        } catch (Exception e) {
            log.error("查看详细信息异常,{}", e);
            return ReturnUtil.createExceptionReturn(e);
        }
    }

    @ApiOperation( value = "数据源管理单条数据源信息新增", notes = "新增")
    @PostMapping(value = "/mdm/interfaceDataSources/addInterfaceDataSources", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8")
    public R<String> addInterfaceDataSources(@RequestBody @ApiParam MdmInfoDataSourceInterfaceVO mdmInfoDataSourceInterfaceVO) {
        try {

            return interfaceDataSourcesService.addInterfaceDataSources(mdmInfoDataSourceInterfaceVO);

        } catch (Exception e) {
            log.error("添加接口信息异常==>" + e.getMessage());
            return ReturnUtil.createExceptionReturn(e);
        }
    }

    @ApiOperation(value = "数据源管理单条数据源信息修改", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceId", value = "interfaceId",
                    dataType = "String", paramType = "path",
                    required = true),
    })
    @PutMapping(value = "/mdm/interfaceDataSources/updateInterfaceDataSourcesById/{interfaceId}", produces = "application/json;charset=UTF-8")
    public R updateInterfaceDataSourcesById(
            @PathVariable(name = "interfaceId") String interfaceId,
            @ApiParam @RequestBody MdmInfoDataSourceInterfaceVO mdmInfoDataSourceInterfaceVO) {
        R r = new R();
        if (null == interfaceId && interfaceId.equals("")) {
            return new R("-1", "interfaceId不能为空");
        }
        try {
            mdmInfoDataSourceInterfaceVO.setInterfaceId(interfaceId);
            interfaceDataSourcesService.updateInterfaceDataSourcesById(mdmInfoDataSourceInterfaceVO);
            return r;
        } catch (Exception e) {
            log.error(e.getMessage());
            r.setCode("-1");
            r.setMsg(e.getMessage());
            return r;
        }

    }



    @ApiOperation(value = "数据源管理单条数据源详细信息测试", notes = "测试信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceId", value = "接口id", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "interfaceUrl", value = "接口地址", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "methodName", value = "请求方式", dataType = "String", paramType = "query", required = false),
    })
    @GetMapping(value = "/mdm/interfaceDataSources/testInterfaceDataSources", produces = "application/json;charset=UTF-8")
    public JSONObject testInterfaceDataSources(@RequestParam(name="interfaceId",required = false) String interfaceId,
                                               @RequestParam(name="interfaceUrl",required = false) String interfaceUrl,
                                               @RequestParam(name="methodName",required = false) String methodName
                                                                 ) {

        //get传参
        Map<String, String> params = new HashMap<>();
        params.put("checkcode", "datau001");


        HttpHeaders headers = new HttpHeaders();
        headers.set("checkcode","datau001");
        HttpEntity httpEntity = new HttpEntity(headers);

        String strJson="{\n" +
                "  \"checkCode\": \"datau001\",\n" +
                "  \"projectName\": \"dataTest\"\n" +
                "}";
        //下面是把拿到的json字符串转成 json对象
        JSONObject jsStr = JSONObject.parseObject(strJson);
        ResponseEntity<JSONObject> a = null;

        RestTemplate restTemplate = new RestTemplate();
        //测试
        if (StringUtils.isNotEmpty(interfaceId) &&  StringUtils.isEmpty(interfaceUrl)&& StringUtils.isEmpty(methodName)){
            try {

                String url = interfaceDataSourcesService.getInterfaceUrlById(interfaceId);
                methodName = interfaceDataSourcesService.getinterfaceMethodById(interfaceId);

                if (methodName.equals("GET")){
                    a= restTemplate.getForEntity(url,JSONObject.class,httpEntity,params);
                    return a.getBody();

                }else if (methodName.equals("POST")){

                    a = restTemplate.postForEntity(url,jsStr,JSONObject.class);
                    return a.getBody();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (StringUtils.isEmpty(interfaceId) && StringUtils.isNotEmpty(interfaceUrl) && StringUtils.isNotEmpty(methodName)){
            //新增
            if (methodName.equals("GET")){
                a= restTemplate.getForEntity(interfaceUrl,JSONObject.class,httpEntity,params);
                return a.getBody();

            }else if (methodName.equals("POST")){
                a = restTemplate.postForEntity(interfaceUrl,jsStr,JSONObject.class);
                return a.getBody();
            }

        } else if (StringUtils.isNotEmpty(interfaceId) && StringUtils.isNotEmpty(interfaceUrl) && StringUtils.isNotEmpty(methodName)){
            //修改
            if (methodName.equals("GET")){
                a= restTemplate.getForEntity(interfaceUrl,JSONObject.class,httpEntity,params);
                return a.getBody();

            }else if (methodName.equals("POST")){
                a= restTemplate.postForEntity(interfaceUrl,jsStr,JSONObject.class);
                return a.getBody();

            }
        }
        return a.getBody();
    }





    @ApiOperation( value = "数据源管理单条数据源信息删除", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceId", value = "接口id",
                    dataType = "String", paramType = "path",
                    required = true),
    })
    @DeleteMapping(value = "/mdm/interfaceDataSources/deleteInterfaceDataSources/{interfaceId}", produces = "application/json;charset=UTF-8")
    public R deleteInterfaceDataSources(@PathVariable(name = "interfaceId") String interfaceId) {
        try {
            R r = new R();
            if (null == interfaceId && interfaceId.equals("")) {
                return new R("-1", "接口id不能为空");
            }
            interfaceDataSourcesService.deleteInterfaceDataSources(interfaceId);
            return r;
        } catch (Exception e) {
            log.error("删除接口信息异常,{}", e.getMessage());
            return ReturnUtil.createExceptionReturn(e);
        }
    }

    @ApiOperation( value = "数据源管理单条数据源信息接口状态修改", notes = "修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceId", value = "接口id",
                    dataType = "String", paramType = "path",
                    required = true),
    })
    @PutMapping(value = "/mdm/interfaceDataSources/updateInterfaceDataSourcesStatus/{interfaceId}", produces = "application/json;charset=UTF-8")
    public R updateInterfaceDataSourcesStatus(@PathVariable("interfaceId") String interfaceId,
                                              @ApiParam @RequestBody MdmInfoDataSourceInterfaceDTO mdsid) {
        R r = new R<>();
        try {

            mdsid.setInterfaceId(interfaceId);
            this.interfaceDataSourcesService.updateInterfaceDataSourcesStatus(mdsid);
            return r;
        } catch (Exception e) {
            log.error("修改状态,{}", e.getMessage());
            r.setCode("-1");
            r.setMsg("修改状态失败!");
            return r;
        }
    }

    @ApiOperation(value = "数据源管理单条数据源信息接口请求方式查询", notes = "查询")
    @GetMapping("/mdm/interfaceDataSources/listRequestMode")
    public R<List<MdmDimDataSourceInterfaceMethodDTO>> listRequestMode(
    ) {

        try {
            return interfaceDataSourcesService.listRequestMode();
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR, e.getMessage());
        }
    }

    @ApiOperation(value = "数据源管理单条数据源信息接口状态查询查询", notes = "查询")
    @GetMapping("/mdm/interfaceDataSources/listInterfaceDataSourcesStatus")
    public R<List<MdmDimDataSourceInterfaceStatusDTO>> listInterfaceDataSourcesStatus(
    ) {

        try {
            return interfaceDataSourcesService.listInterfaceDataSourcesStatus();
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR, e.getMessage());
        }
    }

    @ApiOperation(value = "数据源管理接口名称信息查询", notes = "查询")
    @GetMapping("/mdm/interfaceDataSources/listInterfaceName")
    public R<List<MdmInfoDataSourceInterfaceVO>> listInterfaceName(
    ) {

        try {
            return interfaceDataSourcesService.listInterfaceName();
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR, e.getMessage());
        }
    }

    @ApiOperation( value = "数据源管理根据接口分类id查询接口", notes = "详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "接口分类id",
                    dataType = "String", paramType = "path",
                    required = true),
    })
    @GetMapping(value = "/mdm/interfaceDataSources/getInterfaceProjectByInterfaceId/{projectId}", produces = "application/json;charset=UTF-8")
    public R<List<MdmInfoDataSourceInterfaceVO>> getInterfaceByProjectId(@PathVariable(name = "projectId") String projectId) {
        try {
            R<MdmInfoDataSourceInterfaceVO> r = new R<>();
            if (null == projectId && projectId.equals("")) {
                return new R("-1", "projectId不能为空");
            }

            return interfaceDataSourcesService.getInterfaceByProjectId(projectId);
        } catch (Exception e) {
            log.error("查询接口信息异常,{}", e);
            return ReturnUtil.createExceptionReturn(e);
        }
    }

    @ApiOperation( value = "数据源管理根据接口id查询接口参数查询", notes = "详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceId", value = "接口id",
                    dataType = "String", paramType = "path",
                    required = true),
    })
    @GetMapping(value = "/mdm/interfaceDataSources/getInterfaceOutParamsByInterfaceId/{interfaceId}", produces = "application/json;charset=UTF-8")
    public R<List<MdmInfoDataSourceInterfaceParamOutDTO>> getInterfaceOutParamsByInterfaceId(@PathVariable(name = "interfaceId") String interfaceId) {
        try {
            R<MdmInfoDataSourceInterfaceParamOutDTO> r = new R<>();
            if (null == interfaceId && interfaceId.equals("")) {
                return new R("-1", "interfaceId不能为空");
            }
            return interfaceDataSourcesService.getInterfaceOutParamsByInterfaceId(interfaceId);


        } catch (Exception e) {
            log.error("查看接口出参信息异常,{}", e);
            return ReturnUtil.createExceptionReturn(e);
        }
    }


    @ApiOperation(value = "数据源管理接口分类接口树", notes = "查询")
    @GetMapping("/mdm/interfaceDataSources/listProjectAndInterfaceTree")
    public R<List<MdmTreeDTO>> listProjectAndInterfaceTree(
    ) {

        try {
            return interfaceDataSourcesService.listProjectAndInterfaceTree();
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR, e.getMessage());
        }
    }




}
