package model

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"fmt"

	"gorm.io/datatypes"
	"gorm.io/plugin/soft_delete"
)

// 增值套餐
type ValueAddBundleProfile struct {
	Id                  int32   `gorm:"column:id;type:int(11);primary_key;AUTO_INCREMENT" json:"id"`
	UUID                string  `json:"uuid" gorm:"column:uuid;type:varchar(1024);comment:增值套餐UUID"`
	Num                 int32   `json:"num" gorm:"column:num;type:int;comment:视频数量"`
	OriginalPrice       float32 `json:"originalPrice" gorm:"column:original_price;type:decimal(12,2);comment:原单价"`
	DiscountPrice       float32 `json:"discountPrice" gorm:"column:discount_price;type:decimal(12,2);comment:优惠单价"`
	SavedAmount         float32 `json:"savedAmount" gorm:"column:saved_amount;type:decimal(12,2);comment:节省金额"`
	TotalPrice          float32 `json:"totalPrice" gorm:"column:total_price;type:decimal(12,2);comment:套餐总价"`
	DiscountPriceStatus bool    `json:"discountPriceStatus" gorm:"column:discount_price_status;default:false;comment:优惠单价状态(true:等于 false:约等于)"`
	Choose              bool    `json:"choose" gorm:"column:choose;default:false;comment:可选条数(true:可以 false:不可以)"`
	//Type                int32   `json:"type" gorm:"column:type;type:int;comment:类型 1:固定套餐 2:自定义套餐"`
	PriceType          int32  `json:"priceType" gorm:"column:price_type;type:int;comment:套餐价格类型 1:人民币 2:美元"`
	Language           string `json:"language" gorm:"column:language;type:varchar(32);comment:套餐语言 zh-CN EN"`
	AddBundleCommonUid string `json:"addBundleCommonUid" gorm:"column:add_bundle_common_uid;type:varchar(1024);comment:套餐公共ID"`
	CreatedAt          int64  `gorm:"column:created_at;autoCreateTime"`
	UpdatedAt          int32  `gorm:"column:updated_at;autoCreateTime"`
	DeletedAt          soft_delete.DeletedAt
}

// 新增值套餐主表
type ValueAddService struct {
	Id                      int32                     `gorm:"column:id;type:int(11);primary_key;AUTO_INCREMENT" json:"id"`
	UUID                    string                    `json:"uuid" gorm:"column:uuid;type:varchar(1024);comment:增值套餐UUID"`
	ServiceName             string                    `json:"serviceName" gorm:"column:service_name;type:varchar(1024);comment:增值服务名称"`
	ServiceType             int32                     `json:"serviceType" gorm:"column:service_type;type:int;comment:服务类型 1:视频 2:图文 3:数据报表 4:账号数 5:可用时长"`
	ValueAddServiceLang     []ValueAddServiceLang     `gorm:"foreignKey:UUID;references:UUID"`
	BundleToValueAddService []BundleToValueAddService `gorm:"foreignKey:ValueUid;references:UUID"`
	CreatedAt               int64                     `gorm:"column:created_at;autoCreateTime"`
	UpdatedAt               int64                     `gorm:"column:updated_at;autoCreateTime"`
	DeletedAt               soft_delete.DeletedAt
}

// 新增值套餐语言表
type ValueAddServiceLang struct {
	Id            int32        `gorm:"column:id;type:int(11);primary_key;AUTO_INCREMENT" json:"id"`
	UUID          string       `json:"uuid" gorm:"column:uuid;type:varchar(1024);comment:增值套餐UUID"`
	ServiceName   string       `json:"serviceName" gorm:"column:service_name;type:varchar(1024);comment:增值服务名称"`
	ServiceType   int32        `json:"serviceType" gorm:"column:service_type;type:int;comment:服务类型 1:视频 2:图文 3:数据报表 4:账号数 5:可用时长"`
	PriceMode     int32        `json:"priceMode" gorm:"column:price_mode;type:int;comment:套餐价格类型 1:单价 2:总价"`
	OriginalPrice float32      `json:"originalPrice" gorm:"column:original_price;type:decimal(12,2);comment:原单价"`
	TotalPrice    float32      `json:"totalPrice" gorm:"column:total_price;type:decimal(12,2);comment:增值服务总价"`
	Unit          string       `json:"unit" gorm:"column:unit;type:varchar(50);comment:单位 1:个 2:条 3:天 4:月 5:年"`
	Language      string       `json:"language" gorm:"column:language;type:varchar(32);comment:套餐语言 zh-CN zh-TW EN de-DE js-JP(中繁英德日)"`
	PriceType     int64        `json:"priceType" gorm:"column:price_type;type:int;comment:币种 1:人民币 2:美元 3:日元 4:欧元"`
	Options       PriceOptions `gorm:"column:options;type:json" json:"options"`
	CreatedAt     int64        `gorm:"column:created_at;autoCreateTime"`
	UpdatedAt     int64        `gorm:"column:updated_at;autoCreateTime"`
	DeletedAt     soft_delete.DeletedAt
}

