package com.muyu.cloud.mart.utils;

import com.muyu.domain.Birthday;
import com.muyu.domain.res.BirthdayRes;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author：chaiyapeng
 * @Package：com.muyu.cloud.mart.utils
 * @Project：cloud-mart
 * @name：BirthdayHelper
 * @Date：2024/8/24 19:36
 * 生辰助手
 */
public class BirthdayHelper {

    public static String API_URL = "http://apis.juhe.cn/birthEight/query";
    // 接口请求Key
    public static String API_KEY = "9bbfc46233d4931c39207b090ed4b27c";


    public static Birthday queryBirthday(BirthdayRes birthdayRes){
//        String apiKey = "9bbfc46233d4931c39207b090ed4b27c";
//        String apiUrl = "http://apis.juhe.cn/birthEight/query";
        HashMap<String, Object> map = new HashMap<>();

        map.put("key", API_KEY);
        map.put("year", birthdayRes.getYear());
        map.put("month", birthdayRes.getMonth());
        map.put("day", birthdayRes.getDay());
        map.put("hour", birthdayRes.getHour());
        String urlencode = urlencode(map);

        Birthday birthday1 = new Birthday();
        String s = doGet(API_URL, urlencode);
        try {
            JSONObject jsonObject = JSONObject.fromObject(s);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0){
                System.out.println("调用接口成功");
                JSONObject result = jsonObject.getJSONObject("result");

                birthday1.setYears(result.getString("year"));
                birthday1.setMonths(result.getString("month"));
                birthday1.setDays(result.getString("day"));
                birthday1.setAnimal(result.getString("Animal"));
                birthday1.setImonthcn(result.getString("ImonthCn"));
                birthday1.setIdaycn(result.getString("IDayCn"));
                birthday1.setCyear(result.getString("cYear"));
                birthday1.setCmonth(result.getString("cMonth"));
                birthday1.setCday(result.getString("cDay"));
                birthday1.setGzyear(result.getString("gzYear"));
                birthday1.setGzmonth(result.getString("gzMonth"));
                birthday1.setGzday(result.getString("gzDay"));
                birthday1.setIsleap(result.getString("isLeap"));
                birthday1.setNcweek(result.getString("ncWeek"));
                birthday1.setIsterm(result.getString("isTerm"));
                birthday1.setTerm(result.getString("Term"));
                birthday1.setAstro(result.getString("astro"));
                birthday1.setEightall(result.getString("eightAll"));
                birthday1.setFiveall(result.getString("fiveAll"));

                System.out.printf("year：%s%n", result.getString("year"));
                System.out.printf("month：%s%n", result.getString("month"));
                System.out.printf("day：%s%n", result.getString("day"));
                System.out.printf("Animal：%s%n", result.getString("Animal"));
                System.out.printf("ImonthCn：%s%n", result.getString("ImonthCn"));
                System.out.printf("IDayCn：%s%n", result.getString("IDayCn"));
                System.out.printf("cYear：%s%n", result.getString("cYear"));
                System.out.printf("cMonth：%s%n", result.getString("cMonth"));
                System.out.printf("cDay：%s%n", result.getString("cDay"));
                System.out.printf("gzYear：%s%n", result.getString("gzYear"));
                System.out.printf("gzMonth：%s%n", result.getString("gzMonth"));
                System.out.printf("gzDay：%s%n", result.getString("gzDay"));
                System.out.printf("isLeap：%s%n", result.getString("isLeap"));
                System.out.printf("ncWeek：%s%n", result.getString("ncWeek"));
                System.out.printf("isTerm：%s%n", result.getString("isTerm"));
                System.out.printf("Term：%s%n", result.getString("Term"));
                System.out.printf("astro：%s%n", result.getString("astro"));
                System.out.printf("eightAll：%s%n", result.getString("eightAll"));
                System.out.printf("fiveAll：%s%n", result.getString("fiveAll"));
            } else {
                System.out.println("调用接口失败：" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return birthday1;
    }


    public static String doGet(String httpUrl, String queryParams) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString());
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
                connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(5000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(6000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流，并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }

    /**
     * 将map型转为请求参数型
     *
     * @param data
     * @return
     */
    public static String urlencode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?    > i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }
}
