package util

import (
	"fmt"
	"ktogame/dbUtil"
	"ktogame/models"
	"time"

	"github.com/astaxie/beego/toolbox"
	"github.com/shopspring/decimal"
)

func init() {
	fmt.Println("进来定时")
	tk1 := toolbox.NewTask("myTask1", "0 01 0 * * 0-6", func() error {
		fenfa()
		return nil
	})
	toolbox.AddTask("myTask1", tk1)
	toolbox.StartTask()
}

func fenfa() {
	var ci models.CommonInfo
	dbUtil.Engine.Get(&ci)
	nowFormat := NowTimeDayString()
	cs := ci.SupplyTime[:10]
	if nowFormat != cs {
		return
	}
	format := time.Now().AddDate(0, 0, -6).Format("2006-01-02 15:04:05")
	sql_total := "SELECT IFNULL(SUM(1-amount_lv),0) as total FROM user_addr WHERE amount_lv<1 AND create_time<?"
	res, _ := dbUtil.Engine.SQL(sql_total, format).QueryInterface()
	totalLv, _ := decimal.NewFromString(string(res[0]["total"].([]uint8)))
	st := time.Now().AddDate(0, 0, 2).Format("2006-01-02 15:04:05")
	ci.SupplyTime = st
	if totalLv.Cmp(decimal.Zero) == 0 {
		dbUtil.Engine.ID(ci.Id).Cols("supply_time").Update(&ci)
		return
	}
	var user []models.UserAddr
	dbUtil.Engine.Where("amount_lv<1 and create_time<?", format).Find(&user)
	div := decimal.NewFromFloat(ci.SupplyAmount).Div(totalLv)
	fmt.Println("div=", div)
	out := getAmountOut()
	fmt.Println("out=", out)
	for _, v := range user {
		mul := decimal.NewFromFloat(1 - v.AmountLv).Mul(div)
		v.Profit4, _ = decimal.NewFromFloat(v.Profit4).Add(mul).Float64()
		v.UseAmount, _ = decimal.NewFromFloat(v.UseAmount).Add(mul).Float64()
		i := mul.Mul(out).Div(decimal.NewFromFloat(200.0))
		v.AmountLv, _ = decimal.NewFromFloat(v.AmountLv).Add(i).Float64()
		f, _ := mul.Float64()
		sb := models.SuccessBill{IdWork.Generate(), v.Addr, f, 1, 0, "", "-", 5, NowTimeString()}
		dbUtil.Engine.ID(v.Addr).Cols("amount_lv,use_amount,profit4").Update(&v)
		dbUtil.Engine.Insert(&sb)
		dbUtil.Engine.ID(ci.Id).Cols("supply_time").Update(&ci)
	}
}
