package protocol

import (
	"fmt"
	"github.com/valyala/bytebufferpool"
	"strconv"
	"time"
)

// 认证登录 (这里设置了默认心跳时间为60s)
func (x AuthDataPack) AuthLogin() *bytebufferpool.ByteBuffer {
	buf := bytebufferpool.Get()
	x.Head = []byte{0xFE, 0x5C, 0x4B, 0x89}
	x.Len = []byte{0x2A, 0x00, 0x00, 0x00}
	x.Type = 0x62
	x.Id = []byte{0x00, 0x00, 0x00, 0x00}
	x.DataLen = []byte{0x17, 0x00, 0x00, 0x00}
	x.Result = 0x31
	x.Separator1 = 0x23
	x.Separator2 = 0x23
	x.HeartBeat = []byte{0x30, 0x36, 0x30} //默认060， 60秒发一次心跳
	x.EndSeparator = 0x23
	x.End = []byte{0xFF, 0xFF}
	buf.Write(x.Head)
	buf.Write(x.Len)
	buf.WriteByte(x.Type)
	buf.Write(x.Id)
	buf.Write(x.DataLen)
	buf.WriteByte(x.Result)
	buf.WriteByte(x.Separator1)

	slice := GetNowDate()
	TmpData := make([]byte, len(slice))
	for i, s := range slice {
		TmpData[i] = byte(s) + 0x30
	}
	x.Time = TmpData
	buf.Write(x.Time)
	buf.WriteByte(x.Separator2)
	buf.Write(x.HeartBeat)
	buf.WriteByte(x.EndSeparator)
	buf.Write(x.End)
	//fmt.Println("TmpData: ", hex.EncodeToString(buf.Bytes()))
	//fmt.Println("TmpData: ", buf.Bytes())
	return buf
}

func GetNowDate() (dateSlice [16]int) {
	now := time.Now()
	year, month, day := now.Date()
	hour, minute, second := now.Clock()
	weekday := int(now.Weekday()) // 0表示星期天，1表示星期一，依此类推
	if weekday == 0 {
		weekday = 7 // 将星期天设为07
	}
	// 格式化
	Y := fmt.Sprintf("%d", year)
	M := fmt.Sprintf("%02d", month)    // 将月份转换为两位数字
	D := fmt.Sprintf("%02d", day)      // 将日期转换为两位数字
	H := fmt.Sprintf("%02d", hour)     // 将小时转换为两位数字
	Min := fmt.Sprintf("%02d", minute) // 将分钟转换为两位数字
	S := fmt.Sprintf("%02d", second)   // 将秒数转换为两位数字
	W := fmt.Sprintf("%02d", weekday)  // 将星期几转换为两位数字

	dateStr := Y + M + D + W + H + Min + S
	for i, _ := range dateStr {
		num, _ := strconv.Atoi(string(dateStr[i]))
		dateSlice[i] = num
	}
	return dateSlice
}
