package backstage_dao

import (
	"errors"
	"github.com/gogf/gf/frame/g"
	"youngmini_server/app/model/backstage_model"
)

// CreatBrand  品牌创建
func CreatBrand(brand *backstage_model.BrandReq) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("brand").
		Data(g.Map{"brand_name": brand.BrandName, "brand_logo": brand.BrandLogo,
			"brand_info": brand.BrandInfo, "brand_person": brand.BrandPerson,
			"brand_contact": brand.BrandContact, "brand_title": brand.BrandContact}).Insert()
	if err != nil {
		return errors.New("品牌创建失败,请重试")
	}
	return err
}

// DeleteBrand 品牌删除
func DeleteBrand(brandId string) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("brand").Where("id", brandId).Delete()
	if err != nil {
		return errors.New("删除失败，请重试")
	}
	return err
}

// UpdateBrand 品牌更新
func UpdateBrand(brand *backstage_model.BrandResp) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("brand").Data(brand).Where("id", brand.Id).OmitEmpty().Update()
	if err != nil {
		return errors.New("更新失败，请重试")
	}
	return err
}

// FindByIdBrand 根据id查询品牌信息
func FindByIdBrand(brandId string) (*backstage_model.BrandResp, error) {
	g.DB().SetDebug(true)
	brand := (*backstage_model.BrandResp)(nil)
	err := g.DB().Model("brand").Where("id", brandId).Scan(&brand)
	if err != nil || brand == nil {
		return nil, errors.New("该ID在数据库中不存在，请输入正确ID值")
	}
	return brand, nil
}

// FindAllBrand 分页查询
func FindAllBrand(indexPage int, pageSize int) ([]*backstage_model.BrandResp, error) {
	var brands []*backstage_model.BrandResp
	err := g.DB().Model("brand").Page(indexPage, pageSize).OrderDesc("updated_at").Scan(&brands)
	if err != nil {
		return nil, err
	}
	return brands, nil
}
