package goods

import (
	"encoding/json"
	"errors"
	"spaceofcheng/services/controllers"
	goodsModel "spaceofcheng/services/models/goods"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/service/goods"
	"spaceofcheng/services/utils"
	"strings"
)

// GoodsController 商品
type GoodsController struct {
	serv *goods.GoodsServ
	controllers.BaseController
}

// Constructor 初始化 Controller
// @Title Constructor
// @Description 初始化 Controller, 系统自动调用
func (c *GoodsController) Constructor() {
	c.serv = goods.NewGoodsServ(c.Context)
}

// GetListByCase 获取案场商品列表
// 管理端
func (c *GoodsController) GetListByCase() {
	page, _ := c.GetInt("page")
	pagesize, _ := c.GetInt("pagesize")
	caseID := c.GetString("caseid")
	goodsName := c.GetString("name")
	goodsType := c.GetString("type")

	goodsList, cnt, err := c.serv.GetGoodsListPageNavi(goodsName, goodsType, caseID, page, pagesize)
	if err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON(map[string]interface{}{
		"list":     goodsList,
		"pagesize": pagesize,
		"pagenum":  cnt,
		"page":     page,
	})
}

// GetListForWechat 获取商品列表
// 微信端
func (c *GoodsController) GetListForWechat() {
	caseID := c.GetString("caseid")
	if caseID == "" {
		c.ResponseError(errors.New("请指定案场"))
	}

	goodsList, err := c.serv.GetListByCase(caseID)
	if err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON(map[string]interface{}{
		"list": goodsList,
	})
}

// UpdateGoods 新增或者更新商品
func (c *GoodsController) UpdateGoods() {
	// 商品
	gds := model.TaGoods{}
	if err := c.ParseForm(&gds); err != nil {
		utils.LogError("接收商品参数失败: " + err.Error())
		c.ResponseError(errors.New("接收商品参数失败"))
	}

	// 图片
	images := strings.Split(c.GetString("images"), ",")

	// 规格
	var specs []goodsModel.SpecWithPrice
	specsJSON := c.GetString("specs")
	if err := json.Unmarshal([]byte(specsJSON), &specs); err != nil {
		utils.LogError("接收商品参数失败: " + err.Error())
		c.ResponseError(errors.New("接收商品参数失败"))
	}

	goodsID := c.GetString(":id")
	gds.GoodsId = goodsID

	if err := c.serv.UpdateGoods(&gds, images, specs); err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON(map[string]interface{}{
		"goods":  gds,
		"images": images,
		"specs":  specs,
	})
}

// DeleteGoods 删除商品
func (c *GoodsController) DeleteGoods() {
	goodsID := c.GetString(":id")
	if goodsID == "" {
		c.ResponseError(errors.New("没有需要删除的商品"))
	}

	if err := c.serv.DeleteGoods(goodsID); err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON("ok")
}
