package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/svc"
	"applet/app/utils"
	"applet/app/utils/cache"
	"applet/app/utils/logx"
	zhios_third_party_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/utils"
	"fmt"
	"time"
	"xorm.io/xorm"
)

func OrderStoreSettle(eg *xorm.Engine, dbName string) {
	var data []model.CommunityTeamOrder
	eg.Where("state=2 and store_settle_at=0 and commission>0 and store_type=0").Limit(20).Find(&data)
	for _, v := range data {
		doing(eg, dbName, v)
	}
	return
}
func doing(eg *xorm.Engine, dbName string, order model.CommunityTeamOrder) {
	// 加锁 防止并发提取
	mutexKey := fmt.Sprintf("%s:task.CommunityTeamOrderStoreSettle:%d", dbName, order.Id)
	withdrawAvailable, err := cache.Do("SET", mutexKey, 1, "EX", 5, "NX")
	if err != nil {
		return
	}
	if withdrawAvailable != "OK" {
		return
	}
	sess := eg.NewSession()
	defer sess.Close()
	sess.Begin()
	orderData := db.GetOrder(sess, zhios_third_party_utils.Int64ToStr(order.Oid))
	if orderData.StoreSettleAt > 0 {
		sess.Rollback()
		return
	}
	orderData.StoreSettleAt = int(time.Now().Unix())
	update, err := sess.Where("id=?", orderData.Id).Cols("store_settle_at").Update(orderData)
	if update == 0 || err != nil {
		sess.Rollback()
		return
	}
	//给钱
	bools := CommSettleMoney(sess, utils.IntToStr(orderData.StoreUid), orderData.Commission, dbName, orderData.Oid)
	if bools == false {
		sess.Rollback()
		return
	}
	sess.Commit()
	return
}
func CommSettleMoney(session *xorm.Session, uid, amount, dbName string, oid int64) bool {
	// 拿到锁才能进行余额操作
	// 获取余额更新锁
	cb, err := svc.HandleBalanceDistributedLock(dbName, uid, "settle_order")
	if err != nil {
		fmt.Println(err)
		return false
	}
	// 释放锁
	if cb != nil {
		defer cb()
	}

	now := time.Now()
	beforeAmount := "0"
	afterAmount := "0"
	var affected int64 = 0
	userProfile, err := db.UserProfileFindByIdWithSession(session, utils.StrToInt(uid))
	if err != nil || userProfile == nil {
		//_ = session.Rollback()
		return true
	}
	// 开始写入流水
	var orderAction = 300
	ItemTitle := "门店提成"
	finUserFlow := model.FinUserFlow{
		Type:         0,
		Uid:          utils.StrToInt(uid),
		Amount:       amount,
		BeforeAmount: beforeAmount,
		AfterAmount:  afterAmount,
		OrdType:      "community_team_store",
		OrdId:        utils.Int64ToStr(oid),
		OrdAction:    orderAction,
		OrdDetail:    utils.Int64ToStr(oid),
		State:        2,
		OtherId:      oid,
		OrdTitle:     ItemTitle,
		OrdTime:      int(now.Unix()),
		CreateAt:     now,
		UpdateAt:     now,
	}
	// 更新用户余额
	finUserFlow.BeforeAmount = userProfile.FinValid
	userProfile.FinValid = utils.Float64ToStrByPrec(utils.AnyToFloat64(userProfile.FinValid)+utils.StrToFloat64(amount), 9)
	userProfile.FinTotal = userProfile.FinTotal + utils.StrToFloat32(utils.Float64ToStrByPrec(utils.StrToFloat64(amount), 9))
	affected, err = db.UserProfileUpdateWithSession(session, uid, userProfile, "fin_valid", "fin_total")
	finUserFlow.AfterAmount = userProfile.FinValid
	has, errs := db.InsertCommWithSession(
		session, &finUserFlow)
	if affected == 0 || err != nil || errs != nil || has == 0 {
		_ = session.Rollback()
		_ = logx.Warn(err)
		return false
	}

	return true
}
