package storemanage

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/models"
	"go-admin/logger"
	"go-admin/pkg/jwtauth"
	"go-admin/tools/app"
	"net/http"
)

func StoreList(c *gin.Context) {
	req := &models.GetStoreReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	data, _ := c.Get(jwtauth.JwtPayloadKey)
	mapClaims := data.(jwtauth.MapClaims)
	sysUid := float64(0)
	if v, ok := mapClaims["identity"]; ok {
		sysUid = v.(float64)
	}
	fmt.Println("sysUid:", sysUid)

	req.SysUid = fmt.Sprintf("%.0f", sysUid)
	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	ret := map[string]interface{}{
		"count":      count,
		"list":       list,
		"pageIndex":  req.Page,
		"total_page": req.PageSize,
	}

	app.OK(c, ret, "")
}

func StoreDel(c *gin.Context) {
	req := struct {
		Id []uint32 `json:"id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	data := models.Store{}
	err := data.MDel(req.Id)
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusBadRequest, err, "参数错误")
		return
	}
	app.OK(c, nil, "删除成功")
}

// StoreAdd 新增门店
// @Summary 新增门店
// @Tags 门店管理
// @Produce json
// @Accept json
// @Param request body models.Store true "新增门店模型"
// @Success 200 {object} app.Response
// @Router /api/v1/store/add [post]
func StoreAdd(c *gin.Context) {
	store := &models.Store{}
	if c.ShouldBindJSON(store) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	store.IsOnline = 1
	if store.MemberService != 2 { // 会员服务：1 开启 2 不开启
		store.MemberService = 1 // 默认开启会员；没开启的门店默认在小程序端不展示，需前端判断
	}
	err := store.Add()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusBadRequest, err, "参数错误")
		return
	}
	app.OK(c, nil, "添加成功")
}

func StoreModify(c *gin.Context) {
	store := &models.Store{}
	if c.ShouldBindJSON(store) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	err := store.Modify()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusBadRequest, err, "参数错误")
		return
	}
	app.OK(c, nil, "修改成功")
}
