package crons

import (
	"designs/global"
	"designs/model"
	"fmt"
	"os"
	"time"
)

func ActiveDelete() {
	//读取前一日数据
	now := time.Now()

	for i := 30; i <= 40; i++ {
		last := now.AddDate(0, 0, -i).Format("2006-01-02")

		path := "storage" + "/" + last

		//删除前一天的文件夹
		err := os.RemoveAll(path)
		if err != nil {
			fmt.Println("删除文件夹失败："+path, err)
		} else {
			fmt.Println("删除文件夹完成：" + path)
		}
	}
}

func OnlineDatabaseDelete() {
	//获取到表名
	now := time.Now()

	date := now.AddDate(0, 0, -29).Format("20060102")

	tableName := "user_online_" + date

	var tableList []string
	sql := "SELECT table_name FROM information_schema.tables WHERE table_schema = 'chunhao' AND table_name LIKE '" + tableName + "%'"
	err := global.App.DB.Raw(sql).Pluck("table_name", &tableList).Error

	if err != nil {
		global.App.Log.Error("查询", date, "user_online数据表失败", err.Error())
		return
	}

	//批量删除数据表
	for _, table := range tableList {
		sql := "drop table IF EXISTS " + table
		err := global.App.DB.Exec(sql).Error
		if err != nil {
			global.App.Log.Error("删除", table, "数据表失败", err.Error())
			return
		}
	}

	global.App.Log.Info(date, "数据表清理完成", tableList)
}

//// 对留存数据进行汇算
//func RemainDataSummary() {
//	//计算上一日的留存
//	lastDay := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
//
//	//读取到所有的gid ，根据GID计算这些数据
//
//
//}

//对广告数据进行汇算

func AdsDataSummary() {
	lastDay := time.Now().AddDate(0, 0, -1).Format("20060102")

	//计算出上一日的广告数据汇总
	var adsSummary []struct {
		Count    int    `json:"count" gorm:"column:count"`
		Pf       string `json:"pf" gorm:"column:pf"`
		Gid      string `json:"gid" gorm:"column:gid"`
		SumType1 string `json:"sumType1" gorm:"column:sumType1"`
		SumType2 string `json:"sumType2" gorm:"column:sumType2"`
		SumType0 string `json:"sumType0" gorm:"column:sumType0"`
	}

	err := global.App.DB.Table("user_see_ads").
		Where("date", lastDay).
		Group("gid,pf").
		Select("count(*) as count", "pf", "gid",
			"SUM(adsState = 1) AS sumType1",
			"SUM(adsState = 2) AS sumType2",
			"SUM(adsState = 0) AS sumType0").
		Scan(&adsSummary).Error

	fmt.Println(adsSummary)
	if err != nil {
		global.App.Log.Error("查询广告汇总数据报错：", err)
		return
	}
	var SummaryUserSeeAds []model.SummaryUserSeeAds

	now := model.XTime{
		Time: time.Now(),
	}
	for _, summary := range adsSummary {
		SummaryUserSeeAds = append(SummaryUserSeeAds, model.SummaryUserSeeAds{
			Date:      lastDay,
			Count:     summary.Count,
			Pf:        summary.Pf,
			Gid:       summary.Gid,
			SumType1:  summary.SumType1,
			SumType2:  summary.SumType2,
			SumType0:  summary.SumType0,
			CreatedAt: now,
		})
	}

	//将汇总数据存入数据库中
	err = global.App.DB.Table("summary_user_see_ads").CreateInBatches(&SummaryUserSeeAds, 100).Error
	if err != nil {
		global.App.Log.Error("存入统计数据失败", err.Error())
		fmt.Println(err.Error())
		return
	}

	return
}

//// 对打点数据进行汇算
//func ActionDataSummary() {
//	lastDay := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
//
//	//
//}
