package events

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

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

type RecordResource struct {
	EventTime   string
	Uid         int
	Event       string
	ItemId      int
	DeltaCount  int
	RemainCount int
}

// 关卡分布
func Resource_get_records(uid, startTime, endTime, itemId int) []*RecordResource {
	// log.Printf("Resource_get_records uid[%d] startTime[%d] endTime[%d] itemId[%d]", uid, startTime, endTime, itemId)
	// 日期列表
	var dateList []string
	times := 0
	for {
		ti := startTime + times*86400
		date := time.Unix(int64(ti), 0).Format("2006-01-02")
		dateList = append(dateList, date)
		times++
		if ti >= endTime {
			break
		}
	}
	// log.Printf("Resource_get_records dateList[%v]", dateList)

	var records []*RecordResource
	loc, _ := time.LoadLocation("Local")
	for _, date := range dateList {
		records = read_date_by_type(uid, startTime, endTime, itemId, "resource", date, loc, records)
		records = read_date_by_type(uid, startTime, endTime, itemId, "item", date, loc, records)
	}

	// log.Printf("Resource_get_records records[%v]", records)
	return records
}

func read_date_by_type(uid, startTime, endTime, itemId int, dateType, date string, loc *time.Location, records []*RecordResource) []*RecordResource {
	if records == nil {
		records = make([]*RecordResource, 0)
	}

	eventFile := fmt.Sprintf("%s/%s-%s.log", utils.GetKeyConf("events", "path"), dateType, date)
	f, err := os.Open(eventFile)
	if err != nil {
		log.Printf("eventFile[%s] err[%v]", eventFile, err)
	}
	defer f.Close()
	if err == nil {
		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, ";")
			uidEvent := utils.StringToInt(arr[2])
			if uid == 0 || uid == uidEvent {
				theTime, errTime := time.ParseInLocation("2006-01-02 15:04:05", arr[0], loc)
				if errTime == nil {
					ti := int(theTime.Unix())
					arrCnt := strings.Split(arr[4], ",")
					if ti >= startTime && ti <= endTime {
						_itemId := utils.StringToInt(arrCnt[0])
						if itemId == 0 || itemId == _itemId {
							item := &RecordResource{}
							item.EventTime = arr[0]
							item.Uid = uidEvent
							item.Event = arr[3]
							item.ItemId = _itemId
							item.DeltaCount = utils.StringToInt(arrCnt[1])
							item.RemainCount = utils.StringToInt(arrCnt[2])

							records = append(records, item)
						}
					}
				}
			}
		}
	}
	return records
}

// 保存文件
func Save_resource_records(records []*RecordResource, 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 = "玩家ID"
	row.AddCell().Value = "事件ID"
	row.AddCell().Value = "资源ID"
	row.AddCell().Value = "变化数量"
	row.AddCell().Value = "变化后剩余数量"

	for i := 0; i < len(records); i++ {
		item := records[i]
		row = sheet.AddRow()
		row.AddCell().SetString(item.EventTime)
		row.AddCell().SetInt(item.Uid)
		row.AddCell().SetString(item.Event)
		row.AddCell().SetInt(item.ItemId)
		row.AddCell().SetInt(item.DeltaCount)
		row.AddCell().SetInt(item.RemainCount)
	}

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

	return name
}
