package events

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

	"time"

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

func RtPay_get_day_time_count(date string, minutes int, serverId string) (map[int]int, int, int) {
	var timeCount = make(map[int]int)
	f, err := os.Open(fmt.Sprintf("%s/pay-%s.log", utils.GetKeyConf("events", "path"), date))
	curCharge := 0
	tolCharge := 0
	if err != nil {
		return timeCount, curCharge, tolCharge
	}
	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])

			sec := eventTime - startTime
			sec = int(math.Floor(float64(sec) / float64(minutes*60)))
			// pid := utils.StringToInt(arr[2])
			params := strings.Split(arr[3], ",")
			//params :
			//			name,orderId,shopId,isFirstCharge,price
			//			test14,GM,201,true,499
			price := 0
			if len(params) > 4 {
				price = utils.StringToInt(params[4])
				if utils.GetDiffDays(eventTime, startTime) == 0 {
					curCharge += price
				}
				tolCharge += price
			}
			if price > 0 {
				timeCount[sec] = timeCount[sec] + price
			}
		}
	}
	return timeCount, curCharge, tolCharge
}

func RtPay_get_range_day_time_count(days, minutes int, serverId string) ([]*tgSeries, []string, int, int) {
	var series []*tgSeries
	currTime := int(time.Now().Unix())
	dayCount := 0
	curCharge := 0
	tolCharge := 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, cur, tol := RtPay_get_day_time_count(date, minutes, serverId)
		if utils.GetDiffDays(tiEvent, currTime) == 0 {
			curCharge = cur
		}
		tolCharge += tol
		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
		}
	}
	var arrCate []string
	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, curCharge, tolCharge
}

// 保存文件
func Save_rtpay_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("实时支付金额统计")
	if err != nil {
		beego.Warn(err)
		return ""
	}

	row = sheet.AddRow()
	row.AddCell().Value = "日期"
	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()
			row.AddCell().SetString(item.Name)
			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.xlsx", user)
	os.Remove(name)
	err = file.Save(name)
	if err != nil {
		beego.Warn(err)
		return ""
	}

	return name
}
