package com.td.Dawa.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.util.HashMap;
import java.util.Map;

/**
 * 瓦达工具类
 */
@Slf4j
@Component
public class WaDaNetUtil {

    private static String env;

    public static String getEnv() {
        return env;
    }

    @Value("${spring.profiles.active}")
    public void setEnv(String env) {
        WaDaNetUtil.env = env;
    }

    private static String waDaUrl;

    public static String getWaDaUrl() {
        return waDaUrl;
    }

    @Value("${meta-pal.url}")
    public void setWaDaUrl(String waDaUrl) {
        WaDaNetUtil.waDaUrl = waDaUrl;
    }

    /**
     * 通过该工厂类创建的RestTemplate发送请求时，可忽略https证书认证
     *
     * @return 工厂
     */
    private static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() throws Exception {
        TrustStrategy acceptingTrustStrategy = ((x509Certificates, authType) -> true);
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        return factory;
    }

    /**
     * 登录验证
     * {
     * "uuid":"xxxxxxxxx",    // 必需
     * "userName":"xxxx",    // 必需
     * "realName":"xxxx",
     * "email":"xxxxxx@xxxx.com",    // 必需
     * "telephone":null,
     * "birthday":null,
     * "sex":1,                // 0女1男
     * "accontStatus":0,            // 账号状态 0正常，1是禁止登录
     * "wallet": “xxxxxxxx”,    // 必需
     * "createTime":"2022.04.01-17.33.19",    // 必需
     * "updateTime":"2022.04.01-17.33.19",    // 最新一次对账号密码或其他信息的修改时间
     * }
     */
    public static Map MetaPalLogin(String userName, String password) {

        // 以 body json体传入
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode params = objectMapper.createObjectNode();
        params.put("username", userName);
        params.put("password", password);
        String DAppUrl = WaDaNetUtil.getWaDaUrl() + "/user/login";
        RestTemplate restTemplate = null;
        try {
            restTemplate = new RestTemplate(WaDaNetUtil.generateHttpRequestFactory());
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("unSSLRestTemplate bean创建失败，原因为：" + e.getMessage());
        }
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE);
        headers.setContentType(type);
        HttpEntity httpEntity = new HttpEntity<>(params.toString(), headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(DAppUrl, httpEntity, Map.class);
        //log.info("response2={}", response);
        if (response.getStatusCodeValue() == 200) {
            //log.info("response2={}", response.getBody());
            return response.getBody();
        } else {
            throw new RuntimeException("请求失败！状态：" + response.getStatusCodeValue() + ";信息：系统繁忙！请稍后重试！");
        }


    }

