package com.xhkjedu.sapi.utils;

import com.xhkjedu.sapi.config.ConfigKey;
import com.xhkjedu.utils.N_Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.xhkjedu.utils.N_Utils.getSecondTimestamp;

/**
 * @ClassName ApiUtil
 * Description api工具类
 * Author WN
 * Date 2022/2/21 11:08
 **/
@Slf4j
public class ApiUtil {
    public static Integer id = 0;
    public static Map<String, String> uriMap = new ConcurrentHashMap<>();

    // 获取id
    public static synchronized String getId() {
        Integer nummin = ConfigKey.nummin;
        Integer nummax = ConfigKey.nummax;
        if (id == 0 || id.equals(nummax)) {
            id = nummin;
        } else {
            id++;
        }
        String _num = (getSecondTimestamp() + ConfigKey.numadd) + "" + id;
        long num = Long.parseLong(_num);
        return Long.toString(num, 36).toUpperCase();
    }

    /**
     * 发送form-data请求返回json结果
     *
     * @return java.lang.String
     * @Param [apiUrl, param]
     * @Author ywx
     * @Date 2021/5/14 17:41
     **/
    public static String sendFormData(String apiUrl, MultiValueMap<String, String> param) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            List<MediaType> acceptableMediaTypes = new ArrayList<>();
            acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
            acceptableMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
            HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(param, headers);
            ResponseEntity<String> response = new RestTemplate().postForEntity(apiUrl, requestParams, String.class);
            String result = response.getBody();
            return result;
        } catch (RestClientException e) {
            log.error("发送form-data请求失败", e.getMessage());
            return null;
        }
    }

    /*
     * @Description 比较当前时间和时间段
     * @Author WN
     * @Date 2023/6/15 11:24:59
     */
    public static boolean compareCurrDateTime(String starttimeStr, String stoptimeStr) throws Exception {
        boolean rtn = false;
        if (N_Utils.isEmpty(starttimeStr) || N_Utils.isEmpty(stoptimeStr)) {
            rtn = false;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");

            Date starttime = sdf.parse(starttimeStr); // 开始时间
            Date stoptime = sdf.parse(stoptimeStr); // 结束时间

            Date nowtime = new Date();
            String times = sdf.format(nowtime);
            Date currtime = sdf.parse(times);// 当前时间

            // 当前时间在开始时间之前或者等于开始时间  并且 当前时间在结束时间之后或者等于结束时间
            if ((starttime.before(currtime) || starttime.equals(currtime)) && (stoptime.after(currtime) || stoptime.equals(currtime))) {
                rtn = true;
            }
        }

        return rtn;
    }

    /*
     * @Description 获取当前时间所在周的开始时间和结束时间
     * @Date 2024/7/22 10:33:54
     * @Author WN
     * @Param []
     * @Return long[]
     **/
    public static long[] getNowWeekOfTimestamp() {
        LocalDate now = LocalDate.now();
        LocalDate startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

        long starttimestamp = startOfWeek.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();

        LocalDateTime dateTime = endOfWeek.atTime(23, 59, 59);
        long endtimestamp = dateTime.atZone(ZoneId.systemDefault()).toEpochSecond();

        long[] rtnTimestamp = new long[2];
        rtnTimestamp[0] = starttimestamp / 1000;
        rtnTimestamp[1] = endtimestamp;
        return rtnTimestamp;
    }

    /*
     * @Description 获取当前时间以及半年前时间
     * @Date 2024/7/23 9:15:21
     * @Author WN
     * @Param []
     * @Return long[]
     **/
    public static long[] getNowhalfYearTimestamp() {
        LocalDate today = LocalDate.now(); // 获取当前日期
        LocalDate halfYearAgo = today.minus(6, ChronoUnit.MONTHS); // 当前日期往前推6个月

        long starttimestamp = halfYearAgo.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
        LocalDateTime dateTime = today.atTime(23, 59, 59);

        long endtimestamp = dateTime.atZone(ZoneId.systemDefault()).toEpochSecond();

        long[] rtnTimestamp = new long[2];
        rtnTimestamp[0] = starttimestamp / 1000;
        rtnTimestamp[1] = endtimestamp;

        return rtnTimestamp;
    }

    /*
     * @Description 获取时间戳对应年月日
     * @Date 2024/7/22 12:18:23
     * @Author WN
     * @Param [timestamp]
     * @Return java.time.LocalDate
     **/
    public static LocalDate getLocalDateByStamp(Integer timestamp) {
        // 使用时间戳构建Instant
        Instant instant = Instant.ofEpochSecond(timestamp);

        // 转换为ZoneId的时间
        LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        return localDate;
    }

    public static void main(String[] args) {
        LocalDate today = LocalDate.now(); // 获取当前日期
        LocalDate halfYearAgo = today.minus(6, ChronoUnit.MONTHS); // 当前日期往前推6个月
        System.out.println("半年前的日期是: " + halfYearAgo);
    }

}
