package events

import (
	"fmt"
	"os"
	"bufio"
	"io"
	"time"
	"strings"
	// "log"

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

var RetainedDays = []int{2,3,4,5,6,7,14,30}
func is_match_retained_day(day int) bool {
	for _, v := range RetainedDays {
		if v == day {
			return true
		}
	}
	return false
}

func Retained_get_day_name(day int) string {
	if day == 2 {
		return "次留"
	}
	return fmt.Sprintf("%d留", day)
}

// 日留存分布
func Retaied_get_day_count(date string , serverId string) map[int]int {
	var rdCount = make(map[int]int)
	var playerRegisterDays = make(map[int]int)
	
	f, err := os.Open(fmt.Sprintf("%s/login-%s.log", utils.GetKeyConf("events", "path"), date))
	if err != nil {
		return rdCount
	}
	defer f.Close()
	
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", date + " 00:00:00", loc)
	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 {
			uid := utils.StringToInt(arr[2])
			arrCnt := strings.Split(arr[3], ",")
			registeTime := utils.StringToInt(arrCnt[0])
			currTime := int(theTime.Unix())
			registeDay := utils.GetDiffDays(registeTime, currTime) + 1
			playerRegisterDays[uid] = registeDay
		}
	}
	// log.Printf("Retaied_get_day_count date[%s] playerRegisterDays[%v]", date, playerRegisterDays)

	// 留存分布
	for _, v := range RetainedDays {
		rdCount[v] = 0
	}
	for _, v := range playerRegisterDays {
		if is_match_retained_day(v) {
			rdCount[v] ++
		}
	}
	return rdCount
}

// 过往留存
func Retained_get_range_count(days int, serverId string) ([]*tgSeries, []string) {
	var arrCate []string
	var mRdCount = make(map[int][]int)
	currTime := time.Now()
	d, _ := time.ParseDuration("-24h")
	startTime := int(currTime.Add(d * time.Duration(days)).Unix())
	dayCount := 0
	for {
		tiEvent := startTime + 86400*dayCount
		date := time.Unix(int64(tiEvent), 0).Format("2006-01-02")

		arrCate = append(arrCate, date)

		mDayCount := Retaied_get_day_count(date, serverId)
		for _, v := range RetainedDays {
			mRdCount[v] = append(mRdCount[v], mDayCount[v])
		}

		dayCount ++
		if dayCount > days {
			break
		}
	}
	
	var series []*tgSeries
	for k, v := range mRdCount {
		item := &tgSeries{}
		item.Name = Retained_get_day_name(k)
		item.Data = v
		
		series = append(series, item)
	}

	return series, arrCate
}

// 保存文件
func Save_retained_records(series []*tgSeries, arrCate []string, 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.Data {
			if v > 0 {
				row = sheet.AddRow()
				row.AddCell().SetString(item.Name)
				row.AddCell().SetString(arrCate[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
}