package service

import (
	"github.com/gomodule/redigo/redis"
	"github.com/tidwall/gjson"
	"go_sku_server/model"
	c "go_sku_server/pkg/common"
	"go_sku_server/pkg/gredis"
)

type CustomPrice struct {
}

// 加上自定义价格的转换
func (sc *CustomPrice) getCustomPriceList(sku model.LySku) (customPriceList []model.CustomPrice, err error) {
	//先根据组织获取对应的自定义价格系数
	redisCon := gredis.Conn("default_r")
	defer redisCon.Close()
	customPriceRule, _ := redis.String(redisCon.Do("HGET", "cube_custom_price", sku.OrgId))
	if customPriceRule=="" {
		return customPriceList, nil
	}
	customPriceRuleArr := gjson.Get(customPriceRule, "price_list").Array()
	//这里是价格规则
	for _, customPriceRule := range customPriceRuleArr {
		//每一个自定义价格都有一个系数,比如会员价利润 10%
		ratio := customPriceRule.Get("ratio").Int()
		priceName := customPriceRule.Get("price_name").String()
		var customPrice model.CustomPrice
		customPrice.PriceName = priceName
		for _, item := range sku.LadderPrice {
			ratioFloat := c.DivFloat(float64(100+ratio), 100)
			customPrice.LadderPrice = append(customPrice.LadderPrice, model.LadderPrice{
				Purchases: item.Purchases,
				PriceCn:   c.MyRound(c.MulFloat(item.PriceCn*ratioFloat), 2),
				PriceUs:   c.MyRound(c.MulFloat(item.PriceUs*ratioFloat), 2),
				PriceAc:   c.MyRound(c.MulFloat(item.PriceAc*ratioFloat), 2),
				PriceAcUs: c.MyRound(c.MulFloat(item.PriceAcUs*ratioFloat), 2),
			})
		}
		customPriceList = append(customPriceList, customPrice)
	}
	return customPriceList, nil
}

// 单独处理华云的阶梯价
func (sc *CustomPrice) transformIEdgeLadderPrice(sku model.LySku) (ladderPriceList []model.LadderPrice) {
	//华云因为它只有一个阶梯,所以生成的阶梯价只有2个阶梯,为了兼容以前的数据格式
	/*
	     {
	       "purchases": 1,
	       "price_us": 0,
	       "price_cn": 293.13,
	       "price_name": "标准价"
	     },
	     {
	       "purchases": 2,
	       "price_us": 0,
	       "price_cn": 190.59,
	       "price_name": "企业价"
	     }
	   ]
	*/
	if len(sku.CustomPriceList) != 0 {
		for index, customPrice := range sku.CustomPriceList {
			if len(customPrice.LadderPrice) > 0 {
				//只取最后一个元素价格就行
				ladderPrice := customPrice.LadderPrice[len(customPrice.LadderPrice)-1]
				ladderPrice.PriceName = customPrice.PriceName
				ladderPrice.Purchases = int64(index + 1)
				ladderPriceList = append(ladderPriceList, ladderPrice)
			}

		}
	}
	return ladderPriceList
}