package bo

import (
	"encoding/json"
	"fmt"
	"github.com/go-playground/validator/v10"
	"time"
	"voucher/internal/biz/vo"
)

// ConsumeInformation 定义消费信息结构体
type ConsumeInformation struct {
	ConsumeTime   time.Time `json:"consume_time" validate:"required"`   // 核销时间
	ConsumeMchid  string    `json:"consume_mchid"`                      // 核销商户号
	TransactionID string    `json:"transaction_id" validate:"required"` // 微信支付交易单号
	ConsumeAmount int       `json:"consume_amount"`                     // 核销金额（单位：分） //  多笔立减金必须 validate:"required"
}

// CombineSubOrder 定义合单子单消费信息结构体
type CombineSubOrder struct {
	TransactionID string    `json:"transaction_id" validate:"required"` // 合单子单微信支付订单号
	ConsumeAmount int       `json:"comsume_amount" validate:"required"` // 子单核销金额，微信文档字段名如此定义
	ConsumeTime   time.Time `json:"consume_time" validate:"required"`   // 子单核销时间
}

// CombineOrderInfo 定义合单订单信息结构体
type CombineOrderInfo struct {
	CombineConsumeAmount int               `json:"combine_consume_amount"`           // 合单总核销金额
	SubOrders            []CombineSubOrder `json:"sub_orders,omitempty"`             // 合单子单列表
}

// PlainText 定义明文数据结构体
type PlainText struct {
	StockCreatorMchid  string                 `json:"stock_creator_mchid" validate:"required"`
	StockID            string                 `json:"stock_id"`
	CouponID           string                 `json:"coupon_id"`
	CouponName         string                 `json:"coupon_name"`
	Description        string                 `json:"description"`
	Status             vo.WechatVoucherStatus `json:"status"`
	CreateTime         time.Time              `json:"create_time" validate:"required"`
	CouponType         string                 `json:"coupon_type"`
	NoCash             bool                   `json:"no_cash"`
	Singleitem         bool                   `json:"singleitem"`
	BusinessType       string                 `json:"business_type"` // 业务类型
	IsCombineOrder     bool                   `json:"is_combine_order,omitempty"`
	ConsumeInformation *ConsumeInformation    `json:"consume_information,omitempty"`
	CombineOrderInfo   *CombineOrderInfo      `json:"combine_order_info,omitempty"`
}

type WechatVoucherNotifyBo struct {
	ID             string    `json:"id" validate:"required"`
	CreateTime     string    `json:"create_time"`
	ResourceType   string    `json:"resource_type"`
	EventType      string    `json:"event_type" validate:"required"`
	Summary        string    `json:"summary"`
	OriginalType   string    `json:"original_type"`
	AssociatedData string    `json:"associated_data"`
	PlainText      PlainText `json:"plain_text" validate:"required"`
}

func (d *WechatVoucherNotifyBo) Str() (string, error) {

	b, err := json.Marshal(d)
	if err != nil {
		return "", fmt.Errorf("json marshal original_data error: %v", err)
	}

	return string(b), nil
}

func (c *WechatVoucherNotifyBo) Validate() error {

	if err := validator.New().Struct(c); err != nil {
		for _, err = range err.(validator.ValidationErrors) {
			return err
		}
	}

	return nil
}

func (c *WechatVoucherNotifyBo) ValidateMultiNotify() error {
	if err := c.Validate(); err != nil {
		return err
	}

	if c.PlainText.IsCombineOrder {
		if c.PlainText.CombineOrderInfo == nil {
			return fmt.Errorf("合单订单信息不能为空")
		}
		if len(c.PlainText.CombineOrderInfo.SubOrders) == 0 {
			return fmt.Errorf("合单子单不能为空")
		}
		for _, subOrder := range c.PlainText.CombineOrderInfo.SubOrders {
			if subOrder.TransactionID == "" {
				return fmt.Errorf("合单子单微信支付订单号不能为空")
			}
			if subOrder.ConsumeAmount <= 0 {
				return fmt.Errorf("合单子单核销金额必须大于0")
			}
			if subOrder.ConsumeTime.IsZero() {
				return fmt.Errorf("合单子单核销时间不能为空")
			}
		}
		return nil
	}

	if c.PlainText.ConsumeInformation == nil {
		return fmt.Errorf("消费信息不能为空")
	}
	if c.PlainText.ConsumeInformation.ConsumeAmount <= 0 {
		return fmt.Errorf("消费金额必须大于0")
	}

	return nil
}
