package com.quantgroup.asset.distribution.util;

import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Created by renfeng on 2019/7/22.
 */
@Slf4j
public class DateUtil {

    public enum DateTimeUtilFormat {
        yyyyMMdd("yyyyMMdd"),
        yyyyMMddHHmm("yyyyMMddHHmm"),
        yyyyMMddHHmmss("yyyyMMddHHmmss"),
        yyyy_MM_dd("yyyy-MM-dd"),
        MM_dd("MM-dd"),
        yyyy_MM_dd_HH_mm("yyyy-MM-dd HH:mm"),
        yyyy_MM_dd_HH_mm_ss("yyyy-MM-dd HH:mm:ss"),
        yyyy_MM_dd_cn("yyyy年MM月dd日"),
        yyyy_MM("yyyy-MM"),
        MM_dd_HH_mm_cn("MM月dd日 HH:mm");
        String format;

        DateTimeUtilFormat(String format) {
            this.format = format;
        }
    }


    /**
     * 获取当前日期（天）
     * @return
     */
    public static String getDay(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(new Date());
    }
    
    /**
     * 获取当前时间 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getCurDateTime() {
    	return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
    }

    /**
     * 将时间类型字符串转换为Long类型
     * @param dateTime
     * @param pattern
     * @return
     */
    public static Long transStringToLong(String dateTime, String pattern) {
        return Timestamp.valueOf(LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern(pattern))).getTime();
    }

    /**
     * 获取格式化日期
     *
     * @param pattern
     * @param add
     * @return
     */
    public static String getStrFormatDate(String pattern, int add) {
        return LocalDateTime.now().plusDays(add).format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String timestamp2Str(String longmills, String pattern) {
        try {
            Timestamp ts = new Timestamp(Long.parseLong(longmills));
            return new SimpleDateFormat(pattern).format(ts);
        } catch (Exception e) {
            log.error("Timestamp转String异常,格式 : {}", pattern, e);
            return null;
        }
    }

    public static String toString(Date date, DateTimeUtilFormat dateTimeUtilFormat) {
        return new DateTime(date).toString(dateTimeUtilFormat.format);
    }

    public static DateTime toDateTime(String dateTime, DateTimeUtilFormat dateTimeUtilFormat) {
        return DateTimeFormat.forPattern(dateTimeUtilFormat.format).parseLocalDate(dateTime).toDateTimeAtStartOfDay();
    }
}
