package localjx

import (
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/tiktok"
	"time"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
)

func getOrderBriefTt(order *model.GoodsOrder) string {
	return fmt.Sprintf("%s等共%d件商品", order.Skus[0].SkuName, order.GoodsCount)
}

func pay4OrderByTT(ctx *jxcontext.Context, order *model.GoodsOrder, vendorPayType, subAppID string) (orderPay *model.OrderPay, err error) {
	param := &tiktok.TickTokCreateOrder{
		//AppID:       api.TiktokApi.GetAppID(),
		OutOrderNo:  utils.Int64ToStr(GenPayOrderID(order)),
		TotalAmount: int(order.ActualPayPrice),
		Subject:     "蔬菜水果日用品",
		Body:        getOrderBriefTt(order),
		ValidTime:   600,
		CpExtra:     "msg",
		NotifyURL:   globals.TictokpayNotifyURL,
	}
	if subAppID == tiktok.TiktokJXDJAppID {
		param.AppID = api.TiktokJXDJApi.GetAppID()
	} else {
		param.AppID = api.TiktokApi.GetAppID()
	}
	ttOrderId, orderToken, err := getTikTok(subAppID).CreateOrderByTicktock(param)
	if err == nil {
		orderPay = &model.OrderPay{
			PayOrderID:    ttOrderId, // 抖音订单id
			PayType:       model.PayTypeTicTok,
			VendorPayType: vendorPayType,
			VendorOrderID: order.VendorOrderID,
			VendorID:      order.VendorID,
			Status:        0,
			PayCreatedAt:  time.Now(),
			PrepayID:      "",
			CodeURL:       orderToken, // 抖音支付token
			TotalFee:      int(order.ActualPayPrice),
		}
	}
	return orderPay, err
}
func getTikTok(appID string) (TikTokMini *tiktok.API) {
	TikTokMini = api.TiktokApi
	if len(appID) > 0 && appID == api.TiktokJXDJApiID {
		TikTokMini = api.TiktokJXDJApi
	}
	return TikTokMini
}

func OnTTPayCallback(msg *tiktok.DetailCallBackMessage, refund *tiktok.DetailCallBackMessage2Refund, payType string) (err error) {
	switch payType {
	case tiktok.PayStatus: // 支付回调
		err = onTTPayFinished(msg)
	case tiktok.RefundStatus: // 退款回调
		err = onTTPayRefund(refund)
	}
	return err
}

func onTTPayFinished(msg *tiktok.DetailCallBackMessage) (err error) {
	orderPay := &model.OrderPay{
		PayOrderID: msg.OrderId,
		PayType:    model.PayTypeTicTok,
	}
	orderPay.DeletedAt = utils.DefaultTimeValue
	db := dao.GetDB()
	if err = dao.GetEntity(db, orderPay, "PayOrderID", "PayType", "DeletedAt"); err == nil {
		loc, _ := time.LoadLocation("Local")
		t1, _ := time.ParseInLocation("20060102150405", time.Unix(msg.PaidAt, 0).Format("20060102150405"), loc)
		orderPay.PayFinishedAt = utils.Time2Pointer(t1)
		orderPay.TransactionID = msg.ChannelNo
		orderPay.OriginalData = utils.Format4Output(msg, true)
		if msg.Status == tiktok.ResponseCodeSuccess {
			orderPay.Status = model.PayStatusYes
		} else {
			orderPay.Status = model.PayStatusFailed
		}
		dao.UpdateEntity(db, orderPay)

		if msg.Status == tiktok.ResponseCodeSuccess {
			err = OnPayFinished(orderPay)
		}
	} else {
		globals.SugarLogger.Debugf("onTTpayFinished msg:%s, err:%v", utils.Format4Output(msg, true), err)
	}
	return err
}

func onTTPayRefund(msg *tiktok.DetailCallBackMessage2Refund) (err error) {
	orderPayRefund := &model.OrderPayRefund{
		RefundID: msg.CpRefundno,
	}
	db := dao.GetDB()
	if err = dao.GetEntity(db, orderPayRefund, "RefundID"); err == nil {
		if msg.Status == tiktok.ResponseCodeSuccess {
			orderPayRefund.Status = model.RefundStatusYes
		} else {
			orderPayRefund.Status = model.RefundStatusFailed
		}
		orderPayRefund.OriginalData = utils.Format4Output(msg, true)
		dao.UpdateEntity(db, orderPayRefund)
	} else if dao.IsNoRowsError(err) {
		globals.SugarLogger.Warnf("收到异常的退款事件, msg:%s", utils.Format4Output(msg, true))
	}

	orderPay := &model.OrderPay{
		VendorOrderID: orderPayRefund.VendorOrderID,
		VendorID:      jxutils.GetPossibleVendorIDFromVendorOrderID(orderPayRefund.VendorOrderID),
		PayType:       model.PayTypeTicTok,
		Status:        model.PayStatusYes,
	}
	orderPay.DeletedAt = utils.DefaultTimeValue
	if err = dao.GetEntity(db, orderPay, "VendorOrderID", "VendorID", "PayType", "Status", "DeletedAt"); err == nil {
		orderPay.Status = model.PayStatusRefund
		dao.UpdateEntity(db, orderPay)
	}
	return err
}

// 申请退款
func RefundOrderByTT(ctx *jxcontext.Context, orderPay *model.OrderPay, refundID string, refundFee int, refundDesc string) (orderPayRefund *model.OrderPayRefund, err error) {
	result, err := api.TiktokApi.RefundOrderTT(&tiktok.RefundOrderReq{
		AppID:        api.TiktokApi.GetAppID(),
		OutOrderNo:   orderPay.VendorOrderID,
		OutRefundNo:  refundID,
		Reason:       refundDesc,
		RefundAmount: orderPay.TotalFee,
		CpExtra:      "msg",
		NotifyURL:    globals.TictokpayNotifyURL,
	})
	if err == nil {
		orderPayRefund = &model.OrderPayRefund{
			RefundID:        refundID,
			VendorRefundID:  result,
			VendorOrderID:   orderPay.VendorOrderID,
			VendorID:        orderPay.VendorID,
			Status:          model.RefundStatusNo,
			TransactionID:   orderPay.TransactionID,
			RefundFee:       refundFee,
			RefundCreatedAt: time.Now(),
		}
		dao.WrapAddIDCULDEntity(orderPayRefund, ctx.GetUserName())
		db := dao.GetDB()
		if result != "" {
			orderPayRefund.Status = model.RefundStatusYes
		} else {
			orderPayRefund.Status = model.RefundStatusFailed
		}
		orderPayRefund.OriginalData = utils.Format4Output(result, true)
		dao.CreateEntity(db, orderPayRefund)

		orderPay.Status = model.PayStatusRefund
		dao.UpdateEntity(db, orderPay)
	}
	return orderPayRefund, err
}
