package events

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

	"box-gm/utils"

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

type RecordChat struct {
	EventTime   string
	Uid         string
	Name        string
	ToUid       string
	MsgType     string
	ContentType string
	Content     string
}

func ChatQuery_get_records(name, uid, ty_chat string, startTime, endTime int) []*RecordChat {
	// 日期列表
	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("ChatQuery_get_records dateList[%v]", dateList)
	t := func(ty string) string {
		switch ty {
		case "1":
			return "PRIVATE"
		case "2":
			return "WORLD"
		case "3":
			return "CLUB"
		}
		return ""
	}
	var records []*RecordChat
	loc, _ := time.LoadLocation("Local")
	for _, date := range dateList {
		eventFile := fmt.Sprintf("%s/chat-%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)
			/* string.format(
			   "%s;%s;%s;%s;%s;%s;%s",
			   get_time_string(),
			   get_server_id(),
			   _tostring(uid),
			   _tostring(toUid),
			   _tostring(msgty),
			   _tostring(iCType),
			   _tostring(cnt)*/
			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())
					if len(arr) > 6 && ti >= startTime && ti <= endTime {
						params := strings.Split(arr[6], ",")
						nickname := ""
						content := ""
						ty := arr[4]
						if len(params) > 1 {
							nickname = params[0]
							content = params[1]
						} else {
							content = arr[6]
						}

						if name == "" || nickname == name {
							if ty_chat == "0" || ty_chat == ty {
								item := &RecordChat{}
								item.EventTime = arr[0]
								item.Uid = arr[2]
								item.Name = nickname
								item.ToUid = arr[3]
								item.MsgType = t(ty)
								item.ContentType = arr[5]
								item.Content = content

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

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

// 保存文件
func Save_chatquery_records(records []*RecordChat, 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 = "发送方昵称"
	row.AddCell().Value = "接收方ID"
	row.AddCell().Value = "消息类型"
	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.Name)
		row.AddCell().SetString(item.ToUid)
		row.AddCell().SetString(item.MsgType)
		row.AddCell().SetString(item.ContentType)
		row.AddCell().SetString(item.Content)
	}

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

	return name
}
