package service

import (
	"encoding/json"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"github.com/syyongx/php2go"
	"github.com/tidwall/gjson"
	"go_sku_server/model"
	"go_sku_server/pkg/common"
	"go_sku_server/pkg/gredis"
	"go_sku_server/pkg/logger"
	"go_sku_server/pkg/mysql"
	"github.com/gogf/gf/util/gconv"
	"sort"
)

// 自营定时任务服务
type ZyCronService struct {
}

/*
 计算自营折扣信息
@param checkGoodsId 单独一个sku运行
fmt.Println(php2go.Stripos("10005,10006","10006",0))
*/
func (a *ZyCronService) ZyDiscount(checkGoodsId string) {

	var (
		i int
		dbSpu = mysql.Conn("liexin_data") //spu实例化链接
		redisConn = gredis.Conn("search_w")
	)
	defer redisConn.Close()

	if checkGoodsId == "" {
		redisConn.Do("del","zy_ratio_sku") //删除所有系数缓存
	}

	twoYearsAgotime := php2go.Time()-60 * 60 * 24 * 365 * 2  //两年前时间戳

    page_size := 1000 //查数据库每页大小
    OuterLoop:
		for i=0;i<1000;i++ {
			start := 0;
			if i == 0 {
				start = 0;
			}else{
				start = (i-1)*page_size
			}

			sql := "select goods_id,class_id2,brand_id,cost,ladder_price from lie_goods where self_supplier_type = 1 and stock >0 and status=1 limit "+gconv.String(start)+","+gconv.String(page_size);
			if checkGoodsId != "" {
				sql = "select goods_id,class_id2,brand_id,cost,ladder_price from lie_goods where goods_id="+checkGoodsId;
			}

			//fmt.Println(sql)
			goodsInfos, err := dbSpu.QueryString(sql)
			if err != nil || len(goodsInfos) == 0{
				//fmt.Print("查询没有数据",err)
				 break;
			}
			for _,a := range goodsInfos{
				now_goods_id := a["goods_id"]
				now_class_id := a["class_id2"]
				now_brand_id := a["brand_id"]
				/********开始计算系数******/
				//fmt.Println("开始计算系数"+now_goods_id)

				goodsBatch,_ := gredis.String(redisConn.Do("HGET","Self_goods_batch",now_goods_id))  //获取商品批次信息
				apiGoodsList := gjson.Parse(goodsBatch).Array()

				var EarlyBatchTime int64 = 0; //最早的批次
				for _, goods := range apiGoodsList {
					dc_time := goods.Get("dc_time").Int()
					if EarlyBatchTime == 0 {
						EarlyBatchTime = dc_time
						continue;
					}
					if dc_time < EarlyBatchTime {
						EarlyBatchTime = dc_time
					}
				}

				if EarlyBatchTime == 0 {
					//fmt.Println("没有批次信息,goods_id :"+now_goods_id)
					continue;
				}
				//查询所有的系数列表
				ratioAll, _ := redis.Values(redisConn.Do("hgetall", "Self_goods_ratio"))
				var retioArr []string
				err := redis.ScanSlice(ratioAll, &retioArr)
				if err != nil || len(retioArr) == 0 {
					fmt.Println("查询系数失败");
					return
				}

				//系数排序,sort最高的优先排序
				var slic model.SorterRatio
				for _,v:=range retioArr{
					if len(v) > 10 {
						slic = append(slic,map[string]string{
							"goods_id":gjson.Get(v,"goods_id").String(),
							"sort":gjson.Get(v,"sort").String(), //系数名称
							"name":gjson.Get(v,"name").String(), //系数名称
							"ratio":gjson.Get(v,"ratio").String(),  //折扣价
							"min_ratio":gjson.Get(v,"min_ratio").String(), //保本折扣价
							"class_id":gjson.Get(v,"class_id").String(),
							"brand_id":gjson.Get(v,"brand_id").String(),
							"expire_time":gjson.Get(v,"expire_time").String(),
							"allow_coupon":gjson.Get(v,"allow_coupon").String(),
							"allow_presale":gjson.Get(v,"allow_presale").String(),
						})
					}
				}

				sort.Sort(model.SorterRatio(slic))
				//fmt.Println(slic)
				//return

				//计算系数价格
				OuterLoop2:
					for _,info :=range slic{
						//fmt.Println(info)
						//不参与系数的商品
						if info["goods_id"] != "" {
							if php2go.Stripos(info["goods_id"],","+now_goods_id+",",0) > -1 {
								//fmt.Println("1001 本商品不参与系数"+now_goods_id)
								continue;
							}
						}
						//不参与分类的商品
						if info["class_id"] != "" {
							if php2go.Stripos(info["class_id"],","+now_class_id+",",0) == -1 {
								//fmt.Println("1002 不参与分类的商品"+now_goods_id)
								continue;
							}
						}
						//不参与分类的商品
						if info["brand_id"] != "" {
							if php2go.Stripos(info["brand_id"],","+now_brand_id+",",0) == -1 {
								//fmt.Println("1003 不参与分类的商品"+now_goods_id)
								continue;
							}
						}

						//处理过期
						isExpire := false
						expireTimeArr := php2go.Explode(",",info["expire_time"])
						for _,v1 := range expireTimeArr {
							//已过期
							if v1 == "-1" &&  EarlyBatchTime <= twoYearsAgotime {
								isExpire = true;
								break
							}
							//三个月后过期
							if v1 == "-2" &&  EarlyBatchTime >= (twoYearsAgotime+3600* 24 * 30 * 3) {
								isExpire = true;
								break
							}
							//三个内过期
							if  twoYearsAgotime <= EarlyBatchTime && EarlyBatchTime <= (twoYearsAgotime+common.MyInt64(v1)*3600*24*30) {
								isExpire = true;
								break
							}
						}

						//fmt.Println(EarlyBatchTime)
						//fmt.Println(twoYearsAgotime)

						if isExpire == false {
							//fmt.Println("1001 本商品不存在过期"+now_goods_id)
							continue;
						}
						//处理清库存系数,几个系数符合,往下面算
						var ratioPrice float64;
						ratioPrice = php2go.Round(gconv.Float64(a["cost"]) * gconv.Float64(info["ratio"])*10000)/10000

						//查询立创数据
						szlcPriceStr,_ := gredis.String(redisConn.Do("HGET","Self_szlc_price",now_goods_id))  //获取立创价格
						if szlcPriceStr != "" { //有立创的价格
							nowLadder := gjson.Parse(a["ladder_price"]).Array()
							endnowLadder := nowLadder[len(nowLadder)-1].Get("purchases").Int() //最后一个梯度
							//fmt.Println(endnowLadder)
							//获取立创对应的梯度价格
							szlcPriceArr := gjson.Parse(szlcPriceStr).Array()
							var szlcPrice float64 =0  //找到立创对应的梯度价格
							for _,b := range szlcPriceArr{
								if b.Get("purchases").Int() <= endnowLadder {
									szlcPrice = b.Get("price").Float() //自营立创
								}
							}
							szlcPrice = szlcPrice*0.95  //立创95折
							if ratioPrice > szlcPrice { //比立创的95折大
								minPrice := php2go.Round(gconv.Float64(a["cost"]) * gconv.Float64(info["min_ratio"])*10000)/10000
								if szlcPrice < minPrice {
									ratioPrice = minPrice
								}else{
									ratioPrice = szlcPrice
								}
							}
						}

						//立创价格
						allow_coupon := info["allow_coupon"]
						if allow_coupon == "" {
							allow_coupon = "2"
						}
						allow_presale := info["allow_presale"]
						if allow_presale == "" {
							allow_presale = "2"
						}

						ratioRes,_ := json.Marshal(map[string]string{
							"goods_id":now_goods_id,
							"allow_coupon":allow_coupon,
							"allow_presale":allow_presale,
							"szlc_price":szlcPriceStr,
							"price_ac":gconv.String(ratioPrice),
						})
						_,err := redisConn.Do("HSET","zy_ratio_sku",now_goods_id,string(ratioRes)) //写入缓存
						if err != nil {
							fmt.Println(err)
						}

						//最后写日志
						logger.Log("计算阶梯价成功 goods_id: "+now_goods_id+" 原始梯度价:"+a["ladder_price"]+" 立创梯度价: "+ szlcPriceStr +" 结果:"+string(ratioRes),"ratio_sku_",2)
						break OuterLoop2;
					}

				if checkGoodsId != "" {
					break OuterLoop; //只跑一个跳出所有循环
				}
			}

			if checkGoodsId != "" {
				break;
			}

		}

    fmt.Print("计算完毕")

}