package com.bcxin.Infrastructures.utils;

import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DateUtil {
    /*
    SimpleDateFormat是线程不安全的，不能采用这种方式,
    曾经使用Hibernate进行持久化的时候，使用静态的SimpleDateFormat.parse的日期竟然出现过: 202021-01-1这样的日期格式
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static Collection<SimpleDateFormat> shortDateFormats = new ArrayList<>();
    static {
        shortDateFormats.add(dateFormat);
        shortDateFormats.add(new SimpleDateFormat("yyyy.MM.dd"));
        shortDateFormats.add(new SimpleDateFormat("yyyy/MM/dd"));
    }

     */

    public static String format2ShortDate() {
        return (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
    }

    public static String format2ShortDate(Date date) {
        if (date == null) {
            return null;
        }

        return (new SimpleDateFormat("yyyy-MM-dd")).format(date);
    }


    public static String format2ShortDate(Date date,String format) {
        if (date == null) {
            return null;
        }

        return (new SimpleDateFormat(format)).format(date);
    }

    public static String format2ShortDateTime(Date date) {
        if (date == null) {
            return null;
        }

        return (new SimpleDateFormat("yyyyMMddHHmmss")).format(date);
    }

    public static Date fromString(String text) {
        if (!StringUtils.hasLength(text)) {
            return null;
        }

        text = text.replace(" ","");
        //for (String ii : Stream.of("yyyy-MM-dd", "yyyy.MM.dd", "yyyy/MM/dd").collect(Collectors.toList())) {
        for (String ii : Stream.of("-", "\\.", "/").collect(Collectors.toList())) {
            try {
                String[] splitItems = text.split(ii);
                if (splitItems.length == 3) {
                    String formattedText = String.format("%s-%s-%s", splitItems[0], leftString(splitItems[1], 2, "0"), leftString(splitItems[2], 2, "0"));
                    return new SimpleDateFormat("yyyy-MM-dd").parse(formattedText);
                }

                //return new SimpleDateFormat(ii).parse(text);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return null;
    }

    private static String leftString(String input,int length,String pad) {
        if (!StringUtils.hasLength(input)) {
            return null;
        }

        if (input.length() >= length) {
            return input;
        }

        return String.format("0%s", input);
    }
}
