package util

import (
	"errors"
	"ordonnance/common/auth"
	"strconv"
	"strings"
)

type TokenDsta struct {
	UserId      int   `json:"userId"`
	MilliSecond int64 `json:"milliSecond"`
	AreaId      int   `json:"areaId"`
	AuthFlg     int   `json:"authFlg"`
}

func ParseToken(tokenStr string) (*TokenDsta, error) {
	retErr := errors.New("parse token err")
	if len(tokenStr) < 1 {
		return nil, retErr
	}
	srcToken := auth.AesDecrypt(tokenStr)
	if len(srcToken) < 10 {
		return nil, retErr
	}
	srcSplic := strings.Split(srcToken, "|")
	if len(srcSplic) != 3 && len(srcSplic) != 4 {
		return nil, retErr
	}
	userId, err := strconv.ParseInt(srcSplic[0], 10, 64)
	if err != nil || userId < 1 {
		return nil, retErr
	}
	milliSecond, err := strconv.ParseInt(srcSplic[1], 10, 64)
	if err != nil || milliSecond < 1 {
		return nil, retErr
	}
	areaId, err := strconv.ParseInt(srcSplic[2], 10, 64)
	if err != nil {
		return nil, retErr
	}
	tokenData := &TokenDsta{
		UserId:      int(userId),
		MilliSecond: milliSecond,
		AreaId:      int(areaId),
	}
	if len(srcSplic) == 4 {
		tokenData.AuthFlg, _ = strconv.Atoi(srcSplic[3])
	}
	return tokenData, nil
}
