package events

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

	"box-gm/utils"

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

type RecordOrder struct {
	EventTime string
	Uid       string
	Name      string
	OrderId   string
	GoodsId   int
	Price     int
	BuyCount  int
}

func OrderQuery_get_records(name, uid string, startTime, endTime int) ([]*RecordOrder, int, int) {
	// 日期列表
	var dateList []string
	times := 0
	cur_charge := 0
	tol_charge := 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("OrderQuery_get_records dateList[%v]", dateList)

	var records []*RecordOrder
	loc, _ := time.LoadLocation("Local")
	for _, date := range dateList {
		eventFile := fmt.Sprintf("%s/pay-%s.log", utils.GetKeyConf("events", "path"), date)
		f, err := os.Open(eventFile)
		if err != nil {
			log.Printf("eventFile[%s] err[%v]", eventFile, err)
			continue
		}
		defer f.Close()
		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 := arr[2]
			if uid == "" || 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[3], ",")
					if len(arrCnt) > 4 && ti >= startTime && ti <= endTime {
						nickname := arrCnt[0]
						orderId := arrCnt[1]
						// if orderId != "GM" {
						// 	//"%s|%s|%s|%s", sServerKey, pid, iNowTime, iRanNumber
						// }
						goodsId := utils.StringToInt(arrCnt[2])
						// isFirstCharge := arrCnt[3]
						price := utils.StringToInt(arrCnt[4])
						if name == "" || nickname == name {
							tol_charge += price
							if utils.GetDiffDays(ti, int(time.Now().Unix())) == 0 {
								cur_charge += price
							}
							item := &RecordOrder{}
							item.EventTime = arr[0]
							item.Uid = uidEvent
							item.Name = nickname
							item.OrderId = orderId
							item.GoodsId = goodsId
							item.Price = price
							item.BuyCount = 1

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

	// log.Printf("OrderQuery_get_records records[%v]", records)
	return records, cur_charge, tol_charge
}

// 保存文件
func Save_orderquery_records(records []*RecordOrder, 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().SetString(item.Uid)
		row.AddCell().SetString(item.OrderId)
		row.AddCell().SetInt(item.GoodsId)
		row.AddCell().SetInt(item.Price)
		row.AddCell().SetInt(item.BuyCount)
	}

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

	return name
}
