package com.fufan.mtsaas.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.fufan.mtsaas.constant.UDIBizConstant;
import com.fufan.mtsaas.modules.base.intflog.service.IntfLogUtil;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.tools.AESTool;
import com.fufan.mtsaas.util.HttpConnPoolUtil;
import com.fufan.mtsaas.util.JSonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class CodeApi {
    public static String ip = "http://124.220.103.126:7001";
    public static void getCodeResult(JSONObject js) {
        List<String> resultList = new ArrayList<>();
        String packageCode = "";
        try {
            packageCode = getCodeData(js);
            String url = ip + "/api/Data/DownLoad?fileCode=" + packageCode;
            String result = executeGet("getCodeData", url);
            resultList = Arrays.asList(result.split("\r\n"));

        }catch (Exception e){

        }
    }

    public static String getCodeData(JSONObject js) {
//        js.put("qty", "2");
//        js.put("dataType", "2");
        js.put("facNo", "");
        js.put("sku", "");
        js.put("orderNo", "");
        js.put("batchNo", "");
        js.put("supplierNo", "");
        js.put("InUrl", "");
        js.put("outUrl", "");
        String url = ip + "/api/Data/GetData";
        String result = executePost("getCodeData", js.toJSONString(), url, "local", String.valueOf(System.currentTimeMillis()), new RequestPojo(), js.toJSONString());
       JSONObject json = JSONObject.parseObject(result);
        return json.getJSONObject("value").getString("fileCode");
    }

    public static void main(String[] args) {
        getCodeResult(new JSONObject());

    }

    /**
     * 统一发送POST请求
     *
     * @param type   请求类型(下单/撤单/查询订单)
     * @param params 参数
     * @param url    请求地址
     * @return response
     */
    public static String executePost(String type, String params, String url, String remoteServer, String key, RequestPojo requestPojo, String orignalRequestMsg) {
        String DEFAULT_USER = "";
        String DEFAULT_PASS = "";
        String orignalResponseMsg = "";
        Page page = new Page();

        int responseCode = 0;
        String result = "";
        try {
            String requestUrl = url;
            HttpPost post = new HttpPost(requestUrl);
            post.addHeader("Content-Type", "application/json");
            post.setEntity((new StringEntity(params, "UTF-8")));


            if(StringUtils.isNotEmpty(DEFAULT_USER) && StringUtils.isNotEmpty(DEFAULT_PASS)) {
                String enc = DEFAULT_USER + ":" + DEFAULT_PASS;
                post.addHeader("Authorization", "Basic " + Base64Utils.encodeToString(enc.getBytes(StandardCharsets.UTF_8)));
                log.info("用户密码：" + enc);
            }
            // 发送请求日志
            log.info("准备查询 " + type + " :" + requestUrl);
            CloseableHttpResponse response = HttpConnPoolUtil.getHttpClient().execute(post);
//            CloseableHttpResponse response = HttpConnPoolUtil.getHttpClient().execute(post, context);

            responseCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            //写入通讯日志
            String respStatus = "S";
            if(responseCode != 200){
                respStatus = "E";
            }

            try{
            JSONObject respObjective = JSonUtil.toBean(result, JSONObject.class);
                if(Objects.nonNull(respObjective.getJSONObject("resData"))) {
                    page = respObjective.getJSONObject("resData").toJavaObject(Page.class);
                    orignalResponseMsg = AESTool.decrypt(page.getRecords().get(0).toString());
                }
            }catch (Exception e){
                log.error("解密失败 {}", e.getLocalizedMessage());
            }

            IntfLogUtil.processLog(UDIBizConstant.UDISAASPLATFORM, remoteServer, respStatus, params, result, result, "客户",
                    type, key, requestPojo, orignalRequestMsg, orignalResponseMsg, url);
            return result;
        } catch (Exception e) {
            log.error(" " + type + ", 响应码:" + responseCode + ", 响应内容:" + result + ", 请求内容:" + params.toString());
            log.error(" 异常", e);
            log.info(" 响应码:" + responseCode + ", 响应内容:" + result + ", 请求内容:" + url);
            log.info(" 异常", e);
            result = "ERR: 请求 " + url + ", 异常：" + e.getLocalizedMessage();
            //写入通讯日志
            IntfLogUtil.processLog(UDIBizConstant.UDISAASPLATFORM, remoteServer, "S", params, result, result, "客户",
                    type, key, requestPojo, orignalRequestMsg, orignalResponseMsg, url);
        }

        return result;
    }

    /**
     * 试验方法 basic Authorization
     * @param username
     * @param password
     * @param params
     * @throws Exception
     */
    public static void test(String username, String password, String params) throws Exception  {

//            HttpClient httpClient = HttpClientBuilder.create().build();
//            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
//            httpClient.getState().setCredentials(AuthScope.ANY, creds);

        HttpHost target = new HttpHost("yx-po-dev.yuexiu.com", 51001, "https");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(username, password));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider).build();
        try {

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            // Generate BASIC scheme object and add it to the local
            // auth cache
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);

            // Add AuthCache to the execution context
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            HttpPost httpPost = new HttpPost("https://yx-po-dev.yuexiu.com:51001/RESTAdapter/BC_YX_SP_HSNFFC/SI_E1216_MATERIAL_QUERY_OUT_SYN");
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.setEntity((new StringEntity(params, "UTF-8")));
            //System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);

            CloseableHttpResponse response = httpclient.execute(target, httpPost, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }





    /**
     * 统一发送GET请求
     *
     * @param url 请求地址
     * @return response
     */
    public static String executeGet(String type, String url) {
        int responseCode = 0;
        String result = "";
        String requestUrl = "";
        try {
            requestUrl = url;
            HttpGet get = new HttpGet(requestUrl);
            log.info("准备查询BIAN " + type + " :" + requestUrl);
            CloseableHttpResponse response = HttpConnPoolUtil.getHttpClient().execute(get);
            responseCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            return result;
        } catch (Exception e) {
            log.error("BIAN 查询响应码:" + responseCode + ", 响应内容:" + result + ", 请求内容:" + url);
            log.error("BIAN 查询异常", e);
        } finally {
            log.info("查询BIAN " + type + ", 响应码:" + responseCode + ", 响应内容:" + result + ", 请求内容:" + requestUrl);
        }
        return null;
    }
}
