package utils

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
)

func StrToTime(s string) (int64, error) {
	// delete all not int characters
	if s == "" {
		return time.Now().Unix(), nil
	}
	r := make([]rune, 14)
	l := 0
	// 过滤除数字以外的字符
	for _, v := range s {
		if '0' <= v && v <= '9' {
			r[l] = v
			l++
			if l == 14 {
				break
			}
		}
	}
	for l < 14 {
		r[l] = '0' // 补0
		l++
	}
	t, err := time.Parse("20060102150405", string(r))
	if err != nil {
		return 0, err
	}
	return t.Unix(), nil
}

func TimeToStr(unixSecTime interface{}, layout ...string) string {
	i := AnyToInt64(unixSecTime)
	if i == 0 {
		return ""
	}
	f := "2006-01-02 15:04:05"
	if len(layout) > 0 {
		f = layout[0]
	}
	return time.Unix(i, 0).Format(f)
}

func FormatNanoUnix() string {
	return strings.Replace(time.Now().Format("20060102150405.0000000"), ".", "", 1)
}

func TimeParse(format, src string) (time.Time, error) {
	return time.ParseInLocation(format, src, time.Local)
}

func TimeParseStd(src string) time.Time {
	t, _ := TimeParse("2006-01-02 15:04:05", src)
	return t
}

func TimeStdParseUnix(src string) int64 {
	t, err := TimeParse("2006-01-02 15:04:05", src)
	if err != nil {
		return 0
	}
	return t.Unix()
}

// 获取一个当前时间 时间间隔 时间戳
func GetTimeInterval(unit string, amount int) (startTime, endTime int64) {
	t := time.Now()
	nowTime := t.Unix()
	tmpTime := int64(0)
	switch unit {
	case "years":
		tmpTime = time.Date(t.Year()+amount, t.Month(), t.Day(), t.Hour(), 0, 0, 0, t.Location()).Unix()
	case "months":
		tmpTime = time.Date(t.Year(), t.Month()+time.Month(amount), t.Day(), t.Hour(), 0, 0, 0, t.Location()).Unix()
	case "days":
		tmpTime = time.Date(t.Year(), t.Month(), t.Day()+amount, t.Hour(), 0, 0, 0, t.Location()).Unix()
	case "hours":
		tmpTime = time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+amount, 0, 0, 0, t.Location()).Unix()
	}
	if amount > 0 {
		startTime = nowTime
		endTime = tmpTime
	} else {
		startTime = tmpTime
		endTime = nowTime
	}
	return
}

// 几天前
func TimeInterval(newTime int) string {
	now := time.Now().Unix()
	newTime64 := AnyToInt64(newTime)
	if newTime64 >= now {
		return "刚刚"
	}
	interval := now - newTime64
	switch {
	case interval < 60:
		return AnyToString(interval) + "秒前"
	case interval < 60*60:
		return AnyToString(interval/60) + "分前"
	case interval < 60*60*24:
		return AnyToString(interval/60/60) + "小时前"
	case interval < 60*60*24*30:
		return AnyToString(interval/60/60/24) + "天前"
	case interval < 60*60*24*30*12:
		return AnyToString(interval/60/60/24/30) + "月前"
	default:
		return AnyToString(interval/60/60/24/30/12) + "年前"
	}
}

// 时分秒字符串转时间戳，传入示例：8:40 or 8:40:10
func HmsToUnix(str string) (int64, error) {
	t := time.Now()
	arr := strings.Split(str, ":")
	if len(arr) < 2 {
		return 0, errors.New("Time format error")
	}
	h, _ := strconv.Atoi(arr[0])
	m, _ := strconv.Atoi(arr[1])
	s := 0
	if len(arr) == 3 {
		s, _ = strconv.Atoi(arr[3])
	}
	formatted1 := fmt.Sprintf("%d%02d%02d%02d%02d%02d", t.Year(), t.Month(), t.Day(), h, m, s)
	res, err := time.ParseInLocation("20060102150405", formatted1, time.Local)
	if err != nil {
		return 0, err
	} else {
		return res.Unix(), nil
	}
}

// 获取特定时间范围
func GetTimeRange(s string) map[string]int64 {
	t := time.Now()
	var stime, etime time.Time
	switch s {
	case "today":
		stime = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
		etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location())
	case "yesterday":
		stime = time.Date(t.Year(), t.Month(), t.Day()-1, 0, 0, 0, 0, t.Location())
		etime = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
	case "within_seven_days":
		// 明天 0点
		etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location())
		stime = time.Unix(etime.Unix()-7*86400, 0)

	case "within_fifteen_days":
		// 明天 0点
		etime = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location())
		// 前14天0点
		stime = time.Unix(etime.Unix()-15*86400, 0)
	case "current_month":
		stime = GetFirstDateOfMonth(t)
		etime = time.Now()
	case "last_month":
		etime = GetFirstDateOfMonth(t)
		monthTimes := TimeStdParseUnix(etime.Format("2006-01-02 15:04:05")) - 86400
		times, _ := UnixToTime(Int64ToStr(monthTimes))
		stime = GetFirstDateOfMonth(times)
	}

	return map[string]int64{
		"start": stime.Unix(),
		"end":   etime.Unix(),
	}
}

/**
获取本周周一的日期
*/
func GetFirstDateOfWeek() (weekMonday string) {
	now := time.Now()

	offset := int(time.Monday - now.Weekday())
	if offset > 0 {
		offset = -6
	}

	weekStartDate := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
	weekMonday = weekStartDate.Format("2006-01-02")
	return
}

/**
获取上周的周一日期
*/
func GetLastWeekFirstDate() (weekMonday string) {
	thisWeekMonday := GetFirstDateOfWeek()
	TimeMonday, _ := time.Parse("2006-01-02", thisWeekMonday)
	lastWeekMonday := TimeMonday.AddDate(0, 0, -7)
	weekMonday = lastWeekMonday.Format("2006-01-02")
	return
}

//时间戳转时间格式
func UnixToTime(e string) (datatime time.Time, err error) {
	data, err := strconv.ParseInt(e, 10, 64)
	datatime = time.Unix(data, 0)
	return
}

//获取传入的时间所在月份的第一天，即某月第一天的0点。如传入time.Now(), 返回当前月份的第一天0点时间。
func GetFirstDateOfMonth(d time.Time) time.Time {
	d = d.AddDate(0, 0, -d.Day()+1)
	return GetZeroTime(d)
}

//获取传入的时间所在月份的最后一天，即某月最后一天的0点。如传入time.Now(), 返回当前月份的最后一天0点时间。
func GetLastDateOfMonth(d time.Time) time.Time {
	return GetFirstDateOfMonth(d).AddDate(0, 1, -1)
}

//获取某一天的0点时间
func GetZeroTime(d time.Time) time.Time {
	return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
}

//获取当月某天的某个时间的时间
func GetDayToTime(day, timeStr string) string {
	if timeStr == "" {
		timeStr = "00:00:00"
	}
	year := time.Now().Year()
	month := time.Now().Format("01")
	times := fmt.Sprintf("%s-%s-%s %s", IntToStr(year), month, day, timeStr)
	return times
}
