package hdl

import (
	"applet/app/db"
	"applet/app/e"
	md "applet/app/md/institutional_management/egg_energy"
	"applet/app/svc"
	"applet/app/utils"
	"code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
	"code.fnuoos.com/EggPlanet/egg_models.git/src/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

type GetTotalDataReq struct {
	Year  string `form:"year" binding:"required"`
	Month string `form:"month" binding:"required"`
}

type TotalDataResp struct {
	TotalUserCount      int    `json:"total_user_count"`      // 平台总用户数
	VerifiedUserCount   int    `json:"verified_user_count"`   // 已认证用户数
	NoSignInUserCount   int    `json:"no_sign_in_user_count"` // 未签到用户数
	TotalWithdrawAmount string `json:"total_withdraw_amount"` //已提现累计金额
	Year                string `json:"year"`                  // 年份
	Month               string `json:"month"`                 // 月份
}

// GetTotalData
// @Summary      首页-首页-数据总览
// @Tags         首页
// @Description  数据总览
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    year    query	string 	true  "年"
// @Param    month    query	string 	true  "月"
// @Success      200   {object}   TotalDataResp   	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/homePage/totalData [GET]
func GetTotalData(c *gin.Context) {
	var req GetTotalDataReq
	err := c.ShouldBindQuery(&req)
	if err != nil {
		err = svc.HandleValidateErr(err)
		err1 := err.(e.E)
		e.OutErr(c, err1.Code, err1.Error())
		return
	}

	year := req.Year
	month := req.Month
	if year == "" || month == "" {
		nowStr := time.Now().Format("2006-01-02")
		year = strings.Split(nowStr, "-")[0]
		month = strings.Split(nowStr, "-")[1]
	}
	dataDb := implement.NewPlatformTotalDataDb(db.Db)
	data, err := dataDb.PlatformTotalDataGetOneByTime(year, month)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	if data == nil {
		resp := TotalDataResp{
			TotalUserCount:      0,
			VerifiedUserCount:   0,
			NoSignInUserCount:   0,
			TotalWithdrawAmount: "",
			Year:                "",
			Month:               "",
		}
		e.OutSuc(c, resp, nil)
		return
	}
	resp := TotalDataResp{
		TotalUserCount:      data.TotalUserCount,
		VerifiedUserCount:   data.VerifiedUserCount,
		NoSignInUserCount:   data.NoSignInUserCount,
		TotalWithdrawAmount: data.TotalWithdrawAmount,
		Year:                data.Year,
		Month:               data.Month,
	}
	e.OutSuc(c, resp, nil)
}

type GetActiveDataResp struct {
	Today     *model.PlatformActiveData `json:"today"`     // 今日数据
	Yesterday *model.PlatformActiveData `json:"yesterday"` // 昨日数据
}

// GetActiveData
// @Summary      首页-首页-活跃数据
// @Tags         首页
// @Description  活跃数据
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success      200   {object}   GetActiveDataResp   	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/homePage/activeData [GET]
func GetActiveData(c *gin.Context) {
	nowStr := time.Now().Format("2006-01-02")
	yesterdayStr := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	activityDb := implement.NewPlatformActiveDataDb(db.Db)

	today, err := activityDb.PlatformActiveDataGetOneByParams(map[string]interface{}{"key": "date", "value": nowStr})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err)
	}
	yesterday, err := activityDb.PlatformActiveDataGetOneByParams(map[string]interface{}{"key": "date", "value": yesterdayStr})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err)
	}
	resp := GetActiveDataResp{
		Today:     today,
		Yesterday: yesterday,
	}
	e.OutSuc(c, resp, nil)
}

type GetGrowDataReq struct {
	Kind string `form:"kind" binding:"required"`
}

// GetGrowData
// @Summary      首页-首页-用户增长曲线
// @Tags         首页
// @Description  用户增长曲线
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    kind    query	string 	false  "1:按天 2:按周 3:按小时"
// @Success      200   {object}  md.GetPriceCurveResp  	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/homePage/growData [GET]
func GetGrowData(c *gin.Context) {
	var req GetGrowDataReq
	err := c.ShouldBindQuery(&req)
	if err != nil {
		err = svc.HandleValidateErr(err)
		err1 := err.(e.E)
		e.OutErr(c, err1.Code, err1.Error())
		return
	}
	kind := req.Kind
	var yData []interface{}
	var xData []interface{}
	now := time.Now()
	dataDb := implement.NewPlatformGrowDataDb(db.Db)
	m, has, err := dataDb.PlatformGrowDataGetLastOne()
	if err != nil || !has {
		resp := md.GetPriceCurveResp{
			XData: xData,
			YData: yData,
		}
		e.OutSuc(c, resp, nil)
		return
	}

	switch kind {
	case "1":
		// 日
		var date = now.AddDate(0, 0, -30).Format("2006-01-02")
		var sql = fmt.Sprintf("SELECT user_grow_count, date FROM `platform_grow_data` WHERE DATE >= \"%s\" AND DATE != \"%s\" ORDER BY DATE ASC ", date, now.Format("2006-01-02"))
		results, _ := db.Db.QueryString(sql)
		for _, v := range results {
			tmpDate := utils.TimeParseDateStd(v["date"])
			yData = append(yData, v["user_grow_count"])
			xData = append(xData, tmpDate.Format("2006-01-02"))
		}
		yData = append(yData, utils.IntToStr(m.UserGrowCount))
		tmpDate := utils.TimeParseDateStd(m.Date)
		xData = append(xData, tmpDate.Format("2006-01-02"))
		break
	case "2":
		// 周
		var nums = 29
		for i := nums; i >= 1; i-- {
			var date = now.AddDate(0, 0, -7*i).Format("2006-01-02")
			var sql = "SELECT user_grow_count,date FROM `platform_grow_data` WHERE   DATE = \"%s\" "
			sql = fmt.Sprintf(sql, date)
			results, _ := db.Db.QueryString(sql)
			if results != nil {
				year, week, _, _ := utils.GetWeekInfoByDate(results[0]["date"])
				yData = append(yData, results[0]["user_grow_count"])
				xData = append(xData, fmt.Sprintf("%s年%s周", year, week))
			}
		}
		yData = append(yData, utils.IntToStr(m.UserGrowCount))
		year, week, _, _ := utils.GetWeekInfoByDate(m.Date)
		xData = append(xData, fmt.Sprintf("%s年%s周", year, week))
		break
	case "3":
		// 月
		var nums = 29
		for i := nums; i >= 1; i-- {
			var date = now.AddDate(0, -i, 0).Format("2006-01-02")
			var sql = "SELECT user_grow_count,date FROM `platform_grow_data` WHERE   DATE = \"%s\" "
			sql = fmt.Sprintf(sql, date)
			results, _ := db.Db.QueryString(sql)
			if results != nil {
				tmpDate := utils.TimeParseDateStd(results[0]["date"])
				yData = append(yData, results[0]["user_grow_count"])
				xData = append(xData, tmpDate.Format("2006-01"))
			}
		}
		yData = append(yData, utils.IntToStr(m.UserGrowCount))
		tmpDate := utils.TimeParseDateStd(m.Date)
		xData = append(xData, tmpDate.Format("2006-01"))
		break
	}
	resp := md.GetPriceCurveResp{
		XData: xData,
		YData: yData,
	}
	e.OutSuc(c, resp, nil)
}