package com.izouma.nineth.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

public class DateTimeUtils {
    public static final String DATE_TIME_FORMAT   = "yyyy-MM-dd HH:mm";
    public static final String T_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
    public static final String DATE_FORMAT        = "yyyy-MM-dd";

    public static LocalDate toLocalDate(long ts) {
        if (String.valueOf(ts).length() > 10) {
            return LocalDate.from(Instant.ofEpochMilli(ts));
        } else {
            return LocalDate.from(Instant.ofEpochSecond(ts));
        }
    }

    public static LocalDateTime toLocalDateTime(long ts) {
        if (String.valueOf(ts).length() > 10) {
            return LocalDateTime.from(Instant.ofEpochMilli(ts));
        } else {
            return LocalDateTime.from(Instant.ofEpochSecond(ts));
        }
    }

    public static LocalDate toLocalDate(String str, String fmt) {
        return LocalDate.from(DateTimeFormatter.ofPattern(fmt).parse(str));
    }

    public static LocalDateTime toLocalDateTime(String str, String fmt) {
        return LocalDateTime.from(DateTimeFormatter.ofPattern(fmt).parse(str));
    }

    public static String format(TemporalAccessor temporal, String fmt) {
        return DateTimeFormatter.ofPattern(fmt).format(temporal);
    }

    public static long toTimestamp(TemporalAccessor temporal) {
        return Instant.from(temporal).toEpochMilli();
    }

    public static boolean isWorkDay(LocalDate date) {
        try {
            HttpRequest request = HttpRequest.get("https://jiejiari.market.alicloudapi.com/queryHoliday?day="
                            + date.format(DateTimeFormatter.ofPattern("yyyyMMdd")))
                    .header("Authorization", "APPCODE b48bc8f6759345a79ae20a951f03dabe");
            int code = request.code();
            if (code == 200) {
                String body = request.body();
                JSONObject res = JSON.parseObject(body);
                System.out.println(JSON.toJSONString(res, true));
                if (res.getInteger("showapi_res_code") == 0) {
                    JSONObject resBody = res.getJSONObject("showapi_res_body");
                    return StringUtils.equals(resBody.getString("type"), "1");
                }
            } else {
                System.out.println(code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
