package svc

import (
	"applet/app/db"
	"applet/app/e"
	"applet/app/utils"
	"encoding/json"
	"github.com/gin-gonic/gin"
)

func Goods(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	storeId := GetStoreId(c)

	arg["store_type"] = "0"
	if utils.StrToInt(storeId) > 0 {
		arg["uid"] = storeId
		storeData := db.GetStoreIdEg(MasterDb(c), storeId)
		if storeData.StoreType == 2 {
			storeData.StoreType = 1
		}
		if storeData.StoreType == 0 {
			arg["uid"] = "0"
		}
		arg["store_type"] = utils.IntToStr(storeData.StoreType)
	}
	goods := db.GetGoods(MasterDb(c), arg)
	goodsList := make([]map[string]interface{}, 0)

	if goods != nil {
		scheme, host := ImageBucket(c)

		for _, v := range *goods {
			speImageList := make([]string, 0)
			if v.IsSpeImageOn == 1 {
				json.Unmarshal([]byte(v.SpeImages), &speImageList)
			}
			tmp := map[string]interface{}{
				"id":            utils.IntToStr(v.Id),
				"title":         v.Title,
				"img":           ImageFormatWithBucket(scheme, host, v.Img),
				"info":          v.Info,
				"price":         v.Price,
				"stock":         utils.IntToStr(v.Stock),
				"is_single_sku": utils.IntToStr(v.IsSingleSku),
				"sale_count":    utils.IntToStr(v.SaleCount),
			}
			goodsList = append(goodsList, tmp)
		}
	}
	e.OutSuc(c, goodsList, nil)
	return
}
func GoodsSku(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	sku := db.GetGoodsSku(MasterDb(c), arg["goods_id"])
	skuList := make([]map[string]string, 0)
	if sku != nil {
		for _, v := range *sku {
			tmp := map[string]string{
				"sku_id":   utils.Int64ToStr(v.SkuId),
				"goods_id": utils.IntToStr(v.GoodsId),
				"price":    v.Price,
				"stock":    utils.IntToStr(v.Stock),
				"indexes":  v.Indexes,
				"sku":      v.Sku,
			}
			skuList = append(skuList, tmp)
		}
	}
	goods := db.GetGoodsId(MasterDb(c), arg["goods_id"])
	res := map[string]interface{}{
		"spe":      goods.Spe,
		"sku_list": skuList,
	}
	e.OutSuc(c, res, nil)
	return
}
func GoodsCoupon(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	returnData := CommCoupon(c, arg["amount"])
	e.OutSuc(c, returnData, nil)
	return
}
