package services

import (
	"fmt"
	"github.com/tealeg/xlsx"
	"hongze/hongze_task/models"
	"hongze/hongze_task/utils"
	"os"
	"time"
)

//潜在客户回访记录
func FreeViewerDetail() (err error) {
	defer func() {
		if err != nil {
			fmt.Println("crete FreeViewerDetail err:", err.Error())
			utils.FileLog.Info("crete FreeViewerDetail err: %s", err.Error())
		}
	}()


	//endTime := time.Now().Format(utils.FormatDateTime)
	startTime := time.Now().AddDate(0, 0, -7).Format(utils.FormatDateTime)
	endTime :=time.Now().Format(utils.FormatDateTime)

	items,err:=models.GetFreeViewerDetails(startTime,endTime)
	if err!=nil {
		return
	}
	title:="潜在客户回访记录"
	//创建excel
	file := xlsx.NewFile()
	sheet, err := file.AddSheet(title)
	if err != nil {
		return err
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "手机号"
	cellC := rowTitle.AddCell()
	cellC.Value = "客户公司"
	cellD := rowTitle.AddCell()
	cellD.Value = "创建时间"
	cellE := rowTitle.AddCell()
	cellE.Value = "最后访问时间"

	for _, item := range items {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.Mobile
		cellC := row.AddCell()
		cellC.Value=item.Note
		cellD := row.AddCell()
		cellD.Value = item.CreatedTime
		cellE := row.AddCell()
		cellE.Value = item.MaxCreatedTime
	}

	savePath := "free_viewer_details"+ time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	err = file.Save("./" + savePath)
	if err != nil {
		return
	}
	//发送邮件
	fmt.Println("start send email")
	sendResult := utils.SendEmailByHongze(title, "潜在客户回访记录',\"你好，上周潜在客户回访记录见附件。", utils.EmailSendToHzUsers, savePath,title+".xlsx")
	//sendResult:=utils.SendEmailByHongze(title,"你好，上周研报阅读统计见附件。",utils.EmailSendToMe,savePath)
	if sendResult {
		os.Remove(savePath)
	}
	//fmt.Println("send result:", sendResult)
	fmt.Println("end send email")
	return nil
}