package logic

import (
	"context"
	"errors"
	"fonchain-fiee/api/bundle"
	"fonchain-fiee/pkg/model/login"
	"fonchain-fiee/pkg/service"
	"fonchain-fiee/pkg/service/bundle/common"
	bundleModel "fonchain-fiee/pkg/service/bundle/model"
	"strconv"
	"time"

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

// 校验参数
func ValidateRequest(c *gin.Context, req *bundle.OrderCreateRecord) error {
	if req.BundleUuid == "" {
		return errors.New(common.MissBundleUUID)
	}
	if req.Language == "" {
		req.Language = c.GetHeader("Accept-Language")
		if req.Language == "" {
			return errors.New(common.MissLanguageTypes)
		}
	}
	if req.PurchaseType != common.NewPurchaseOrder && req.PurchaseType != common.RenewalOrder {
		return errors.New(common.ErrPurchaseType)
	}
	return nil
}

// 校验用户状态
func ValidateUserStatus(userInfo login.Info) error {
	statusMessages := map[int32]string{
		1: common.Unnamed,
		2: common.UnderReview,
		3: common.ReviewFailed,
	}
	if userInfo.Status != 4 {
		if msg, ok := statusMessages[userInfo.Status]; ok {
			return errors.New(msg)
		}
		return errors.New(common.UnknownStatus)
	}
	return nil
}

// 校验用户是否已有套餐
func CheckUserOrder(userID uint64) error {
	req := bundle.OrderRecordsDetailRequest{CustomerID: strconv.FormatUint(userID, 10)}
	records, _ := service.BundleProvider.OrderRecordsDetail(context.Background(), &req)
	//if err != nil {
	//	return err
	//}
	// 校验用户是否已有订单
	if records.OrderRecord != nil {
		if records.OrderRecord.CustomerID == strconv.FormatUint(userID, 10) && records.OrderRecord.Status == 1 {
			return errors.New(common.ThereAreOutstandingOrders)
		}
		if records.OrderRecord.CustomerID == strconv.FormatUint(userID, 10) && records.OrderRecord.ExpirationTime > time.Now().Format("2006-01-02 15:04:05") {
			return errors.New(common.HadOrder)
		}
	}
	return nil
}

// 校验用户是否首次购买
func CheckUserFirstOrder(userID uint64) bool {
	req := bundle.OrderRecordsDetailRequest{
		CustomerID: strconv.FormatUint(userID, 10),
		Status:     2,
	}
	records, _ := service.BundleProvider.OrderRecordsDetail(context.Background(), &req)
	// 用户没有任何订单记录
	if records.OrderRecord == nil {
		return true
	}
	// 检查订单是否属于该用户
	if records.OrderRecord.CustomerID != strconv.FormatUint(userID, 10) {
		return true
	}
	return false
}

// 获取最后一次合同编号
func GetLastContractNo() (string, error) {
	records, err := service.BundleProvider.OrderRecordsList(context.Background(), &bundle.OrderRecordsRequest{
		PageSize: 1,
		Page:     1,
	})
	if err != nil {
		return "", err
	}
	if len(records.OrderRecords) > 0 {
		return records.OrderRecords[0].ContractNo, nil
	}
	return "", nil
}

// 获取套餐详情
func GetBundleDetail(uuid, lang string) (*bundle.BundleProfileLang, error) {
	return service.BundleProvider.BundleLangDetailV2(context.Background(), &bundle.BundleDetailRequest{
		Uuid:     uuid,
		Language: lang,
	})
}

// 组装服务内容（套餐权益和附加权益）
func BuildServiceRecords(req *bundle.OrderCreateRecord, bundleDetail *bundle.BundleProfileLang) ([]*bundle.OrderCreateAddRecord, float32, string, error) {
	var (
		addRecords       []*bundle.OrderCreateAddRecord
		addTotalPrice    float32
		expirationDay    string
		addUidService    = make(map[string]bool)
		bundleUidService = make(map[string]bool)
		foundExpiration  = false
	)

	// 分类权益
	for _, i := range bundleDetail.ServiceLangInfo {
		switch i.BenefitsType {
		case 1:
			bundleUidService[i.ValueAddUuid] = true
		case 2:
			addUidService[i.ValueAddUuid] = true
		}
	}
	if len(bundleUidService) == 0 {
		return nil, 0, "", errors.New(common.BundleUnBindingAddService)
	}

	// 附加权益
	for _, i := range req.AddRecords {
		if !addUidService[i.ValueUid] {
			return nil, 0, "", errors.New(common.UnknownAddServiceUUID)
		}
		price, err := service.BundleProvider.CalculatePrice(context.Background(), &bundle.CalculatePriceRequest{
			Uuid:     i.ValueUid,
			Num:      i.Num,
			Language: req.Language,
		})
		if err != nil {
			return nil, 0, "", err
		}
		addTotalPrice += price.Price

		addService, err := service.BundleProvider.ValueAddServiceLangByUuidAndLanguage(context.Background(),
			&bundle.ValueAddServiceDetailRequest{Uuid: i.ValueUid, Language: req.Language})
		if err != nil {
			return nil, 0, "", err
		}
		addRecords = append(addRecords, buildAddRecord(addService, i.ValueUid, price.Price, i.Num, 2))
	}

	// 套餐权益
	for uid := range bundleUidService {
		addService, err := service.BundleProvider.ValueAddServiceLangByUuidAndLanguage(context.Background(),
			&bundle.ValueAddServiceDetailRequest{Uuid: uid, Language: req.Language})
		if err != nil {
			return nil, 0, "", err
		}
		var num int32
		for _, s := range addService.Options {
			if s.IsDefault {
				num = s.Num
				break
			}
		}
		addRecords = append(addRecords, buildAddRecord(addService, uid, 0, num, 1))

		// 计算到期时间
		if !foundExpiration && addService.ServiceType == 5 {
			expirationDay = calculateExpirationDate(time.Now(), num, addService.Unit)
			foundExpiration = true
		}
	}
	// 如果没有找到服务类型为5的，使用默认值
	if !foundExpiration {
		expirationDay = time.Now().AddDate(0, 0, 7).Format("2006-01-02")
	}

	return addRecords, addTotalPrice, expirationDay, nil
}

// 构建单条服务记录
func buildAddRecord(addService *bundle.ValueAddServiceLang, uid string, price float32, num int32, equityType int32) *bundle.OrderCreateAddRecord {
	return &bundle.OrderCreateAddRecord{
		ServiceType:   addService.ServiceType,
		ValueUid:      uid,
		CurrencyType:  addService.PriceType,
		Amount:        price,
		Num:           num,
		Unit:          addService.Unit,
		Source:        1,
		PaymentStatus: 1,
		EquityType:    equityType,
		QuotaType:     addService.QuotaType,
		QuotaValue:    addService.QuotaValue,
		IsExpired:     addService.IsExpired,
	}
}

// 组装订单请求
func BuildOrderRequest(req *bundle.OrderCreateRecord, userInfo login.Info,
	bundleDetail *bundle.BundleProfileLang, addRecords []*bundle.OrderCreateAddRecord,
	addTotalPrice float32, lastContractNo, signContract string) error {

	req.CustomerNum = userInfo.SubNum
	req.CustomerName = userInfo.Name
	req.CustomerID = strconv.FormatUint(userInfo.ID, 10)
	req.BundleName = bundleDetail.Name
	req.Amount = bundleDetail.Price
	req.AmountType = bundleDetail.PriceType
	req.TotalAmount = bundleDetail.Price + addTotalPrice
	req.ContractNo = common.GenerateContractNo(lastContractNo)
	req.SignContract = signContract
	req.SignedTime = common.GetBeijingTime()
	req.Status = bundleModel.OrderSigned
	req.AddRecords = addRecords
	req.PayType = 1

	//确认购买类型
	if req.PurchaseType == common.RenewalOrder {
		currentOrder, err := service.BundleProvider.GetInEffectOrderRecord(context.Background(), &bundle.GetInEffectOrderRecordRequest{
			UserID: userInfo.ID,
		})
		if err != nil {
			return err
		}
		req.RenewalOrderUUID = currentOrder.Uuid
	}
	return nil
}
func calculateExpirationDate(startDate time.Time, num int32, unit string) string {
	//now := time.Now()
	switch unit {
	case "天":
		return startDate.AddDate(0, 0, int(num)).Format("2006-01-02")
	case "月":
		return startDate.AddDate(0, int(num), 0).Format("2006-01-02")
	case "年":
		return startDate.AddDate(int(num), 0, 0).Format("2006-01-02")
	default:
		return ""
	}
}
