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/shopspring/decimal"
	"github.com/tidwall/gjson"
	"math"
	"math/rand"
	"time"
)

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

	ord, err := CheckCommunityTeam(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
	}
	// 回调
	CommonCallbackCommunityTeam(c, utils.AnyToString(ord.Oid), md.BALANCE_PAY)
	return nil, nil
}
func AlipayCommunityTeam(c *gin.Context) (interface{}, error) {
	ord, err := CheckCommunityTeam(c)
	if err != nil {
		return nil, err
	}
	payParams := &md.AliPayPayParams{
		Subject:   "小店下单",
		Amount:    ord.Amount,
		OrdId:     utils.AnyToString(ord.Oid),
		OrderType: md.CommunityTeam,
		Uid:       utils.IntToStr(ord.Uid),
		AgentId:   ord.ParentUid,
	}
	r, err := PrepareAlipayCode(c, payParams)
	if err != nil {
		return nil, err
	}
	return r, nil
}
func WxPayCommunityTeam(c *gin.Context) (interface{}, error) {
	var r interface{}
	var err error
	ord, err := CheckCommunityTeam(c)
	if err != nil {
		return nil, err
	}
	params := map[string]string{
		"subject":        "小店下单",
		"amount":         wxMoneyMulHundred(ord.Amount),
		"order_type":     md.CommunityTeam,
		"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 AlipayCallbackCommunityTeam(c *gin.Context) {
	orderId, err := AlipayCallback(c)
	if err != nil || orderId == "" {
		return
	}
	CommonCallbackCommunityTeam(c, orderId, md.ALIPAY)
}
func WxPayCallbackCommunityTeam(c *gin.Context) {
	orderId, err := wxPayCallback(c)
	if err != nil || orderId == "" {
		return
	}
	CommonCallbackCommunityTeam(c, orderId, md.WX_PAY)
}

// 微信金额乘100
func wxMoneyMulHundred(m string) string {
	amount, _ := decimal.NewFromString(m)
	newM := amount.Mul(decimal.NewFromInt(100))
	return newM.String()
}
func CommonCallbackCommunityTeam(c *gin.Context, orderId string, payMethod string) {
	ord := db.GetOrderEg(db.DBs[c.GetString("mid")], orderId)
	if ord == nil {
		return
	}
	// 判断是否失效
	if ord.State != 0 {
		return
	}
	ord.State = 1
	ord.UpdateAt = time.Now()
	ord.Code = Code()
	ord.PayAt = time.Now()
	ord.PayMethod = md.PayMethodIDs[payMethod]
	MasterDb(c).Where("id=?", ord.Id).Cols("state,update_at,code,pay_at,pay_method").Update(ord)
	engine := MasterDb(c)
	storeId, ord1, goodsInfo, err := CommGetPrinterContent(c, utils.Int64ToStr(ord.Oid))
	if err != nil {
		e.OutErr(c, 400, err)
		return
	}
	//打印操作
	go ReplaceDoing(c, engine, storeId, ord1, goodsInfo)
	return
}
func Code() string {
	rand.Seed(time.Now().UnixNano())
	var digits = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
	b := make([]rune, 6)
	for i := range b {
		if fl := float64(rand.Intn(10)); fl > math.Log10(float64(i+1)) {
			b[i] = digits[rand.Intn(len(digits))]
		} else {
			b[i] = digits[rand.Intn(10)]
		}
	}
	fmt.Println(string(b))
	return string(b)
}
func CheckCommunityTeam(c *gin.Context) (*model.CommunityTeamOrder, 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.GetOrderEg(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
}
