package bundle

import (
	"context"
	"errors"
	"fonchain-fiee/api/bundle"
	"fonchain-fiee/api/order"
	"fonchain-fiee/pkg/model/login"
	"fonchain-fiee/pkg/service"
	"fonchain-fiee/pkg/service/bundle/common"
	"fonchain-fiee/pkg/service/bundle/logic"
	bundleModel "fonchain-fiee/pkg/service/bundle/model"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"strconv"
)

func CreateBundleOrderSignature(c *gin.Context) {
	var req bundle.OrderRecord

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

	if req.BundleUuid == "" {
		service.Error(c, errors.New(common.MissBundleUUID))
		return
	}

	if req.Signature == "" {
		service.Error(c, errors.New(common.MissOrderSignature))
		return
	}

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

	// 校验 当前用户只能买一次套餐
	orderRecordsListReq := bundle.OrderRecordsRequest{
		CustomerID: strconv.FormatUint(userInfo.ID, 10),
	}
	orderRecordsList, orderRecordsListErr := service.BundleProvider.OrderRecordsList(context.Background(), &orderRecordsListReq)
	if orderRecordsListErr != nil {
		service.Error(c, orderRecordsListErr)
		return
	}

	if orderRecordsList.OrderRecords != nil {
		for _, order := range orderRecordsList.OrderRecords {
			if order.CustomerID == strconv.FormatUint(userInfo.ID, 10) {
				service.Error(c, errors.New(common.HadOrder))
				return
			}
		}
	}

	req.CustomerNum = userInfo.SubNum
	req.CustomerName = userInfo.Name
	req.CustomerID = strconv.FormatUint(userInfo.ID, 10)

	// 获取 套餐信息
	bundleDetailReq := &bundle.BundleDetailRequest{
		Uuid: req.BundleUuid,
	}
	bundleDetail, detailErr := service.BundleProvider.BundleDetail(context.Background(), bundleDetailReq)
	if detailErr != nil {
		service.Error(c, detailErr)
		return
	}

	req.BundleName = bundleDetail.Bundle.Name
	req.Amount = bundleDetail.Bundle.Price
	req.AmountType = bundleDetail.Bundle.PriceType

	req.PayType = 1 // 默认 人民币

	// 当前 未将 签名 写入合同中
	signContract, signContractErr := logic.SignContract(req.CustomerNum, bundleDetail.Bundle.Contract, req.Signature)
	if signContractErr != nil {
		service.Error(c, signContractErr)
		return
	}

	req.SignContract = signContract

	req.SignedTime = common.GetBeijingTime()

	req.Status = bundleModel.OrderSigned

	res, err := service.BundleProvider.CreateOrderRecord(context.Background(), &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
}

func UpdateBundleOrderStatusPaid(c *gin.Context) {
	var req bundle.OrderRecord

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

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

	if req.Uuid == "" {
		service.Error(c, errors.New(common.MissOrderUUID))
		return
	}

	detail, detailErr := service.BundleProvider.OrderRecordsDetail(context.Background(), &bundle.OrderRecordsDetailRequest{
		Uuid: req.Uuid,
	})

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

	// 判断 是否是 本人操作
	if strconv.FormatUint(userInfo.ID, 10) != detail.OrderRecord.CustomerID {
		service.Error(c, errors.New(common.NotMatchOrderInfo))
		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
		}

		totalStripe := 0

		if stripeInfosRes != nil && len(stripeInfosRes.StripeInfos) > 0 {
			totalStripe = len(stripeInfosRes.StripeInfos)
			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(),
					})
					if updateOrderRecordErr != nil {
						service.Error(c, detailErr)
						return
					}
					totalStripe--
				}
			}
		}

		if totalStripe != 0 && totalStripe == len(stripeInfosRes.StripeInfos) {
			_, updateOrderRecordErr := service.BundleProvider.UpdateOrderRecord(context.Background(), &bundle.OrderRecord{
				Uuid:               detail.OrderRecord.Uuid,
				CheckoutSessionId:  "",
				CheckoutSessionUrl: "",
			})
			if updateOrderRecordErr != nil {
				service.Error(c, detailErr)
				return
			}
		}
	}

	service.Success(c, nil)
}

func OrderRecordsList(c *gin.Context) {
	var req bundle.OrderRecordsRequest

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

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

	//req.CustomerID = strconv.FormatUint(userInfo.ID, 10)

	res, err := service.BundleProvider.OrderRecordsList(context.Background(), &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
}

func OrderRecordsDetail(c *gin.Context) {
	var req bundle.OrderRecordsDetailRequest

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

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

	req.CustomerID = strconv.FormatUint(userInfo.ID, 10)

	res, err := service.BundleProvider.OrderRecordsDetail(context.Background(), &req)
	if err != nil {
		service.Error(c, err)
		return
	}

	service.Success(c, res)
}