package service

import (
	"go_sku_server/model"
	"go_sku_server/pkg/gredis"
	"go_sku_server/service/sorter"
	"sort"
	"strings"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/util/gconv"
	"github.com/gomodule/redigo/redis"
	"github.com/tidwall/gjson"
)

type LyService struct {
}

type Power struct {
	UserId          string `json:"user_id"`
	Mobile          string `json:"mobile"`
	Email           string `json:"email"`
	Member          string `json:"member"`
	VerifyBlacklist string `json:"verify_blacklist"`
	Invoice         string `json:"invoice"`
	SpecialInvoice  string `json:"special_invoice"`
}

/*
 联营数据详情
*/
func (ls *LyService) LyGoodsDetail(ctx *gin.Context, goodsIds []string, ch chan sync.Map) {
	redisConn := gredis.Conn("search_r")
	defer func() {
		redisConn.Close()
	}()
	fast := ctx.Request.FormValue("power[fast]")
	//是否展示属性
	showAttr := ctx.Request.FormValue("show_attr")
	//是否展示在途库存
	showStockInfo := ctx.Request.FormValue("show_stock_info")
	//批量获取商品详情
	skuArr := gredis.Hmget("default_r", "sku", goodsIds)
	//为了性能着想,这边也先去批量获取spu的信息
	var spuService SpuService
	spuList := spuService.getSpuList(skuArr)

	GoodsRes := sync.Map{}
	for goodsId, skuStr := range skuArr {
		if skuStr == "" {
			GoodsRes.Store(goodsId, false)
			continue
		}
		//初始化有序map,拼接data 数据
		sku := model.InitSkuData(skuStr)
		sku.GoodsId = goodsId
		spu := spuList[sku.SpuId]
		//读取包装字段的缓存
		if sku.SupplierId == 7 {
			//sku_raw_map哪里写入(成意写的)
			packing, _ := redis.String(redisConn.Do("HGET", "sku_raw_map", goodsId))
			sku.Packing = gjson.Get(packing, "pack").String()
		}
		sku = ls.GetGoodsImages(sku, spu)
		//pdf
		pdf := gjson.Get(spu, "pdf").String()
		// spuLargeImage := gjson.Get(spu, "images_l").String()
		if pdf != "" {
			pdf = strings.Replace(pdf, "http://img.ichunt.com", "https://img.ichunt.com", 1)
			//还要针对如果是自己的上传服务的pdf文件,还要补上类型用于预览
			if (strings.Contains(pdf, "files.ichunt.net") || strings.Contains(pdf, "file.liexindev.net")) && !strings.Contains(pdf, "fileType=pdf") {
				pdf += "?fileType=pdf"
			}
			sku.Pdf = pdf
		}

		//处理分类
		//fast的参数含义,为了节省开销性能的参数,传1就不会去分类这些参数
		if fast != "1" {
			sku = ls.GetGoodsClass(sku, spu)
		}

		//获取商品名称
		if sku.GoodsName == "" {
			sku.GoodsName = gjson.Get(spu, "spu_name").String()
		}

		//获取品牌名称
		brandId := gjson.Get(spu, "brand_id").Int()
		brandName, _ := redis.String(redisConn.Do("HGET", "brand", brandId))
		sku.BrandName = brandName
		//获取税务信息
		if fast != "1" { //仅提供价格和库存
			if sku.GoodsName != "" && brandId != 0 {
				sku.ErpTax = ls.GetErpTax(sku.GoodsName, brandName)
			}
			sku.SupplierName = ls.GetPoolSupplierName(sku.SupplierId)
			if showAttr == "1" {
				//获取属性
				sku.Attrs = ls.GetSpuAttr(sku.SpuId)
			}
			if sku.Attrs == nil {
				sku.Attrs = []interface{}{}
			}
		}

		if showStockInfo == "1" && sku.OldGoodsId != 0 {
			sku.StockInfo = ls.getStockInfo(sku.SupplierId, sku.OldGoodsId)
		}
		//格式化为对象返回
		if sku.StockInfo == nil {
			type StockInfoResult struct {
			}
			sku.StockInfo = new(StockInfoResult)
		}

		//获取供应链标准品牌
		//什么是供应链的标准品牌  供应链那边报关的时候要求他们的标准品牌,所以要吧自己的品牌映射上去
		//继来那边对接的标准品牌(下单的时候)
		sku.ScmBrand = ls.GetScmBrand(brandId)

		//获取新版的标准品牌
		sku.StandardBrand = ls.GetStandardBrand(brandId)

		//处理过期,todo 2022.7.13 专卖没有过期
		if sku.SupplierId != 17 && gjson.Get(skuStr, "is_expire").Int() != 0 {
			sku.LadderPrice = nil
		}

		//处理活动
		sku.AcType = 0
		sku.AllowCoupon = 1
		sku.BrandId = brandId

		//这里获取活动价格和活动类型
		sku = ls.GetActivity(sku)

		//处理阶梯价数据
		if len(sku.LadderPrice) > 0 {
			//排序
			sort.Sort(sorter.LadderPriceSorter(sku.LadderPrice))
			//取出第一个阶梯价
			purchases := sku.LadderPrice[0].Purchases
			if purchases > sku.Moq {
				sku.Moq = purchases
			}
		}
		//获取系数
		sku = ls.GetCoefficientAndPrice(sku)

		//仅提供价格和库存
		if fast != "1" {
			if sku.SupplierId != 0 {
				sku.SuppExtendFee = ls.GetExtendFee(sku.SupplierId, sku.Canal)
			}
			//还要处理货期
			delivery := ls.GetDelivery(sku.SupplierId, sku.Canal)
			if delivery["cn_delivery"] != "" {
				sku.CnDeliveryTime = delivery["cn_delivery"]
			}
			if delivery["hk_delivery"] != "" {
				sku.HkDeliveryTime = delivery["hk_delivery"]
			}
		}

		//处理是否可以购买
		if sku.Mpq == 0 {
			sku.Mpq = 1
		}

		if len(sku.LadderPrice) > 0 {
			sku.LadderPriceResult = sku.LadderPrice
		} else {
			sku.LadderPriceResult = []int{}
		}

		//这边有个临时逻辑,如果供应商id是TI的,就库存为0
		// if sku.SupplierId == 1679 {
		// 	sku.Stock = 0
		// }

		//判断是否可以购买
		sku.IsBuy = ls.GetIsBuy(sku)

		//过期修改库存为0
		if sku.IsExpire == 1 && sku.SupplierId != 17 {
			sku.Stock = 0
		}

		var TagService TagsService
		sku.GoodsTag = TagService.GetTags(sku.GoodsId, 0)

		//用spuInfo补全信息
		sku = ls.CombineSup(sku, spu)
		//最后一步,将sku的全部信息放到有序map里面
		GoodsRes.Store(goodsId, sku)
		//(*goodsRes)[goodsId] = A

	}
	ch <- GoodsRes
}

//获取活动
func (ls *LyService) GetActivity(sku model.LySku) model.LySku {
	//去判断是否有活动(促销打折活动和满赠活动)
	checkData := model.ActivityCheckData{
		SupplierId:      int(sku.SupplierId),
		BrandId:         int(sku.BrandId),
		StandardBrandId: int(sku.StandardBrand.StandardBrandId),
		GoodsId:         sku.GoodsId,
		Canal:           sku.Canal,
		ClassId:         sku.ClassID2,
	}
	var activityService ActivityService
	priceActivity, giftActivity := activityService.GetActivityData(checkData)
	if priceActivity.HasActivity {
		sku.AcType = 10
		sku.Ratio = priceActivity.Ratio
		sku.RatioUs = priceActivity.RatioUs

		sku.ActivityInfo = priceActivity
	}
	if giftActivity.HasActivity {
		sku.HasGiftActivity = gconv.Int(giftActivity.HasActivity)
		sku.GiftActivity = giftActivity
	}

	//获取是否能使用优惠券
	if giftActivity.AllowCoupon == 2 || priceActivity.AllowCoupon == 2 {
		sku.AllowCoupon = 2
	}
	return sku
}