package schedule

import (
	"github.com/robfig/cron/v3"
	"github.com/sirupsen/logrus"
	"log"
	"time"
	"youngee_b_api/app/dao"
	"youngee_b_api/app/service"
)

func AutoTaskRecharge() error {
	// 新建一个定时任务对象
	crontab := cron.New(cron.WithSeconds()) // 精确到秒
	spec := "0 */2 * * * ?"                 //cron表达式

	// 定时任务  检查微信支付是否充值成功
	_, err1 := crontab.AddFunc(spec, AutoCheckWXRechargeTask)
	if err1 != nil {
		return err1
	}

	// 启动定时器
	crontab.Start()
	// 定时任务是另起协程执行的,这里使用 select 简单阻塞.需要根据实际情况进行控制
	//select {} //阻塞主线程停止
	return nil
}

// 定时任务  检查微信支付是否充值成功
func AutoCheckWXRechargeTask() {
	log.Println("AutoCheckWXRechargeTask running Start, Time :", time.Now())
	rechargeRecords, err := dao.RechargeRecordDao{}.GetWXRechargeByStatusList(1)
	if err != nil {
		log.Println("GetWXRechargeByStatusList", err)
	}
	var rechargeId string
	var noPayIds []int64
	for _, rechargeRecord := range rechargeRecords {
		rechargeId = rechargeRecord.RechargeID
		tradeState, err := service.RechargeService{}.QueryOrderByTradeId(rechargeRecord.EnterpriseID, rechargeRecord.SubAccountId, rechargeId)
		if err != nil {
			logrus.Errorf("AutoCheckWXRechargeTask [QueryOrderByTradeId] call Show err:%+v\n", err)
		}
		// 支付成功的状态会在方法里更新，未支付的需要单独更新
		if "NOTPAY" == tradeState {
			noPayIds = append(noPayIds, rechargeRecord.ID)
		}
	}
	if len(noPayIds) > 0 {
		err2 := dao.RechargeRecordDao{}.UpdateRechargeFailedList(noPayIds)
		if err2 != nil {
			log.Println("UpdateRechargeFailedList", err2)
		}
	}
	log.Println("AutoCheckWXRechargeTask running End, Time :", time.Now())
}
