package mallmanage

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

func GoodsCatCreate(c *gin.Context) {
	goodsCat := &models.GoodsCat{}
	if c.ShouldBindJSON(goodsCat) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	if goodsCat.Name == "" {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("name para err"), "参数错误")
		return
	}
	goodsCat.State = 2
	if goodsCat.Pid == 0 {
		goodsCat.Level = 1
	} else {
		if goodsCat.Level == 0 {
			logger.Error("level err:")
			app.Error(c, http.StatusInternalServerError, errors.New("goods cat level err"), "添加分类失败")
			return
		}
		//goodsCat.Pid = goodsCat.ID
		goodsCat.Level += 1
		goodsCat.ID = 0
	}
	exist, err := models.QueryRecordExist(fmt.Sprintf("SELECT * FROM goods_cat WHERE `name` = '%s' AND pid=%d",
		goodsCat.Name, goodsCat.Pid))
	if err != nil {
		logger.Error("exist spec err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("exist cat  err"), "添加分类失败")
		return
	}
	if exist {
		logger.Error("cat exist")
		app.Error(c, http.StatusInternalServerError, errors.New("cat exist  err"), "分类存在")
		return
	}

	err = orm.Eloquent.Create(goodsCat).Error
	if err != nil {
		logger.Errorf("err:%#v", logger.Field("err", err))
		msg := "添加分类失败"
		app.Error(c, http.StatusInternalServerError, errors.New("goods create err"), msg)
		return
	}

	app.OK(c, goodsCat, "添加分类成功")
	return
}

func GoodsCatList(c *gin.Context) {
	var goodsCats []models.GoodsCat
	err := orm.Eloquent.Table("goods_cat").Where("level=?", 1).Where("state=2").
		Order("sort DESC").Find(&goodsCats).Error
	if err != nil {
		logger.Error("goods cat list err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "获取分类列表失败")
		return
	}
	pids := make([]uint32, 0)
	for i, _ := range goodsCats {
		pids = append(pids, goodsCats[i].ID)
	}

	var subCat []models.GoodsCat
	err = orm.Eloquent.Table("goods_cat").Where("pid in (?)", pids).Where("state=2").
		Order("sort DESC").Find(&subCat).Error
	if err != nil {
		logger.Errorf("pCat err:%#v", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("goods create err"), "获取分类失败")
		return
	}
	pCatMap := make(map[uint32][]models.GoodsCat, 0)
	for i, _ := range subCat {
		pCatMap[subCat[i].Pid] = append(pCatMap[subCat[i].Pid], subCat[i])
	}
	for i, _ := range goodsCats {
		v, ok := pCatMap[goodsCats[i].ID]
		if ok {
			goodsCats[i].SubCats = v
		}
	}

	app.OK(c, goodsCats, "")
	return
}

func GoodsCatUpdate(c *gin.Context) {
	goodsCat := &models.GoodsCat{}
	if c.ShouldBindJSON(goodsCat) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := orm.Eloquent.Save(goodsCat).Error
	if err != nil {
		logger.Errorf("goods cat update err:%#v", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("goods cat update err"), "分类修改失败")
		return
	}

	app.OK(c, goodsCat, "分类修改成功")
	return
}

func GoodsCatDelete(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
	}
	err := orm.Eloquent.Table("goods_cat").Where("id=?", req.Id).Delete(&models.GoodsCat{}).Error
	if err != nil {
		logger.Errorf("err:%#v", logger.Field("err", err))
		msg := "删除商品分类失败"
		app.Error(c, http.StatusInternalServerError, errors.New("goods cat delete err"), msg)
		return
	}
	app.OK(c, nil, "操作成功")
	return
}

func GoodsSpecCreate(c *gin.Context) {
	spec := &models.Spec{}
	if c.ShouldBindJSON(spec) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	exist, err := models.QueryRecordExist(fmt.Sprintf("SELECT * FROM spec WHERE display_name = '%s'", spec.DisplayName))
	if err != nil {
		logger.Error("exist spec err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("exist spec  err"), "添加规格失败")
		return
	}
	if exist {
		logger.Error("spec exist")
		app.Error(c, http.StatusInternalServerError, errors.New("spec exist  err"), "规格存在")
		return
	}
	spec.State = 2
	err = orm.Eloquent.Create(spec).Error
	if err != nil {
		logger.Error("create spec err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("create spec  err"), "添加规格失败")
		return
	}

	app.OK(c, spec, "添加规格成功")
	return
}

func GoodsSpecList(c *gin.Context) {
	var specs []models.Spec
	err := orm.Eloquent.Table("spec").Order("sort DESC").Find(&specs).Error
	if err != nil {
		logger.Error("create spec list err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("create spec  err"), "获取规格列表失败")
		return
	}
	models.SpecListSetValue(specs)
	app.OK(c, specs, "")
	return
}

func GoodsSpecUpdate(c *gin.Context) {
	spec := &models.Spec{}
	if c.ShouldBindJSON(spec) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := orm.Eloquent.Save(spec).Error
	if err != nil {
		logger.Errorf("goods cat update err:%#v", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("goods cat update err"), "分类修改失败")
		return
	}

	app.OK(c, spec, "规格修改成功")
	return
}

func SpecValueCreate(c *gin.Context) {
	specValue := &models.SpecValue{}
	if c.ShouldBindJSON(specValue) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	exist, err := models.QueryRecordExist(
		fmt.Sprintf("SELECT * FROM spec_value WHERE display_value = '%s' AND spec_id=%d",
			specValue.DisplayValue, specValue.SpecId))
	if err != nil {
		logger.Error("exist spec err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("exist spec  err"), "添加规格值失败")
		return
	}
	if exist {
		logger.Error("spec exist")
		app.Error(c, http.StatusInternalServerError, errors.New("spec exist  err"), "规格值存在")
		return
	}
	specValue.State = 2
	err = orm.Eloquent.Create(specValue).Error
	if err != nil {
		logger.Error("create spec err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("create spec  err"), "添加规格值失败")
		return
	}

	app.OK(c, specValue, "添加规格值成功")
	return
}

func SpecValueList(c *gin.Context) {
	req := &struct {
		SpecId uint32 `json:"spec_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	var specValues []models.SpecValue
	err := orm.Eloquent.Table("spec_value").Where("spec_id=?", req.SpecId).Order("sort DESC").Find(&specValues).Error
	if err != nil {
		logger.Error("create spec list err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("create spec  err"), "获取规格值列表失败")
		return
	}

	app.OK(c, specValues, "")
	return
}

func SpecValueUpdate(c *gin.Context) {
	specValue := &models.SpecValue{}
	if c.ShouldBindJSON(specValue) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := orm.Eloquent.Save(specValue).Error
	if err != nil {
		logger.Errorf("goods cat update err:%#v", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, errors.New("goods cat update err"), "分类修改失败")
		return
	}

	app.OK(c, specValue, "规格修改成功")
	return
}
