package util

import (
	"strings"
	"time"
)

var bjlocation *time.Location

func init() {
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		bjlocation = time.FixedZone("CST", 8*3600)
	} else {
		bjlocation = loc
	}
}

func Unix2Time(sec int64) string {
	return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
}

func MlNow() time.Time {
	return time.Now().In(bjlocation)
}

func MlParseTime(strTime string) (time.Time, error) {
	if strings.Contains(strTime, ".") {
		return time.ParseInLocation("2006-01-02 15:04:05.000", strTime, bjlocation)
	}
	return time.ParseInLocation("2006-01-02 15:04:05", strTime, bjlocation)
}

func MlParseTimeX(layout, strTime string) (time.Time, error) {
	return time.ParseInLocation(layout, strTime, bjlocation)
}

type MLTime time.Time

const (
	timeFormart = "2006-01-02 15:04:05"
)

func (t *MLTime) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), bjlocation)
	*t = MLTime(now)
	return
}

func (t MLTime) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(timeFormart)+2)
	b = append(b, '"')
	tt := time.Time(t)
	if !tt.IsZero() {
		b = tt.AppendFormat(b, timeFormart)
	}
	b = append(b, '"')
	return b, nil
}

func (t MLTime) String() string {
	tt := time.Time(t)
	if tt.IsZero() {
		return ""
	}
	return tt.Format(timeFormart)
}

type MLTimeEx time.Time

const (
	timeFormartEx = "2006-01-02 15:04:05.000"
)

func (t *MLTimeEx) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+timeFormartEx+`"`, string(data), bjlocation)
	*t = MLTimeEx(now)
	return
}

func (t MLTimeEx) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(timeFormartEx)+2)
	b = append(b, '"')
	tt := time.Time(t)
	if !tt.IsZero() {
		b = tt.AppendFormat(b, timeFormartEx)
	}
	b = append(b, '"')
	return b, nil
}

func (t MLTimeEx) String() string {
	tt := time.Time(t)
	if tt.IsZero() {
		return ""
	}
	return tt.Format(timeFormartEx)
}
