package svc

import (
	"applet/app/db"
	"applet/app/e"
	"applet/app/svc"
	"applet/app/utils"
	"applet/app/utils/cache"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func StoreOrderConfirm(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	// 加锁 防止并发提取
	mutexKey := fmt.Sprintf("%s:team.StoreOrderConfirm:%s", c.GetString("mid"), arg["oid"])
	withdrawAvailable, err := cache.Do("SET", mutexKey, 1, "EX", 5, "NX")
	if err != nil {
		e.OutErr(c, e.ERR, err)
		return
	}
	if withdrawAvailable != "OK" {
		e.OutErr(c, e.ERR, e.NewErr(400000, "请求过于频繁，请稍后再试"))
		return
	}
	sess := svc.MasterDb(c).NewSession()
	defer sess.Close()
	sess.Begin()
	order := db.GetOrder(sess, arg["oid"])
	if order == nil {
		sess.Rollback()
		e.OutErr(c, 400, e.NewErr(400, "订单不存在"))
		return
	}
	if order.State != 1 {
		sess.Rollback()
		e.OutErr(c, 400, e.NewErr(400, "订单不能确认"))
		return
	}
	order.State = 2
	order.UpdateAt = time.Now()
	order.ConfirmAt = time.Now()
	update, err := sess.Where("id=?", order.Id).Cols("state,confirm_at,update_at").Update(order)
	if update == 0 || err != nil {
		sess.Rollback()
		e.OutErr(c, 400, e.NewErr(400, "订单确认失败"))
		return
	}
	//给商家余额
	money := utils.StrToFloat64(order.Commission)
	if order.ParentUid > 0 {
		money = utils.StrToFloat64(order.Amount) - utils.StrToFloat64(order.AgentCommission)
	}
	if order.StoreType == 1 {
		money = utils.StrToFloat64(order.Amount) - utils.StrToFloat64(order.PlatformCommission)
	}
	bools := svc.MoneyCheck(c, sess, order.StoreUid, order.ParentUid, order.StoreType, 0, 1, money, "订单核销", order.Oid)
	if bools == false {
		sess.Rollback()
		e.OutErr(c, 400, e.NewErr(400, "订单确认失败"))
		return
	}
	sess.Commit()
	e.OutSuc(c, "success", nil)
	return
}
