package com.xiaomai.client;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.utils.*;
import org.springframework.util.StringUtils;
import org.testng.Assert;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class XMAppApi {


    private String path;
    private String host;
    private String url;
    private String apiName;
    @Deprecated
    private String env;
    private String apiModule;
    private String loginUser;
    private String apiDesc;
    private String requestParameterTemplate; // 接口入参模板
    private IdentityHashMap<String, String> api_request_params = new IdentityHashMap<String, String>();
    private String api_request_data;
    private Map<String, String> api_request_headers = null;
    private String api_response;
    private String api_traceId;

    public Long getApi_startTime() {
        return api_startTime;
    }

    public XMAppApi setApi_startTime(Long api_startTime) {
        this.api_startTime = api_startTime;
        return this;
    }

    public Long getApi_endTime() {
        return api_endTime;
    }

    public XMAppApi setApi_endTime(Long api_endTime) {
        this.api_endTime = api_endTime;
        return this;
    }

    private Long api_startTime;
    private Long api_endTime;
    private Long api_requestTime;
    private CommonRequestParameters loginInfo;
    private Map<String, String> headrs = new HashMap<>();
    private IdentityHashMap<String, String> params = new IdentityHashMap<>();
    private String dataJson = "";


    public CommonRequestParameters getLoginInfo() {
        this.loginInfo = CommonLoginInfo.getLoginUser(this.loginUser);
        return this.loginInfo;
    }


    public Long getApi_requestTime() {
        return api_requestTime;
    }

    public XMAppApi setApi_requestTime(Long api_requestTime) {
        this.api_requestTime = api_requestTime;
        return this;
    }

    public String getApiDesc() {
        return apiDesc;
    }

    public void setApiDesc(String apiDesc) {
        this.apiDesc = apiDesc;
    }

    public IdentityHashMap<String, String> getApi_request_params() {
        return api_request_params;
    }

    public String getApi_request_data() {
        return api_request_data;
    }

    public Map<String, String> getApi_request_headers() {
        return api_request_headers;
    }

    public String getApi_response() {
        return api_response;
    }

    public String getApi_traceId() {
        return api_traceId;
    }

    //  测试接口所属端位：B端，M端，C端
    private String terminal;

    public XMAppApi setApi_request_params(IdentityHashMap<String, String> api_request_params) {
        this.api_request_params = api_request_params;
        if (null != api_request_params) {
            System.out.println("===============================================\n");
            System.out.println("This is your request params ==> \n" + api_request_params);
            System.out.println("===============================================\n\n");
        }
        return this;
    }

    public XMAppApi setApi_request_data(String api_request_data) {
        this.api_request_data = api_request_data;
        if (!StringUtils.isEmpty(api_request_data)) {
            System.out.println("===============================================\n");
            System.out.println("This is your request json ==> \n" + api_request_data);
            System.out.println("===============================================\n\n");
        }
        return this;
    }

    public XMAppApi setApi_request_headers(Map<String, String> api_request_headers) {
        this.api_request_headers = api_request_headers;
        return this;
    }

    public XMAppApi setApi_response(String api_response) {
        this.api_response = api_response;
        return this;
    }

    public XMAppApi setApi_traceId(String api_traceId) {
        this.api_traceId = api_traceId;
        return this;
    }

    public String getTerminal() {
        return terminal;
    }

    public XMAppApi setTerminal(String terminal) {
        this.terminal = terminal;
        return this;
    }


    public String getPath() {
        return path;
    }

    public XMAppApi setPath(String path) {
        this.path = path;
        return this;
    }

    public String getHost() {
        return host;
    }

    public XMAppApi setHost(String host) {
        this.host = host;
        return this;
    }

    public String getUrl() {
        return url;
    }

    public XMAppApi setUrl(String url) {
        this.url = url;
        return this;
    }

    public String getApiName() {
        return apiName;
    }

    public XMAppApi setApiName(String apiName) {
        this.apiName = apiName;
        return this;
    }

    @Deprecated
    public String getEnv() {
        return env;
    }

    @Deprecated
    public XMAppApi setEnv(String env) {
        this.env = env;
        return this;
    }

    public String getApiModule() {
        return apiModule;
    }

    public XMAppApi setApiModule(String apiModule) {
        this.apiModule = apiModule;
        return this;
    }

    public String getLoginUser() {
        return loginUser;
    }

    public XMAppApi setLoginUser(String loginUser) {
        this.loginUser = loginUser;
        return this;
    }


    @Deprecated
    public void doPost(OkHttpClient okHttpClient, String url, IdentityHashMap<String, String> params, String json, HashMap<String, String> headers) {
//        计算请求开始时间
        Long start = System.currentTimeMillis();
        okHttpClient.doPostRequest(url, json, headers);
//        计算请求结束时间
        Long end = System.currentTimeMillis();
        JSONObject jsonBody = okHttpClient.getBodyInJSON();
        Map<String, String> head = okHttpClient.getHeaders();
        this.api_endTime = end;
        this.api_startTime = start;
        Long requestTime = end - start;
        this.api_requestTime = requestTime;
        this.api_traceId = head.get("traceId");
        this.api_request_data = json;
        this.api_request_params = params;
        this.api_request_headers = headers;
        this.api_response = jsonBody.toJSONString();
    }

    public XMAppApi doRequest(String requestType, HashMap<String, String> headers, String json) {
        doRequest(requestType, new IdentityHashMap<>(), json, headers);
        return this;
    }

    public XMAppApi doRequest(String requestType, HashMap<String, String> headers, JSONObject json) {
        doRequest(requestType, new IdentityHashMap<>(), json.toJSONString(), headers);
        return this;
    }

    public XMAppApi doRequest(String requestType, HashMap<String, String> headers, IdentityHashMap<String, String> params) {
        doRequest(requestType, params, "", headers);
        return this;
    }

    /**
     * @param requestType 请求类型
     * @param params      请求参数
     * @param json        请求发送的json 数据
     * @param headers     请求头
     */
    public XMAppApi doRequest(String requestType, IdentityHashMap<String, String> params, String json, HashMap<String, String> headers) {
        OkHttpClient okHttpClient = new OkHttpClient();

        Long start = System.currentTimeMillis();

        switch (requestType) {
            case "JSON":
                okHttpClient.doPostRequest(url, json, headers);
                break;
            case "PARAM":
                okHttpClient.doPostRequest(url, params, headers);
                break;
            case "FORM":
                okHttpClient.doPostForForm(url, params, headers);
                break;
            case "GET":
                okHttpClient.doGetRequest(url, params, headers);
                break;
        }
        Long end = System.currentTimeMillis();
        Map<String, String> head = okHttpClient.getHeaders();
        String response = okHttpClient.getBody();
        this.api_endTime = end;
        this.api_startTime = start;
        Long requestTime = end - start;
        this.api_requestTime = requestTime;
        this.api_response = response;
        this.api_traceId = head.get("traceId");
        this.setApi_request_data(json);
        this.setApi_request_params(params);
        this.api_request_headers = headers;
        return this;
    }

    /**
     * 简单success 结果断言
     *
     * @param flag
     */
    public void assetsSuccess(boolean flag, String... msg) {
        String msgStr = "请求结果校验失败";
        if (msg.length > 0) {
            msgStr = msg[0];
        }
        String success = XMJSONPath.readPath(this.api_response, "$.success");
        if (flag) {
            Assert.assertEquals(success, "true", msgStr);
        } else {
            Assert.assertEquals(success, "false", msgStr);
        }
    }

    public void assetsResultCode(boolean flag, String... msg) {
        String msgStr = "请求结果校验失败";
        if (msg.length > 0) {
            msgStr = msg[0];
        }
        String success = XMJSONPath.readPath(this.api_response, "$.resultCode");
        if (flag) {
            Assert.assertEquals(success, "0", msgStr);
        } else {
            Assert.assertNotEquals(success, "0", msgStr);
        }
    }
    //

    /**
     * 简单success 结果断言
     *
     * @param flag
     */
    public void assetsResultMsg(boolean flag, String... msg) {
        String msgStr = "请求结果校验失败";
        if (msg.length > 0) {
            msgStr = msg[0];
        }
        String success = XMJSONPath.readPath(this.api_response, "$.resultMsg");
        if (flag) {
            Assert.assertEquals(success, "成功", msgStr);
        } else {
            Assert.assertEquals(success, "失败", msgStr);
        }
    }

    /**
     * 以JSON格式获取到反馈的主体
     *
     * @return
     */
    public JSONObject getBodyInJSON(String... jsonPath) {
        JSONObject api_response_json = null;
        if (this.api_response != null) {
            try {
                api_response_json = JSONObject.parseObject(api_response);
                if (jsonPath.length > 0) {
                    api_response_json = XMJSONPath.getJSONObjectByReadPath(api_response, jsonPath[0]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return api_response_json;
    }

    /**
     * 以JSONArray格式获取到反馈的主体
     *
     * @return
     */
    public JSONArray getBodyInJSONArray(String jsonPath) {
        JSONArray api_response_json = null;
        if (this.api_response != null) {
            try {
                api_response_json = XMJSONPath.getJSONArrayByReadPath(api_response, jsonPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return api_response_json;
    }

    public String getBodyJSONValue(String jsonPath) {
        String api_response_json = null;
        if (this.api_response != null) {
            try {
                api_response_json = XMJSONPath.readPath(api_response, jsonPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return api_response_json;
    }



    public DataUserInfo getUserInfo() {
        DataUserInfo dataUserInfo = new DataUserInfo();
        dataUserInfo.setLoginUser(this.getLoginUser());
        dataUserInfo.setEnv(this.getEnv());
        return dataUserInfo;
    }


    public Map<String, String> getHeadrs() {
        return headrs;
    }

    public XMAppApi setHeadrs(Map<String, String> headrs) {
        this.headrs = headrs;
        return this;
    }

    public IdentityHashMap<String, String> getParams() {
        return params;
    }

    public XMAppApi setParams(IdentityHashMap<String, String> params) {
        this.params = params;
        return this;
    }

    public String getDataJson() {
        return dataJson;
    }

    public void setDataJson(String dataJson) {
        this.dataJson = dataJson;
    }

    public String getRequestParamterTemplate() {
        return requestParameterTemplate;
    }

    public void setRequestParamterTemplate(String requestParamterTemplate) {
        this.requestParameterTemplate = requestParamterTemplate;
    }

    public JSONObject getRequestParameterTemplateJSON() {
        JSONObject requestParamterTemplateJSON = JSONObject.parseObject(this.requestParameterTemplate);
//        requestParamterTemplateJSON.replace("bizAccountId", getLoginInfo().getAid());
//        requestParamterTemplateJSON.replace("instId", getLoginInfo().getInstId());
        requestParamterTemplateJSON.replace("objectId", RandomStringUtil.randomString(20));
        requestParamterTemplateJSON.replace("operationDate", TimeUtils.getCurrentTime());
        return requestParamterTemplateJSON;
    }

}
