package com.td.boss.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.td.boss.common.pojo.IpVo;
import lombok.extern.slf4j.Slf4j;
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.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * dapp工具类
 */
@Slf4j
@Component
public class DappUtil {

    private static String env;

    public static String getEnv() {
        return env;
    }

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

    /**
     * 获取用户直推数量（模块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 DAppChildrenCountTestUrl = "https://wp.landownership.live/api/game/childrenCount";
        String DAppUrl = DappUtil.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();
        }
    }



}
