
package org.tio.sitexxx.service.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.tio.sitexxx.service.vo.Const;

import java.util.Date;
import java.util.Objects;

/**
 * 周期工具类
 * @author xufei
 */
public class PeriodUtils {

	/**
	 * 周期转换
	 * @param date
	 * @param periodType
	 * @return
	 * @author xufei
	 */
	public static String dateToPeriodByType(Date date, short periodType) {
		if (periodType == Const.PeriodType.TOTAL) {
			return Const.PeriodType.TOTAL_PERIOD;
		}
		String periodFormat = "yyyyMMdd";
		if (Objects.equals(periodType, Const.PeriodType.YEAR)) {
			periodFormat = periodFormat.substring(0, 4);
		} else if (Objects.equals(periodType, Const.PeriodType.MONTH)) {
			periodFormat = periodFormat.substring(0, 6);
		} else if (Objects.equals(periodType, Const.PeriodType.WEEK)) {
			date = DateUtil.beginOfWeek(date);
		} else if (Objects.equals(periodType, Const.PeriodType.QUARTER)) {
			date = DateUtil.beginOfQuarter(date);
		} else if (Objects.equals(periodType, Const.PeriodType.HOUR)) {
			periodFormat = "HH";
		} else if (Objects.equals(periodType, Const.PeriodType.TIME)) {
			periodFormat = "HH:mm";
		}
		String period = DateUtil.format(date, periodFormat);
		if (Objects.equals(periodType, Const.PeriodType.WEEK)) {
			period += "W";
		} else if (Objects.equals(periodType, Const.PeriodType.QUARTER)) {
			period += "Q";
		}

		return period;
	}

	/**
	 * 根据周期转换时间
	 * @param period
	 * @return
	 * @author xufei
	 */
	public static DateTime getDateByPeriod(String period) {
		int length = period.length();
		if (length == 5) {
			return new DateTime();
		}
		if (period.contains("W")) {
			period = period.substring(0, period.length() - 1);
		}
		if (period.contains("Q")) {
			period = period.substring(0, period.length() - 1);
		}
		if (period.length() == 4) {
			period = period + "0101";
		}
		if (period.length() == 6) {
			period = period + "01";
		}

		if (period.length() == 10) {
			period = period + "0000";
		}
		return DateUtil.parse(period);
	}
}
