package timetask

import (
	"bytes"
	qu "qfw/util"
	gm "qfw/util/mail"
	"sync"
	"time"
	"util"

	"github.com/donnie4w/go-logger/logger"
	"github.com/tealeg/xlsx"
)

//下载异常附件统计
func GetFileWarn() {
	defer qu.Catch()
	logger.Debug("异常附件数据统计...")
	file, err := xlsx.OpenFile("res/model.xlsx")
	if err != nil {
		qu.Debug("open file err:", err)
		return
	}
	sheet := file.Sheets[0]
	sess := util.MgoS.GetMgoConn()
	defer util.MgoS.DestoryMongoConn(sess)
	query := map[string]interface{}{
		"comeintime": map[string]interface{}{
			"$gte": util.GetTime(-1),
			"$lt":  util.GetTime(0),
		},
	}
	fields := map[string]interface{}{}
	lock := &sync.Mutex{}
	wg := &sync.WaitGroup{}
	ch := make(chan bool, 5)
	it := sess.DB(util.MgoS.DbName).C("spider_warn").Find(&query).Select(&fields).Iter()
	n := 0
	for tmp := make(map[string]interface{}); it.Next(&tmp); n++ {
		wg.Add(1)
		ch <- true
		go func(tmp map[string]interface{}) {
			defer func() {
				<-ch
				wg.Done()
			}()
			info := qu.ObjToString(tmp["info"])
			if info != "Attachment Upload Failed" {
				return
			}
			lock.Lock()
			row := sheet.AddRow()
			lock.Unlock()
			site := qu.ObjToString(tmp["site"])
			row.AddCell().SetValue(site)
			code := qu.ObjToString(tmp["code"])
			row.AddCell().SetValue(code)
			channel := qu.ObjToString(tmp["channel"])
			row.AddCell().SetValue(channel)
			title := qu.ObjToString(tmp["title"])
			row.AddCell().SetValue(title)
			href := qu.ObjToString(tmp["href"])
			row.AddCell().SetValue(href)
			lua, _ := util.MgoE.FindOne("luaconfig", map[string]interface{}{"code": code})
			if len(*lua) > 0 {
				row.AddCell().SetValue((*lua)["modifyuser"])
				urgency := qu.IntAll((*lua)["urgency"])
				if urgency == 0 {
					row.AddCell().SetValue("普通")
				} else {
					row.AddCell().SetValue("紧急")
				}
				row.AddCell().SetValue((*lua)["platform"])
			}
		}(tmp)
		if n%100 == 0 {
			logger.Debug(n)
		}
		tmp = map[string]interface{}{}
	}
	wg.Wait()
	mw := &util.MyWrite{
		Byte: &bytes.Buffer{},
	}
	file.Write(mw)
	bt := mw.Byte.Bytes()
	now := time.Now()
	name := qu.FormatDate(&now, qu.Date_Short_Layout) + "统计报表.xlsx"
	gm.GSendMail_Bq("jy@jianyu360.cn", util.To, "", "", "附件下载失败数据统计", "", name, bt, util.GMail)
	//now := time.Now()
	//path := "res/附件采集情况" + qu.FormatDate(&now, qu.Date_Short_Layout) + ".xlsx"
	//err = file.Save(path) //保存临时excel
	//if err != nil {
	//	qu.Debug("附件采集统计出错")
	//	return
	//}
	////发送邮件
	////删除临时excel
	//go func(path string) {
	//	time.Sleep(300000)
	//	os.Remove(path)
	//}(path)
	logger.Debug("异常附件数据统计完成...")
}
