package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/md"
	"applet/app/utils"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
	"time"
)

func BalanceCommunityTeamPay(c *gin.Context) (interface{}, error) {

	ord, err := CheckCommunityTeamPay(c)
	if err != nil || ord == nil {
		return nil, err
	}
	err = BalancePay(c, ord.Amount, utils.Int64ToStr(ord.Oid), md.CommunityTeam)
	if err != nil {
		return nil, err
	}
	// 回调
	CommonCallbackCommunityTeamPay(c, utils.AnyToString(ord.Oid), md.BALANCE_PAY)
	return nil, nil
}
func AlipayCommunityTeamPay(c *gin.Context) (interface{}, error) {
	ord, err := CheckCommunityTeamPay(c)
	if err != nil {
		return nil, err
	}
	payParams := &md.AliPayPayParams{
		Subject:   "收款码收款",
		Amount:    ord.Amount,
		OrdId:     utils.AnyToString(ord.Oid),
		OrderType: md.CommunityTeamPay,
		Uid:       utils.IntToStr(ord.Uid),
		AgentId:   ord.ParentUid,
	}
	r, err := PrepareAlipayCode(c, payParams)
	if err != nil {
		return nil, err
	}
	return r, nil
}
func WxPayCommunityTeamPay(c *gin.Context) (interface{}, error) {
	var r interface{}
	var err error
	ord, err := CheckCommunityTeamPay(c)
	if err != nil {
		return nil, err
	}
	params := map[string]string{
		"subject":        "收款码收款",
		"amount":         wxMoneyMulHundred(ord.Amount),
		"order_type":     md.CommunityTeamPay,
		"ord_id":         utils.AnyToString(ord.Oid),
		"pay_wx_mch_id":  SysCfgGet(c, "pay_wx_mch_id"),
		"pay_wx_api_key": SysCfgGet(c, "pay_wx_api_key"),
		"uid":            utils.IntToStr(ord.Uid),
	}
	if ord.ParentUid > 0 {
		user, _ := db.UserThirdPartyFindByID(MasterDb(c), ord.ParentUid)
		if user.WechatPayInfo == "" {
			return nil, errors.New("支付失败")
		}
		params["pay_wx_mch_id"] = gjson.Get(user.WechatPayInfo, "pay_wx_mch_id").String()
		params["pay_wx_api_key"] = gjson.Get(user.WechatPayInfo, "pay_wx_api_key").String()
	}
	params["notify_url"] = fmt.Sprintf(md.CALLBACK_URL, c.Request.Host, c.GetString("mid"), params["order_type"], md.WX_PAY)
	r, err = CommPayData(c, params)
	if err != nil {
		return nil, err
	}

	return r, nil
}
func AlipayCallbackCommunityTeamPay(c *gin.Context) {
	orderId, err := AlipayCallback(c)
	if err != nil || orderId == "" {
		return
	}
	CommonCallbackCommunityTeamPay(c, orderId, md.ALIPAY)
}
func WxPayCallbackCommunityTeamPay(c *gin.Context) {
	orderId, err := wxPayCallback(c)
	if err != nil || orderId == "" {
		return
	}
	CommonCallbackCommunityTeamPay(c, orderId, md.WX_PAY)
}

func CommonCallbackCommunityTeamPay(c *gin.Context, orderId string, payMethod string) {
	sess := MasterDb(c).NewSession()
	defer sess.Close()
	sess.Begin()
	ord := db.GetOrderPay(sess, orderId)
	if ord == nil {
		sess.Rollback()
		return
	}
	// 判断是否失效
	if ord.State != 0 {
		return
	}
	ord.State = 1
	ord.UpdateAt = time.Now()
	ord.PayAt = time.Now()
	ord.PayMethod = md.PayMethodIDs[payMethod]
	sess.Where("id=?", ord.Id).Cols("state,update_at,pay_at,pay_method").Update(ord)
	money := utils.StrToFloat64(ord.Commission)
	if ord.ParentUid > 0 {
		money = utils.StrToFloat64(ord.Amount) - utils.StrToFloat64(ord.AgentCommission)
	}
	if ord.StoreType == 1 {
		money = utils.StrToFloat64(ord.Amount) - utils.StrToFloat64(ord.PlatformCommission)
	}
	bools := MoneyCheck(c, sess, ord.StoreUid, ord.ParentUid, ord.StoreType, 0, 4, money, "收款码收款", ord.Oid)
	if bools == false {
		sess.Rollback()
		return
	}
	sess.Commit()
	return
}
func CheckCommunityTeamPay(c *gin.Context) (*model.CommunityTeamPayOrder, error) {
	var args struct {
		MainOrdId string `json:"main_ord_id"`
	}
	if err := c.ShouldBindJSON(&args); err != nil || args.MainOrdId == "" {
		return nil, e.NewErrCode(e.ERR_INVALID_ARGS)
	}
	// 查询订单
	ord := db.GetOrderPayEg(db.DBs[c.GetString("mid")], args.MainOrdId)
	if ord == nil {
		return nil, e.NewErr(403000, "不存在该订单")
	}
	// 判断是否失效
	if ord.State != 0 {
		return nil, e.NewErr(403000, "订单已处理")
	}
	return ord, nil
}
