package events

import (
	"bufio"
	"fmt"
	"box-gm/utils"
	"io"
	"math"
	"os"
	"strings"

	"time"

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

func Online_get_day_time_count(date string, minutes int, serverId string) (map[int]int, int) {
	var timeCount = make(map[int]int)
	f, err := os.Open(fmt.Sprintf("%s/onlinecnt-%s.log", utils.GetKeyConf("events", "path"), date))
	if err != nil {
		return timeCount, 0
	}
	defer f.Close()

	startTime := utils.GetTime(date + " 00:00:00")

	buff := bufio.NewReader(f)
	for {
		line, err := buff.ReadString('\n')

		if err != nil || io.EOF == err {
			break
		}
		line = strings.TrimSpace(line)

		arr := strings.Split(line, ";")
		if serverId == "0" || arr[1] == serverId {
			eventTime := utils.GetTime(arr[0])
			if utils.GetDiffDays(eventTime, startTime) != 0 {
				continue
			}

			sec := eventTime - startTime
			sec = int(math.Floor(float64(sec) / float64(minutes*60)))
			count := utils.StringToInt(arr[2])
			if count > timeCount[sec] {
				timeCount[sec] = count
			}
		}
	}

	cutTime := utils.GetTime(time.Now().Format("2006-01-02 15:04:05"))
	curSec := cutTime - startTime
	curSec = int(math.Floor(float64(curSec) / float64(minutes*60)))

	return timeCount, timeCount[curSec]
}

func Online_get_range_day_time_count(days, minutes int, serverId string) (series []*tgSeries, arrCate []string, curCount int) {
	series = make([]*tgSeries, 0)
	currTime := int(time.Now().Unix())
	dayCount := 0
	curCount = 0
	t := 24 * 60 / minutes
	for {
		tiEvent := currTime - 86400*dayCount
		date := time.Unix(int64(tiEvent), 0).Format("2006-01-02")
		// m, _ := time.ParseDuration("1m")

		item := &tgSeries{}
		item.Name = date
		glCount, count := Online_get_day_time_count(date, minutes, serverId)
		if utils.GetDiffDays(currTime, tiEvent) == 0 { //当前在线
			curCount = count
		}
		for i := 0; i < t; i++ {
			item.Data = append(item.Data, glCount[i])
		}
		item.MapCount = glCount
		// log.Printf("item[%v]", item)
		series = append(series, item)
		dayCount++
		if dayCount > days {
			break
		}
	}

	arrCate = make([]string, 0)
	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 < t; i++ {
		ti := theTime.Add(time.Minute * time.Duration(minutes) * time.Duration(i))
		arrCate = append(arrCate, fmt.Sprintf("%02d:%02d:%02d", ti.Hour(), ti.Minute(), ti.Second()))
	}
	return series, arrCate, curCount
}

// 保存文件
func Save_rtonline_records(series []*tgSeries, minutes int, 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(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 * time.Duration(minutes) * 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
}
