package svc

import (
	"applet/app/db"
	"applet/app/utils"
	"applet/app/utils/logx"
	"errors"
	"fmt"
	"time"
	"xorm.io/xorm"
)

func CancelOrder(eg *xorm.Engine, dbName string) {
	fmt.Println("cancel order...")
	defer func() {
		if err := recover(); err != nil {
			_ = logx.Error(err)
		}
	}()

	timeStr, err := getCancelCfg(eg, dbName)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	now := time.Now()
	// x 分钟后取消订单
	expTime := now.Add(-time.Hour * time.Duration(utils.StrToInt64(timeStr)))
	expTimeStr := utils.Time2String(expTime, "")

	page := 1

	for {
		isEmpty, err := handleOnePage(eg, dbName, expTimeStr)
		if err != nil {
			_ = logx.Error(err)
			break
		}
		if isEmpty {
			break
		}

		if page > 100 {
			break
		}

		page += 1

	}
}

func handleOnePage(eg *xorm.Engine, dbName, expTimeStr string) (isEmpty bool, err error) {
	return false, nil
}

func getCancelCfg(eg *xorm.Engine, masterId string) (string, error) {
	cfg := db.SysCfgGetWithDb(eg, masterId, "order_expiration_time")

	if cfg == "" {
		return "", errors.New("order_expiration_time no found")
	}
	return cfg, nil
}