package events

import (
	"fmt"
	"os"
	"time"

	"github.com/astaxie/beego"
	"github.com/tealeg/xlsx"
)

func RtLogin_get_range_day_time_count(serverId string) ([]*tgSeries, []string) {
	var series []*tgSeries

	date := time.Now().Format("2006-01-02")
	item := &tgSeries{}
	glCount, totalCount := Login_get_day_time_count(date, serverId)
	item.Name = date + fmt.Sprintf(" 活跃人数:%d", totalCount)
	for i := 0; i < 289; i++ {
		item.Data = append(item.Data, glCount[i])
	}
	item.MapCount = glCount
	series = append(series, item)
	// log.Printf("login date[%s] item[%v]", date, item)

	var arrCate []string
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", time.Now().Format("2006-01-02")+" 00:00:00", loc)
	for i := 0; i < 289; i++ {
		ti := theTime.Add(time.Minute * 5 * time.Duration(i))
		arrCate = append(arrCate, fmt.Sprintf("%02d:%02d:%02d", ti.Hour(), ti.Minute(), ti.Second()))
	}
	return series, arrCate
}

// 保存文件
func Save_rtlogin_records(series []*tgSeries, user string) string {
	var file *xlsx.File
	var sheet *xlsx.Sheet
	var row *xlsx.Row
	var err error

	file = xlsx.NewFile()
	date := time.Now().Format("2006-01-02")
	sheet, err = file.AddSheet(fmt.Sprintf("%s实时登录分布", date))
	if err != nil {
		beego.Warn(err)
		return ""
	}

	row = sheet.AddRow()
	row.AddCell().Value = "时间"
	row.AddCell().Value = "人数"

	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", date+" 00:00:00", loc)
	for i := 0; i < len(series); i++ {
		item := series[i]
		for k, v := range item.MapCount {
			row = sheet.AddRow()
			ti := theTime.Add(time.Minute * 5 * time.Duration(k))
			row.AddCell().SetString(fmt.Sprintf("%02d:%02d:%02d", ti.Hour(), ti.Minute(), ti.Second()))
			row.AddCell().SetInt(v)
		}
	}

	name := fmt.Sprintf("./static/统计-实时登录-%s-%s.xlsx", user, date)
	os.Remove(name)
	err = file.Save(name)
	if err != nil {
		beego.Warn(err)
		return ""
	}

	return name
}