type ValueAddServiceHistory struct {
	Id              int32          `gorm:"column:id;type:int(11);primary_key;AUTO_INCREMENT" json:"id"`
	Uuid            string         `json:"uuid" gorm:"column:uuid;type:varchar(1024);comment:UUID"`
	ValueAddService datatypes.JSON `json:"valueAddService" gorm:"column:value_add_service;type:json;comment:增值服务"`
	Operator        string         `json:"operator" gorm:"column:operator;type:varchar(1024);comment:操作人"`
	OperatorId      uint64         `json:"operatorId" gorm:"column:operator_id;type:int;comment:操作人ID"`
	CreatedAt       int64          `gorm:"column:created_at;autoCreateTime"`
	UpdatedAt       int64          `gorm:"column:updated_at;autoCreateTime"`
	DeletedAt       soft_delete.DeletedAt
}

type PriceOptions []*PriceOption
type PriceOption struct {
	Id     int32   `json:"id"`
	Num    int32   `json:"num"`
	Symbol string  `json:"symbol"` // 符号> < = <= =>
	Price  float32 `json:"price"`  // 价格(根据priceMode决定是单价还是总价)
}

// 实现 driver.Valuer 接口
func (o PriceOptions) Value() (driver.Value, error) {
	return json.Marshal(o)
}

// 实现 sql.Scanner 接口
func (o *PriceOptions) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("实现 sql.Scanner 接口 failed: type assertion to []byte failed")
	}
	return json.Unmarshal(bytes, o)
}

// 校验Options是否合法,避免同一数字被多个规则覆盖
func ValidateOptions(options PriceOptions) (bool, error) {
	symbolSet := map[string]struct{}{">": {}, "<": {}, ">=": {}, "<=": {}, "=": {}}
	cover := make(map[int]struct{})
	for _, opt := range options {
		if opt.Num < 0 || opt.Num > 100 {
			return false, errors.New("数字范围错误")

		}
		if _, ok := symbolSet[opt.Symbol]; !ok {
			return false, errors.New("符号错误")

		}
		var nums []int
		switch opt.Symbol {
		case "=":
			nums = []int{int(opt.Num)}
		case ">":
			for i := int(opt.Num) + 1; i <= 100; i++ {
				nums = append(nums, i)
			}
		case ">=":
			for i := int(opt.Num); i <= 100; i++ {
				nums = append(nums, i)
			}
		case "<":
			for i := 1; i < int(opt.Num); i++ {
				nums = append(nums, i)
			}
		case "<=":
			for i := 1; i <= int(opt.Num); i++ {
				nums = append(nums, i)
			}
		}
		for _, n := range nums {
			if _, exist := cover[n]; exist {
				return false, errors.New("逻辑存在冲突,请重新设置")

			}
			cover[n] = struct{}{}
		}
	}
	return true, nil
}
func (m *ValueAddService) TableName() string {
	return "value_add_service"
}
func (m *ValueAddServiceLang) TableName() string {
	return "value_add_service_lang"
}
func (m *ValueAddServiceHistory) TableName() string {
	return "value_add_service_history"
}
func (options PriceOptions) CalculatePrice(priceMode, target int32) (float32, error) {
	for _, opt := range options {
		match := false
		switch opt.Symbol {
		case "=":
			match = target == opt.Num
		case ">":
			match = target > opt.Num
		case ">=":
			match = target >= opt.Num
		case "<":
			match = target < opt.Num
		case "<=":
			match = target <= opt.Num
		default:
			return 0, fmt.Errorf("不支持的符号: %s", opt.Symbol)
		}

		if match {
			switch priceMode {
			case 1:
				return float32(target) * opt.Price, nil
			case 2:
				return opt.Price, nil
			default:
				return 0, fmt.Errorf("未知价格模式: %d", priceMode)
			}
		}
	}

	return 0, fmt.Errorf("未找到匹配规则")
}