package bundle

import (
	"context"
	"errors"
	"fmt"
	"fonchain-fiee/api/bundle"
	"fonchain-fiee/api/order"
	"fonchain-fiee/pkg/config"
	"fonchain-fiee/pkg/model/login"
	"fonchain-fiee/pkg/service"
	"fonchain-fiee/pkg/service/bundle/common"
	bundleModel "fonchain-fiee/pkg/service/bundle/model"
	"io"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

func CreateStripeCheckoutSession(c *gin.Context) {
	var req order.CreateStripeCheckoutSessionRequest

	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		service.Error(c, err)
		return
	}

	// 获取 用户信息
	userInfo := login.GetUserInfoFromC(c)

	fmt.Println("userInfo.ID:", userInfo.ID)

	// 检查 订单信息
	detail, detailErr := service.BundleProvider.OrderRecordsDetail(context.Background(), &bundle.OrderRecordsDetailRequest{
		OrderNo: req.OutTradeNo,
	})

	if detailErr != nil {
		service.Error(c, detailErr)
		return
	}

	fmt.Printf("detail: %+v\n", detail)

	// 判断 是否是 本人操作
	if strconv.FormatUint(userInfo.ID, 10) != detail.OrderRecord.CustomerID {
		service.Error(c, errors.New(common.NotMatchOrderInfo))
		return
	}

	//金额校验
	if detail.OrderRecord.TotalAmount*100 != float32(req.ProductAllPrice) {
		service.Error(c, errors.New(common.InvalidOrderAmount))
		return
	}

	// 如果 当前订单 是 已签未支付  且 存在 checkoutSessionId 需要 查询 支付结果
	if detail.OrderRecord.Status == bundleModel.OrderSigned && detail.OrderRecord.CheckoutSessionId != "" && detail.OrderRecord.PayTime == "" {
		// 查询支付结果
		stripeInfosRes, stripeInfosErr := service.OrderProvider.QueryStripeInfoByCheckSessionIds(context.Background(), &order.QueryStripeInfoRequest{
			CheckoutSessionIds: []string{detail.OrderRecord.CheckoutSessionId},
		})

		if stripeInfosErr != nil {
			service.Error(c, errors.New(common.ErrorQueryStripeInfo))
			return
		}

		if stripeInfosRes != nil && len(stripeInfosRes.StripeInfos) > 0 {
			for _, stripeInfo := range stripeInfosRes.StripeInfos {
				if stripeInfo.OutTradeNo == detail.OrderRecord.OrderNo && stripeInfo.PaymentIntentStatus == "paid" {
					_, updateOrderRecordErr := service.BundleProvider.UpdateOrderRecord(context.Background(), &bundle.OrderRecord{
						Uuid:    detail.OrderRecord.Uuid,
						Status:  bundleModel.OrderPaid,
						PayTime: common.GetBeijingTime(),
					})
					fmt.Println("detail.OrderRecord.Uuid :", detail.OrderRecord.Uuid)
					if updateOrderRecordErr != nil {
						service.Error(c, detailErr)
						return
					}
					service.Success(c, &service.Response{
						Msg:  common.HadPay,
						Code: 0,
					})
					return
				}
			}
		}
	}

	//调用微服务获取支付地址
	result, err := service.OrderProvider.CreateStripeCheckoutSession(context.Background(), &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	//更新订单状态
	_, updateOrderRecordErr := service.BundleProvider.UpdateOrderRecord(context.Background(), &bundle.OrderRecord{
		Uuid:               detail.OrderRecord.Uuid,
		CheckoutSessionId:  result.CheckoutSessionId,
		CheckoutSessionUrl: result.CheckoutSessionUrl,
	})

	if updateOrderRecordErr != nil {
		service.Error(c, updateOrderRecordErr)
		return
	}

	service.Success(c, result)

}

func StripeCheckoutSessionWebhook(c *gin.Context) {
	var req order.GetCheckoutWebhookRequest
	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, int64(65536))
	payloadBytes, err := io.ReadAll(c.Request.Body)
	if err != nil {
		service.Error(c, err)
		return
	}
	req.Payload = string(payloadBytes)
	req.Signature = c.GetHeader("Stripe-Signature")
	req.WebhookKey = config.Webhookkey
	fmt.Printf("webhookKey:%s\n", req.WebhookKey)
	resp, err := service.OrderProvider.CommonCheckoutWebhook(c, &req)
	if err != nil {
		service.Error(c, err)
		return
	}
	fmt.Println("resp.PaymentIntentStatus:", resp.PaymentIntentStatus)
	if resp.PaymentIntentStatus == "paid" {
		//支付成功
		_, updateStatusErr := service.BundleProvider.UpdateOrderRecordByOrderNo(context.Background(), &bundle.OrderRecord{
			OrderNo: resp.OutTradeNo,
			PayTime: common.GetBeijingTime(),
			Status:  bundleModel.OrderPaid,
		})
		if updateStatusErr != nil {
			service.Error(c, err)
			return
		}

	}
	service.Success(c)
}
