package service

import (
	"designs/global"
	"designs/model"
	"designs/utils"
	"github.com/pkg/errors"
	"math"
	"time"
)

func RemainDataBydDay(types int, pf string, gid string, startTime string, endTime string) (map[string]map[string]interface{}, error) {
	var err error

	//对于传过来的endTime ,做一个处理
	t, _ := time.Parse("2006-01-02", endTime)
	endTimeData := t.AddDate(0, 0, 1).Format("2006-01-02")

	UsersBydDay := utils.GetTimeDayDate(startTime, endTime)     //用户分别是在哪天注册的
	UserLoginBydDay := utils.GetTimeDayDate(startTime, endTime) //用户分别是在哪天注册的
	var UsersId []int
	userIdMap := make(map[int]bool)
	if types == 1 {
		//先计算出这个时间内 ，每天的注册用户数量
		var users []model.User
		err = global.App.DB.Table("user").
			Where("pf", pf).Where("gid", gid).
			Where("createdAt", ">=", startTime).
			Where("createdAt", "<=", endTimeData).
			Scan(&users).Error
		if err != nil {
			return nil, err
		}

		for _, user := range users {
			userIdMap[user.UserId] = true
			UsersBydDay[user.CreatedAt.Format("2006-01-02")] = append(UsersBydDay[user.CreatedAt.Format("2006-01-02")], user.UserId)

		}
		for user := range userIdMap {
			UsersId = append(UsersId, user)
		}
		users = nil //用完后清空内存
	} else if types == 2 {
		var users []model.UserLogin
		err = global.App.DB.Table("user_login").
			Where("pf", pf).Where("gid", gid).
			Where("loginTime", ">=", startTime).
			Where("loginTime", "<=", endTimeData).
			Group("userId").
			Scan(&users).Error
		if err != nil {
			return nil, err
		}
		for _, user := range users {
			UsersId = append(UsersId, user.UserId)
			UsersBydDay[user.LoginTime.Format("2006-01-02")] = append(UsersBydDay[user.LoginTime.Format("2006-01-02")], user.UserId)
		}

	} else {
		return nil, errors.New("type 参数错误")
	}

	//把每天的注册用户进行集合，查出后面所有天数的活跃情况
	var UserLogin []model.UserOnline
	err = global.App.DB.Table("user_online").
		Where("pf", pf).Where("gid", gid).
		WhereIn("userId", UsersId).
		Where("logTime", ">=", startTime).
		Select("logTime", "userId").
		Group("date,userId").
		Scan(&UserLogin).Error
	if err != nil {
		return nil, err
	}
	//对这些数据进行整理
	for _, v := range UserLogin {
		//根据天进行分组，得出总共有多少
		times := v.LogTime.Format("2006-01-02")
		UserLoginBydDay[times] = append(UserLoginBydDay[times], v.UserId)
	}

	res := make(map[string]map[string]interface{})
	//逐天比较注册的数据和留存的数据，得出每天的活跃比例和人数
	for day, v := range UsersBydDay {
		remain := make(map[string]interface{})
		remain["count"] = len(v)
		remain["date"] = day
		//分别比较每一天的数据
		for dayDate, loginDay := range UserLoginBydDay {
			ok, remainDays := utils.CompareDates(dayDate, day)
			if !ok {
				continue
			}
			remain[remainDays] = math.Round(utils.IntersectionRate(v, loginDay)*100*100) / 100
		}

		res[day] = remain
	}

	return res, nil
}
