package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/lib/mob"
	"applet/app/lib/sms"
	"applet/app/svc"
	"applet/app/utils"
	"applet/app/utils/cache"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
	"time"
)

func StoreWithdrawFlow(c *gin.Context) {
	var req map[string]string
	if err := c.ShouldBindJSON(&req); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	req["store_uid"] = utils.IntToStr(user.Info.Uid)
	store := db.GetStoreIdEg(svc.MasterDb(c), utils.IntToStr(user.Info.Uid))
	if store != nil {
		req["parent_uid"] = utils.IntToStr(store.ParentUid)
		req["store_type"] = utils.IntToStr(store.StoreType)
	}
	withdraw, total := db.GetStoreWithdraw(svc.MasterDb(c), req)
	list := make([]map[string]string, 0)
	if withdraw != nil {
		var stateList = []string{"审核中", "审核通过", "审核通过", "审核拒绝"}
		for _, v := range *withdraw {
			tmp := map[string]string{
				"amount":         v.Amount,
				"alipay_account": v.WithdrawAccount,
				"alipay_name":    v.WithdrawName,
				"state_str":      stateList[v.State],
				"state":          utils.IntToStr(v.State),
				"memo":           v.Memo,
				"time":           v.CreateAt.Format("2006-01-02 15:04:05"),
			}
			list = append(list, tmp)
		}
	}
	res := map[string]interface{}{
		"total": total,
		"list":  list,
	}
	e.OutSuc(c, res, nil)
	return
}
func StoreWithdrawDoing(c *gin.Context) {
	var req map[string]string
	if err := c.ShouldBindJSON(&req); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	if user.Profile.AccAlipay == "" || user.Profile.AccAlipayRealName == "" {
		e.OutErr(c, 400, e.NewErr(400, "未绑定支付宝"))
		return
	}
	if utils.StrToFloat64(req["amount"]) <= 0 {
		e.OutErr(c, 400, e.NewErr(400, "金额不正确"))
		return
	}
	sess := svc.MasterDb(c).NewSession()
	defer sess.Close()
	sess.Begin()
	oid := utils.StrToInt64(utils.OrderUUID(user.Info.Uid))
	store := db.GetStoreId(sess, utils.IntToStr(user.Info.Uid))
	if store == nil {
		e.OutErr(c, 400, e.NewErr(400, "提现失败"))
		return
	}
	bools := svc.MoneyCheck(c, sess, user.Info.Uid, store.ParentUid, store.StoreType, 1, 2, utils.StrToFloat64(req["amount"]), "提现", oid)
	if bools == false {
		e.OutErr(c, 400, e.NewErr(400, "提现失败"))
		return
	}
	var flow = &model.CommunityTeamStoreWithdrawApply{
		Uid:             user.Info.Uid,
		ParentUid:       store.ParentUid,
		StoreType:       store.StoreType,
		Amount:          req["amount"],
		Type:            1,
		WithdrawAccount: user.Profile.AccAlipay,
		WithdrawName:    user.Profile.AccAlipayRealName,
		CreateAt:        time.Now(),
		UpdateAt:        time.Now(),
		Oid:             oid,
	}
	insert, err := sess.Insert(flow)
	if insert == 0 || err != nil {
		e.OutErr(c, 400, e.NewErr(400, "提现失败"))
		return
	}
	sess.Commit()
	e.OutSuc(c, "success", nil)
	return
}

func StoreWithdrawBindAlipay(c *gin.Context) {
	var req map[string]string
	if err := c.ShouldBindJSON(&req); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	if req["alipay_account"] == "" {
		e.OutErr(c, 400, e.NewErr(400, "支付宝不能为空"))
		return
	}
	if req["alipay_name"] == "" {
		e.OutErr(c, 400, e.NewErr(400, "真实姓名不能为空"))
		return
	}
	mob1, errr := mob.GetMobSDK(c.GetString("mid"))
	if errr != nil {
		e.OutErr(c, e.ERR_MOB_CONFIG, errr)
		return
	}
	user := svc.GetUser(c)
	req["phone"] = user.Info.Phone
	if req["zone"] == "" {
		req["zone"] = "86"
	}
	send := map[string]interface{}{
		"phone": req["phone"],
		"zone":  req["zone"],
		"code":  req["captcha"],
	}
	var ok bool
	var err error
	// h5(wap) 登录
	smsPlatform := sms.GetSmsPlatform(c)
	key := fmt.Sprintf("%s_SMS_FastLogin_%s", db.SysCfgGet(c, "app_name"), req["phone"])
	if smsPlatform == "ljioe" {
		b, err := cache.GetBytes(key)
		if err != nil {
			e.OutErr(c, e.ERR_MOB_SMS_NO_EXISTS, err)
			return
		}
		if req["captcha"] != gjson.GetBytes(b, "data.captcha").String() {
			e.OutErr(c, e.ERR_MOB_SMS_NO_SAME, err)
			return
		}
		ok = true
	} else {
		c.Set("not_deduction_doing", "1")
		ok, err = mob1.MobSMS(c, send)
		if err != nil {
			e.OutErr(c, 400, err.Error())
			return
		}
	}

	if ok {
		user.Profile.AccAlipay = req["alipay_account"]
		user.Profile.AccAlipayRealName = req["alipay_name"]
		svc.MasterDb(c).Where("uid=?", user.Profile.Uid).Cols("acc_alipay,acc_alipay_real_name").Update(user.Profile)
		e.OutSuc(c, "success", nil)
		return
	}
	// 验证码无效或者过期，验证码错误
	e.OutErr(c, e.ERR_SMS_AUTH, err)
	return
}
