package pay

import (
	"common/connection"
	"common/timer"
	"goutil/logUtilPlus"
	"paycenter/internal/wxpay"
	"strconv"
	"time"
)

func init() {
	timer.Register(timer.TriggerTypeHalfHour, CheckOrderStatus)
}

// CheckOrderStatus 检查订单状态
// @return error
func CheckOrderStatus(nowTime time.Time) error {

	//检索最近一个月的订单
	for i := 0; i < 2; i++ {

		//取i的负数
		dbDate := connection.GetToMonthAdd(int32(-i))
		var orders []Order // 使用切片存储查询结果

		//这里使用原始sql
		sql := "select * from order_" + strconv.Itoa(int(dbDate)) + " where order_status = 0"
		dbResult := connection.GetPayDB().Exec(sql).Find(&orders)
		if dbResult.Error != nil {
			logUtilPlus.ErrorLog("查询订单状态失败", dbResult.Error.Error())
			continue
		}

		// 处理查询结果
		for _, order := range orders {

			//查询订单状态
			statusStr, err := wxpay.QueryOrderByOutTradeNo(order.OrderID)
			if err != nil {
				logUtilPlus.ErrorLog("查询订单状态失败", err.Error())
				continue
			}
			if statusStr == "SUCCESS" {
				//修改订单状态
				err = ChangeOrderStatus(order.OrderID, 1)
				if err != nil {
					logUtilPlus.ErrorLog("修改订单状态失败", err.Error())
					continue
				}
			} else if statusStr == "CLOSED" { //已关闭
				order.OrderStatus = 2
				//修改订单状态
				connection.AsyncSave(connection.GetPayDB(), &order)
			} else if order.OrderTime.Add(time.Hour * 1).Before(time.Now()) { //超一个小时未支付 直接关闭订单
				//直接关闭订单
				err = wxpay.CloseOrder(order.OrderID)
				if err != nil {
					logUtilPlus.ErrorLog("关闭订单失败", err.Error())
					continue
				}
				order.OrderStatus = 2
				connection.AsyncSave(connection.GetPayDB(), &order)
			}
		}
	}

	return nil
}
