package bundle

import (
	"context"
	"errors"
	"fonchain-fiee/api/account"
	"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"
	"math/big"
	"strconv"

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

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
			}
		}
	}

	// 获取 最后一次的 合同编号
	lastOrderRecord, lastOrderRecordErr := service.BundleProvider.OrderRecordsList(context.Background(), &bundle.OrderRecordsRequest{
		PageSize: 1,
		Page:     1,
	})

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

	lastContractNo := ""

	if lastOrderRecord.OrderRecords != nil {
		for _, lastOrder := range lastOrderRecord.OrderRecords {
			lastContractNo = lastOrder.ContractNo
		}
	}

	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
	}

	//获取增值套餐信息
	if req.ValueAddBundleUuid != "" {
		valueAddBundleDetail, err := service.BundleProvider.ValueAddBundleDetail(context.Background(), &bundle.ValueAddBundleDetailRequest{
			Uuid: req.ValueAddBundleUuid,
		})
		if err != nil {
			service.Error(c, err)
			return
		}

		req.ValueAddBundleUuid = valueAddBundleDetail.Data.Uuid
		req.ValueAddOriginalPrice = valueAddBundleDetail.Data.OriginalPrice
		req.ValueAddDiscountPrice = valueAddBundleDetail.Data.DiscountPrice

		if valueAddBundleDetail.Data.Choose { // 可选条数
			req.ValueAddBundleAmount = valueAddBundleDetail.Data.DiscountPrice * float32(req.Num)
			discount, _ := new(big.Float).Sub(big.NewFloat(float64(valueAddBundleDetail.Data.OriginalPrice)), big.NewFloat(float64(valueAddBundleDetail.Data.DiscountPrice))).Float32()
			req.ValueAddSavedAmount = discount * float32(req.Num)
		} else { // 固定条数
			req.ValueAddBundleAmount = valueAddBundleDetail.Data.TotalPrice
			req.ValueAddSavedAmount = valueAddBundleDetail.Data.SavedAmount
		}

		req.TotalAmount, _ = new(big.Float).Add(big.NewFloat(float64(req.ValueAddBundleAmount)), big.NewFloat(float64(bundleDetail.Bundle.Price))).Float32()
	}

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

	req.TotalAmount = req.Amount + req.ValueAddBundleAmount
	req.PayType = 1 // 默认 人民币

	req.ContractNo = common.GenerateContractNo(lastContractNo)

	// 当前 未将 签名 写入合同中
	signContract, signContractErr := logic.SignContractV2(req.CustomerNum, bundleDetail.Bundle.Contract, req.TotalAmount, bundleDetail.Bundle.ContractDuration)
	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
	}

	for _, orderRecord := range res.OrderRecords {
		if orderRecord.CustomerID != "" {
			var userID uint64
			userID, err = strconv.ParseUint(orderRecord.CustomerID, 10, 64)
			if err != nil {
				err = nil
				continue
			}

			userInfo, _ := service.AccountProvider.Info(context.Background(), &account.InfoRequest{
				Domain: "app",
				ID:     userID,
			})
			if userInfo != nil {
				orderRecord.Sex = userInfo.Sex
				orderRecord.Nationality = userInfo.Nationality
				orderRecord.CertificatePicture = userInfo.CertificatePicture
				orderRecord.PlaceOfResidence = userInfo.PlaceOfResidence
				orderRecord.GroupPhoto = userInfo.GroupPhoto
			}
		}

	}

	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)
}
