package events

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

	"time"

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

func Goods_get_day_time_count(date string, serverId string) map[int]int {
	var goodsCount = make(map[int]int) //[id,count]
	f, err := os.Open(fmt.Sprintf("%s/pay-%s.log", utils.GetKeyConf("events", "path"), date))
	if err != nil {
		return goodsCount
	}
	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, ";")
		if serverId == "0" || arr[1] == serverId {
			params := strings.Split(arr[3], ",")

			goodsId := 0
			if len(params) > 2 {
				goodsId = utils.StringToInt(params[2])
			}
			if goodsId > 0 {
				goodsCount[goodsId] += 1
			}
		}
	}
	return goodsCount
}

func Goods_get_range_day_time_count(days int, serverId string) ([]*tgSeries, []string) {
	var series []*tgSeries
	var arrCate []string
	currTime := int(time.Now().Unix())
	dayCount := 0
	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 := Goods_get_day_time_count(date, serverId)

		for k, _ := range glCount {
			item.Data = append(item.Data, glCount[k])
			key := fmt.Sprintf("%d", k)
			if !utils.InSlice(arrCate, key) {
				arrCate = append(arrCate, key)
			}
		}

		item.MapCount = glCount
		// log.Printf("item[%v]", item)
		series = append(series, item)
		dayCount++
		if dayCount > days {
			break
		}
	}

	return series, arrCate
}

// 保存文件
func Save_goods_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 = "商品id"
	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().SetString(fmt.Sprintf("%d", 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
}