    /**
     * 获取用户直推数量（模块1：偷菜）
     * {
     * "code": 200,
     * "msg": "success",
     * "data": 0
     * }
     */
    public static Integer getChildrenCount(String userId) {

        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("id", userId);
        //验证地址
        //String DAppChildrenCountOnlineUrl = "https://yt.landownership.live/api/game/childrenCount";
        String DAppChildrenCountOnlineUrl = "http://192.168.20.251/api/game/childrenCount";
        String DAppChildrenCountTestUrl = "https://wp.landownership.live/api/game/childrenCount";
        String DAppUrl = WaDaNetUtil.getEnv().equals("prod") ? DAppChildrenCountOnlineUrl : DAppChildrenCountTestUrl;
        //log.info("用户直推数量地址：" + DAppUrl);
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //设置content-type
            MediaType type = MediaType.parseMediaType("multipart/form-data");
            headers.setContentType(type);
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //用HttpEntity封装整个请求报文

            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
            Map response = restTemplate.postForObject(DAppUrl, files, Map.class);
            //log.info("response={}", response);
            return (Integer) response.get("data");
        } catch (Exception e) {
            log.error(e.getMessage());
            return 0;
            //e.printStackTrace();
        }
    }

    /**
     * 根据村民ID找到所属村的cnt总支付和总兑换数量（模块4）
     * {
     * "code": 200,
     * "msg": "success",
     * "data": 0
     * }
     */
    public static Map getCntPayAndSwapAmount(String userId) {

        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("id", userId);
        //验证地址
        //String onlineUrl = "https://yt.landownership.live/api/game/cntPayAndSwapAmount";
        String onlineUrl = "http://192.168.20.251/api/game/cntPayAndSwapAmount";
        String testUrl = "https://wp.landownership.live/api/game/cntPayAndSwapAmount";
        String DAppUrl = WaDaNetUtil.getEnv().equals("prod") ? onlineUrl : testUrl;
        //log.info("根据村民ID找到所属村的cnt总支付和总兑换数量：" + DAppUrl);
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //设置content-type
            MediaType type = MediaType.parseMediaType("multipart/form-data");
            headers.setContentType(type);
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //用HttpEntity封装整个请求报文

            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
            Map response = restTemplate.postForObject(DAppUrl, files, Map.class);
            log.info("response={}", response);
            return response;
        } catch (Exception e) {
            log.error(e.getMessage());
            return new HashMap<>();
            //e.printStackTrace();
        }
    }

    /**
     * 获取用户直推且有消费土地的人数量（模块7： 放牧与养殖）
     * {
     * "code": 200,
     * "msg": "success",
     * "data": 0
     * }
     */
    public static Integer getChildrenBuyLandCount(String userId) {

        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("id", userId);
        //验证地址
        //String DAppChildrenCountOnlineUrl = "https://yt.landownership.live/api/game/getChildrenBuyLandCount";
        String DAppChildrenCountOnlineUrl = "http://192.168.20.251/api/game/getChildrenBuyLandCount";
        String DAppChildrenCountTestUrl = "https://wp.landownership.live/api/game/getChildrenBuyLandCount";
        String DAppUrl = WaDaNetUtil.getEnv().equals("prod") ? DAppChildrenCountOnlineUrl : DAppChildrenCountTestUrl;
        //log.info("获取用户直推且有消费土地的人数量：" + DAppUrl);
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //设置content-type
            MediaType type = MediaType.parseMediaType("multipart/form-data");
            headers.setContentType(type);
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //用HttpEntity封装整个请求报文

            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
            Map response = restTemplate.postForObject(DAppUrl, files, Map.class);
            //log.info("response={}", response);
            return (Integer) response.get("data");
        } catch (Exception e) {
            log.error(e.getMessage());
            return 0;
            //e.printStackTrace();
        }
    }

    /**
     * 获取用户直推下级的消费土地的总cnt数额（模块9： 积分兑换种子）
     * {
     * "code": 200,
     * "msg": "success",
     * "data": 0
     * }
     */
    public static Integer getChildrenBuyLandAmount(String userId) {

        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("id", userId);
        //验证地址
        //String DAppChildrenCountOnlineUrl = "https://yt.landownership.live/api/game/getChildrenBuyLandAmount";
        String DAppChildrenCountOnlineUrl = "http://192.168.20.251/api/game/getChildrenBuyLandAmount";
        String DAppChildrenCountTestUrl = "https://wp.landownership.live/api/game/getChildrenBuyLandAmount";
        String DAppUrl = WaDaNetUtil.getEnv().equals("prod") ? DAppChildrenCountOnlineUrl : DAppChildrenCountTestUrl;
        //log.info("获取用户直推下级的消费土地的总cnt数额：" + DAppUrl);
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //设置content-type
            MediaType type = MediaType.parseMediaType("multipart/form-data");
            headers.setContentType(type);
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //用HttpEntity封装整个请求报文

            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
            Map response = restTemplate.postForObject(DAppUrl, files, Map.class);
            //log.info("response={}", response);
            return (Integer) response.get("data");
        } catch (Exception e) {
            log.error(e.getMessage());
            return 0;
            //e.printStackTrace();
        }
    }

}
