package service

import (
	"go_sku_server/model"
	"go_sku_server/pkg/common"
	"go_sku_server/pkg/gredis"
	"strings"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/iancoleman/orderedmap"
	"github.com/syyongx/php2go"
	"github.com/tidwall/gjson"
)

type ZiyingService struct {
}

/*
 自营数据详情
查询商品详情(自营或者联营)
@doc  http://192.168.2.232:3000/project/128/interface/api/649

@param   goods_id                   支持批量,不建议超过40个,超过会导致处理时间超过2秒,进程异常 : 74564,65897,456464131
@param   power[newCustomer]         是否获取新客价  :true
@param   power[member]              是否获取会员价  :true
@param   power[mobile]              获取会员价时,用户有手机号时必填,用于会员价可见名单。活动价时必须,否则可能导致用户无法享受活动价 :13510507993
@param   power[email]               获取会员价时,用户有邮箱时必填,用于会员价可见名单。活动价时必须,否则可能导致用户无法享受活动价   ymx@ichunt.com
@param   power[user_id]             获取会员价时,必填,用于会员价可见名单。活动价时必须,否则可能导致用户无法享受活动价,如果用户未登录,可为空,用户是否可见活动价取决于配置 65139
@param   power[fast]                仅获取价格与库存 :1
@param   power[invoice]             增值税普通发票公司名字,活动价时必须,否则可能导致用户无法享受活动价  :深圳是猎芯科技有限公司
@param   power[special_invoice]     增值税专用发票公司名字,活动价时需要,否则可能导致用户无法享受活动价  : 深圳是猎芯科技有限公司
@param   power[verify_blacklist]    是否验证黑名单,用于折扣活动提交订单页面与后台下单 :true
*/
func (qs *ZiyingService) ZyGoodsDetail(ctx *gin.Context, goodsIds []string, ch chan sync.Map) {
	redisConn := gredis.Conn("search_r")
	redisConnSpu := gredis.Conn("spu")
	defer func() {
		//wg.Done();
		redisConn.Close()
		redisConnSpu.Close()
	}()

	skuArr := gredis.Hmget("search_r", "Self_SelfGoods", goodsIds) //批量获取商品详情
	fast := ctx.Request.FormValue("power[fast]")

	GoodsRes := sync.Map{}
	for goodsId, info := range skuArr {
		if gjson.Get(info, "goods_name").String() == "" {
			//fmt.Print("zy goods_name为空-----",goods_id,skuArr)
			GoodsRes.Store(goodsId, false)
			continue
		}

		//拼接属性
		attrJsonArr := gjson.Parse(gjson.Get(info, "attrs").String()).Array()
		attrs := make([]model.Attrs, 0)
		for _, d := range attrJsonArr {
			if d.Get("attr_name").String() == "" {
				continue
			}
			attrs = append(attrs, model.Attrs{
				AttrName:  d.Get("attr_name").String(),
				AttrValue: d.Get("attr_value").String(),
			})
		}

		//数组
		A := orderedmap.New() //初始化有序map,拼接data 数据
		A.Set("goods_id", common.MyInt64(goodsId))
		A.Set("goods_type", gjson.Get(info, "goods_type").Int())   //查询总条数
		A.Set("supplier_id", gjson.Get(info, "supplier_id").Int()) //查询总条数
		// A.Set("brand_id", gjson.Get(info, "brand_id").Int())       //

		otherAttrs := gjson.Get(info, "other_attrs").String()
		if otherAttrs == "" {
			A.Set("other_attrs", "")
		} else {
			B := make(map[string]string)
			pickType := gjson.Get(otherAttrs, "pick_type").String()
			length := gjson.Get(otherAttrs, "length").String()
			grossWegiht := gjson.Get(otherAttrs, "gross_wegiht").String()
			if pickType != "" {
				B["pick_type"] = pickType
			}
			B["length"] = length
			if grossWegiht != "" {
				B["gross_wegiht"] = grossWegiht
			}
			A.Set("other_attrs", B)
		}

		classId1 := gjson.Get(info, "class_id1").Int()
		classId2 := gjson.Get(info, "class_id2").Int()
		classId1Name := ""
		if classId1 > 0 {
			classId1Info, _ := gredis.String(redisConn.Do("HGET", "Self_SelfClassInfo", classId1))
			classId1Name = gjson.Get(classId1Info, "class_name").String()
		}

		classId2Name := ""
		if classId2 > 0 {
			classId2Info, _ := gredis.String(redisConn.Do("HGET", "Self_SelfClassInfo", classId2))
			classId2Name = gjson.Get(classId2Info, "class_name").String()
		}

		//迁移品牌获取,以前是读的自营品牌库,现在改成了读spu的品牌(其实就是联营品牌)以及获取标准品牌信息
		spuId := gjson.Get(info, "spu_id").Int()
		var standardBrand model.StandardBrand
		var brandId int64
		var brandName string
		if spuId != 0 {
			spuStr, _ := gredis.String(redisConnSpu.Do("HGET", "spu", spuId))
			brandId = gjson.Get(spuStr, "brand_id").Int()
			brandName, _ = gredis.String(redisConn.Do("HGET", "brand", brandId))
			var ly LyService
			standardBrand = ly.GetStandardBrand(brandId)
		}

		A.Set("brand_id_spu", brandId)
		A.Set("brand_name_spu", brandName)
		A.Set("standard_brand", standardBrand)

		A.Set("class_id1", classId1)                                  //
		A.Set("class_id2", classId2)                                  //
		A.Set("class_id1_name", classId1Name)                         //
		A.Set("class_id2_name", classId2Name)                         //
		A.Set("goods_name", gjson.Get(info, "goods_name").String())   //
		A.Set("status", gjson.Get(info, "status").Int())              //
		A.Set("encoded", gjson.Get(info, "encoded").String())         //
		A.Set("encap", gjson.Get(info, "encap").String())             //
		A.Set("packing", gjson.Get(info, "packing").Int())            //
		A.Set("goods_unit", gjson.Get(info, "goods_unit").Int())      //
		A.Set("goods_brief", gjson.Get(info, "goods_brief").String()) //

		moq := gjson.Get(info, "moq").Int()
		mpq := gjson.Get(info, "mpq").Int()

		//自营递增量
		Multiple := gjson.Get(info, "multiple").Int()
		if Multiple > 0 {
			Multiple = Multiple
		} else {
			if mpq > moq {
				Multiple = moq
			} else {
				Multiple = mpq
			}
		}
		A.Set("moq", moq)           //
		A.Set("mpq", mpq)           //
		A.Set("multiple", Multiple) //

		A.Set("update_time", gjson.Get(info, "update_time").Int())                 //
		A.Set("sku_name", strings.Trim(gjson.Get(info, "sku_name").String(), " ")) //
		A.Set("mpl", gjson.Get(info, "mpl").Int())                                 //
		A.Set("spu_id", spuId)                                                     //

		//处理库存
		A.Set("stock", 0)                         //默认库存为0
		dbStock := gjson.Get(info, "stock").Int() //当前db库存
		if dbStock > 0 {
			lockStock := qs.skuLockNum(&redisConn, goodsId) //当前锁库库存
			stockG := dbStock - lockStock                   //当前可购买库存
			if stockG > 0 {
				A.Set("actual_stock", dbStock) //锁定库存
				A.Set("stock", stockG)
			}
			A.Set("saler_atio", "") //
		}

		if len(attrs) == 0 {
			A.Set("attrs", "") //属性值
		} else {
			A.Set("attrs", attrs) //
		}

		A.Set("cost", gjson.Get(info, "cost").String())                          //
		A.Set("new_cost", gjson.Get(info, "new_cost").String())                  //
		A.Set("supplier_stock", gjson.Get(info, "supplier_stock").Int())         //
		A.Set("self_supplier_type", gjson.Get(info, "self_supplier_type").Int()) //

		//处理货期
		cnDeliveryTime := gjson.Get(info, "cn_delivery_time").String()
		if cnDeliveryTime == "" {
			cnDeliveryTime = "3-7工作日"
		}
		A.Set("cn_delivery_time", cnDeliveryTime) // 货期

		//查询品牌名称(作废,现在改成读联营的品牌库,之前有关联自营商品到spu_id)
		brand_id := gjson.Get(info, "brand_id").Int()
		brand_info, _ := gredis.String(redisConn.Do("HGET", "Self_Brand", brand_id))
		A.Set("brand_name", gjson.Get(brand_info, "brand_name").String())
		A.Set("brand_id", brand_id)

		if fast != "1" { //不是快速查询
			// 供应商名称
			supplier_id := gjson.Get(info, "supplier_id").String()
			supplier_name := ""
			if supplier_id != "" {
				supplierInfo, _ := gredis.String(redisConn.Do("HGET", "Self_SelfSupplierInfo", supplier_id))
				supplier_name = gjson.Get(supplierInfo, "supplier_name").String()
			}
			A.Set("supplier_name", supplier_name)

			//商品单位
			goodsUnit := gjson.Get(info, "goods_unit").String()
			goodsUnitName := ""
			if goodsUnit != "" {
				goodsUnitName, _ = gredis.String(redisConn.Do("HGET", "Self_Unit", goodsUnit))
			}
			A.Set("goods_unit_name", goodsUnitName)

			//包装名称
			packing := gjson.Get(info, "packing").String()
			packingName := ""
			if packing != "" {
				packingName, _ = gredis.String(redisConn.Do("HGET", "Self_Unit", packing))
			}
			A.Set("packing_name", packingName) //

			//mpq包装名称
			mpqUnitName := ""
			if packing != "" {
				mpqUnitName, _ = gredis.String(redisConn.Do("HGET", "Self_UnitAlias", packing))
			}
			A.Set("mpq_unit_name", mpqUnitName) //

			//图片
			img := gjson.Get(info, "goods_images").String()
			goodsImages := ""
			if img != "" {
				goodsImages, _ = gredis.String(redisConn.Do("HGET", "Self_SelfGoodsSource", img))
			}
			image := gjson.Get(goodsImages, "url").String()
			image = strings.Replace(image, "http://img.ichunt.com", "https://img.ichunt.com", 1)
			A.Set("goods_images", image)

			pdf := gjson.Get(info, "pdf").String()
			if pdf != "" {
				pdf, _ = gredis.String(redisConn.Do("HGET", "Self_SelfGoodsSource", pdf))
			}
			pdf = gjson.Get(pdf, "url").String()
			pdf = strings.Replace(pdf, "http://img.ichunt.com", "https://img.ichunt.com", 1)
			A.Set("pdf", pdf)
		}

		A.Set("scm_brand_name", gjson.Get(info, "scm_brand_name").String()) //

		//处理系数
		ratio, _ := gredis.String(redisConn.Do("HGET", "zy_ratio_sku", goodsId))
		var PriceAcXi float64 = 0 //系数
		if ratio != "" {
			PriceAcXi = gjson.Get(ratio, "price_ac").Float()
			//获取立创价格
			if gjson.Parse("szlc_price").String() == "" {
				A.Set("szlc_price", nil)
			} else {
				ladderPriceLc := make([]model.LadderPriceLc, 0)
				for _, v := range gjson.Parse("szlc_price").Array() {
					ladderPriceLc = append(ladderPriceLc, model.LadderPriceLc{
						Purchases: v.Get("Purchases").Int(),
						Price:     v.Get("price").Float(),
					})
				}
				A.Set("szlc_price", ladderPriceLc)
			}

			A.Set("allow_coupon", gjson.Get(ratio, "allow_coupon").String())
			A.Set("allow_presale", gjson.Get(ratio, "allow_presale").String())
			A.Set("ac_type", 6) //系数
		}

		//拼接梯度价格
		ladderPriceArr := gjson.Get(info, "ladder_price").Array()
		ladderPrice := make([]model.LadderPrice, 0)
		for _, v := range ladderPriceArr {
			if v.Get("purchases").String() == "" {
				continue
			}
			priceCn := php2go.Round(v.Get("price_cn").Float()*10000) / 10000
			if PriceAcXi == 0 {
				ladderPrice = append(ladderPrice, model.LadderPrice{
					Purchases: v.Get("purchases").Int(),
					PriceCn:   priceCn,
				})
			} else {
				ladderPrice = append(ladderPrice, model.LadderPrice{
					Purchases: v.Get("purchases").Int(),
					PriceCn:   priceCn,
					PriceAc:   PriceAcXi,
				})
			}
		}

		if len(ladderPrice) == 0 {
			A.Set("ladder_price", "") //
		} else {
			A.Set("ladder_price", ladderPrice) //
		}

		//处理限额
		goodsQuota, _ := gredis.String(redisConn.Do("HGET", "Self_goods_quota", goodsId))
		if goodsQuota != "" {
			A.Set("is_quota", 1)
			A.Set("quota_num", gjson.Get(goodsQuota, "num").Int())
		}
		//处理是否能购买
		if gjson.Get(info, "status").String() != "1" || len(ladderPriceArr) == 0 {
			A.Set("is_buy", 0)
		} else {
			A.Set("is_buy", 1)
		}

		//提前设置活动信息的默认值
		A.Set("activity_info", map[string]interface{}{})
		A.Set("has_gift_activity", 0)
		A.Set("gift_activity", map[string]interface{}{})

		if PriceAcXi == 0 { //没有系数价格才处理活动价
			//处理活动价
			A.Set("ac_type", 0)
			A.Set("allow_coupon", 1)
			AcPrice := qs.ActivityPrice(ctx, info)
			if AcPrice != nil {
				keys := AcPrice.Keys()
				for _, k := range keys {
					v, _ := AcPrice.Get(k)
					A.Set(k, v) //活动价格覆盖
				}
			}
		}

		//获取标签信息
		var tagService TagsService
		A.Set("goods_tag", tagService.GetTags(goodsId, gjson.Get(info, "self_supplier_type").Int()))

		//最后写入sync map
		(GoodsRes).Store(goodsId, A)
	}
	ch <- GoodsRes
}