package events

import (
	"fmt"
	"os"
	"bufio"
	"io"
	"strings"

	"box-gm/utils"
	"time"
	"github.com/tealeg/xlsx"
	"github.com/astaxie/beego"
	// "log"
)

type tgSeries struct {
	Name	string
	Data	[]int
	MapCount	map[int]int
}

// 关卡分布
func GameLevel_get_day_level_count(date string, serverId string) (map[int]int, int) {
	var glCount = make(map[int]int)
	var playerLevel = make(map[int]int)
	
	fName := fmt.Sprintf("%s/event-%s.log", utils.GetKeyConf("events", "path"), date)
	f, err := os.Open(fName)
	if err != nil {
		return glCount, 0
	}
	defer f.Close()
	
	buff := bufio.NewReader(f)
	maxLevel := 0
	for {
		line, err := buff.ReadString('\n')

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

		arr := strings.Split(line, ";")
		if arr[3] == "battle-settle" {
			if serverId == "0" || arr[1] == serverId {
				uid := utils.StringToInt(arr[2])
				arrCnt := strings.Split(arr[4], ",")
				level := utils.StringToInt(arrCnt[0])
				status := utils.StringToInt(arrCnt[1])
				if status == 2 {
					// 通关
					playerLevel[uid] = level
				}else{
					playerLevel[uid] = level - 1
				}
				if playerLevel[uid] > maxLevel {
					maxLevel = playerLevel[uid]
				}
			}
		}
	}

	// 关卡分布
	for _, v := range playerLevel {
		glCount[v] ++
	}
	return glCount, maxLevel
}

func GameLevel_get_range_day_level_count(days int, serverId string) ([]*tgSeries, []string) {
	var series []*tgSeries
	currTime := int(time.Now().Unix())
	dayCount := 0
	maxCategories := 0
	for {
		tiEvent := currTime - 86400*dayCount
		date := time.Unix(int64(tiEvent), 0).Format("2006-01-02")
		item := &tgSeries{}
		item.Name = date
		glCount, maxLevel := GameLevel_get_day_level_count(date, serverId)
		for i:=0; i < maxLevel + 5; i++ {
			item.Data = append(item.Data, glCount[i])
		}
		if maxLevel > maxCategories {
			maxCategories = maxLevel
		}
		item.MapCount = glCount
		// log.Printf("item[%v]", item)
		series = append(series, item)

		dayCount ++
		if dayCount > days {
			break
		}
	}
	var arrCate []string
	for i:=0; i < maxCategories + 5; i++ {
		arrCate = append(arrCate, fmt.Sprintf("%d", i))
	}
	return series, arrCate
}

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

	file = xlsx.NewFile()
	sheet, err = file.AddSheet("关卡分布")
	if err != nil {
		beego.Warn(err)
		return ""
	}

	row = sheet.AddRow()
	row.AddCell().Value = "日期"
	row.AddCell().Value = "关卡"
	row.AddCell().Value = "人数"

	for i := 0; i < len(series); i++ {
		item := series[i]
		for k, v := range item.MapCount {
			row = sheet.AddRow()
			row.AddCell().SetString(item.Name)
			row.AddCell().SetInt(k)
			row.AddCell().SetInt(v)
		}
	}

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

	return name
}