package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/md"
	"applet/app/svc"
	"applet/app/utils"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

func AgentGoods(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	store := db.GetStoreIdEg(svc.MasterDb(c), utils.IntToStr(user.Info.Uid))
	arg["uid"] = utils.IntToStr(store.ParentUid)
	arg["store_type"] = "2"
	arg["is_up"] = "1"
	cate, total := db.GetStoreGoods(svc.MasterDb(c), arg)
	list := make([]map[string]string, 0)
	cateData := db.GetGoodsCateAllArg(svc.MasterDb(c), arg)
	cateList := make([]map[string]string, 0)
	cateMap := make(map[int]string)
	if cateData != nil {
		for _, v := range *cateData {
			tmp := map[string]string{
				"name": v.Title, "value": utils.IntToStr(v.Id),
			}
			cateList = append(cateList, tmp)
			cateMap[v.Id] = v.Title
		}
	}
	arg["uid"] = utils.IntToStr(user.Info.Uid)
	arg["store_type"] = "1"
	cateStoreData := db.GetGoodsCateAllArg(svc.MasterDb(c), arg)
	cateStoreList := make([]map[string]string, 0)
	if cateStoreData != nil {
		for _, v := range *cateStoreData {
			tmp := map[string]string{
				"name": v.Title, "value": utils.IntToStr(v.Id),
			}
			cateStoreList = append(cateStoreList, tmp)
		}
	}
	if cate != nil {
		stateMap := []string{"上架", "下架"}
		scheme, host := svc.ImageBucket(c)
		for _, v := range *cate {
			tmp := map[string]string{
				"id":        utils.IntToStr(v.Id),
				"title":     v.Title,
				"price":     v.Price,
				"info":      v.Info,
				"img_url":   svc.ImageFormatWithBucket(scheme, host, v.Img),
				"create_at": v.CreateAt.Format("2006-01-02 15:04:05"),
				"cate":      cateMap[v.Cid],
				"state":     stateMap[v.State],
			}
			list = append(list, tmp)
		}
	}
	res := map[string]interface{}{
		"list": list, "total": total, "cate_list": cateList, "store_cate_list": cateStoreList,
	}
	e.OutSuc(c, res, nil)
	return
}
func AgentGoodsCopy(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	sess := svc.MasterDb(c).NewSession()
	defer sess.Close()
	sess.Begin()
	var goods = make([]model.CommunityTeamGoods, 0)
	sess.In("id", strings.Split(arg["ids"], ",")).Find(&goods)
	for _, v := range goods {
		id := v.Id
		v.Id = 0
		v.Stock = 0
		v.Uid = user.Info.Uid
		v.StoreType = 1
		v.CreateAt = time.Now()
		v.UpdateAt = time.Now()
		v.Cid = utils.StrToInt(arg["cid"])
		_, err := sess.Insert(&v)
		if err != nil {
			sess.Rollback()
			e.OutErr(c, 400, e.NewErr(400, "添加失败"))
			return
		}
		var goodsSku = make([]model.CommunityTeamSku, 0)
		sess.Where("goods_id=?", id).Find(&goodsSku)
		for k1 := range goodsSku {
			goodsSku[k1].SkuId = 0
			goodsSku[k1].GoodsId = v.Id
			goodsSku[k1].Stock = 0
		}
		_, err = sess.Insert(&goodsSku)
		if err != nil {
			sess.Rollback()
			e.OutErr(c, 400, e.NewErr(400, "添加失败"))
			return
		}
	}
	sess.Commit()
	e.OutSuc(c, "success", nil)
	return
}
func AgentGoodsDetail(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	goods := db.GetGoodsById(svc.MasterDb(c), arg["id"])
	if goods == nil {
		e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
		return
	}
	cateData := db.GetGoodsCateAll(svc.MasterDb(c))
	cateList := make([]map[string]string, 0)
	cateMap := make(map[int]string)
	if cateData != nil {
		for _, v := range *cateData {
			tmp := map[string]string{
				"name": v.Title, "value": utils.IntToStr(v.Id),
			}
			cateList = append(cateList, tmp)
			cateMap[v.Id] = v.Title
		}
	}
	stateMap := []string{"上架", "下架"}
	scheme, host := svc.ImageBucket(c)
	res := md.BaseGoods{
		Id:           utils.IntToStr(goods.Id),
		Title:        goods.Title,
		Cid:          utils.IntToStr(goods.Cid),
		CategoryName: cateMap[goods.Cid],
		IsSingleSku:  utils.IntToStr(goods.IsSingleSku),
		Price:        goods.Price,
		Stock:        utils.IntToStr(goods.Stock),
		Img:          goods.Img,
		ImgUrl:       svc.ImageFormatWithBucket(scheme, host, goods.Img),
		Spe:          nil,
		Sort:         utils.IntToStr(goods.Sort),
		Info:         goods.Info,
		State:        utils.IntToStr(goods.State),
		StateStr:     stateMap[goods.State],
	}
	GoodsSpe := make([]md.GoodsSpe, 0)
	json.Unmarshal([]byte(goods.Spe), &GoodsSpe)
	for k, v := range GoodsSpe {
		if len(v.Values) == 0 {
			GoodsSpe[k].Values = make([]string, 0)
		}
	}
	res.Spe = GoodsSpe
	sku := db.GetGoodsSkuById(svc.MasterDb(c), goods.Id)
	skuList := make([]md.MallGoodsSku, 0)
	if sku != nil {
		for _, v := range *sku {
			skuMap := make([]map[string]string, 0)
			json.Unmarshal([]byte(v.Sku), &skuMap)
			tmp := md.MallGoodsSku{
				SkuID:   utils.Int64ToStr(v.SkuId),
				GoodsID: utils.IntToStr(v.GoodsId),
				Price:   v.Price,
				Stock:   utils.IntToStr(v.Stock),
				Indexes: v.Indexes,
				Sku:     skuMap,
			}
			skuList = append(skuList, tmp)
		}
	}
	if goods.IsSingleSku == 1 {
		skuList = nil
	}
	re := map[string]interface{}{
		"base":     res,
		"sku_list": skuList,
	}
	e.OutSuc(c, re, nil)
	return
}
