package services

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

//用户权限统计
func HongzeUsers() (err error) {
	defer func() {
		if err != nil {
			fmt.Println("crete HongzeUsers err:", err.Error())
			utils.FileLog.Info("crete HongzeUsers err: %s", err.Error())
		}
	}()

	items,err:=models.GetHongzeUsers()
	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.CompanyName
		cellC := row.AddCell()
		cellC.Value=item.Mobile
		cellD := row.AddCell()
		cellD.Value = item.IsRegister
		cellE := row.AddCell()
		cellE.Value = item.UserType
	}

	savePath := "hongze_user"+ 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")
	if sendResult {
		os.Remove(savePath)
	}
	fmt.Println("send result:", sendResult)
	fmt.Println("end send email")
	return nil
}

func FixReportLasterViewTime() {
	items,err:=models.GetPotentialUser()
	if err!=nil {
		fmt.Println("Err:"+err.Error())
		return
	}
	for k,v:=range items{
		maxTime,err:=models.GetMaxReviewTime(int(v.UserId))
		if err!=nil {
			fmt.Println("GetMaxReviewTime Err:"+err.Error())
			return
		}
		err=models.ModifyUserLastViewTime(int(v.UserId),maxTime)
		if err!=nil {
			fmt.Println("ModifyUserLastViewTime Err:"+err.Error())
			return
		}

		fmt.Println(k,v.UserId,v.Mobile)
	}
}