package goods

import (
	"errors"
	"spaceofcheng/services/models"
	"spaceofcheng/services/models/cases"
	"spaceofcheng/services/models/customer"
	"spaceofcheng/services/models/goods"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/models/system"
	"spaceofcheng/services/utils"
	"strings"
)

// GoodsServ 系统处理
type GoodsServ struct {
	ctx     *utils.Context
	dao     *goods.GoodsDAO
	caseDAO *cases.CaseDAO
	custDAO *customer.CustomerDAO
	userDAO *system.UserDAO
}

// NewGoodsServ 初始化
func NewGoodsServ(ctx *utils.Context) *GoodsServ {
	return &GoodsServ{
		ctx:     ctx,
		dao:     goods.NewGoodsDAO(ctx),
		caseDAO: cases.NewCaseDAO(ctx),
		custDAO: customer.NewCustomerDAO(ctx),
		userDAO: system.NewUserDAO(ctx),
	}
}

// GetListByCase 获取商品列表
// 微信端
func (s *GoodsServ) GetListByCase(id string) ([]goods.GoodsWithSpec, error) {
	res, err := s.dao.GetGoodsListOfCase(id)

	if err != nil {
		utils.LogError("获取商品列表失败: " + err.Error())
		return nil, errors.New("获取列表失败, 请重试")
	}

	return res, nil
}

// GetGoodsListPageNavi 获取商品列表
// 前端 - 非统计部分
func (s *GoodsServ) GetGoodsListPageNavi(name, typeID, caseID string, page, pagesize int) ([]goods.GoodsWithSpec, int64, error) {
	if page < 1 {
		page = 1
	}
	if pagesize < 0 {
		pagesize = 0
	}

	offset := (page - 1) * pagesize

	res, cnt, err := s.dao.GetGoodsListPageNavi(strings.ToLower(name), typeID, caseID, []int{pagesize, offset})
	if err != nil {
		utils.LogError("获取商品列表失败: " + err.Error())
		return nil, 0, errors.New("获取列表失败, 请重试")
	}

	return res, cnt, nil
}

// UpdateGoods 更新商品
// 如果没有则新增
func (s *GoodsServ) UpdateGoods(goods *model.TaGoods, images []string, specs []goods.SpecWithPrice) error {
	if err := utils.NewAuthEngine(s.ctx).CheckCase(goods.CaseId); err != nil {
		return err
	}

	if goods.GoodsId == "" {
		if err := s.dao.SaveGoods(goods, images, specs); err != nil {
			utils.LogError("保存商品失败: " + err.Error())
			return errors.New("保存商品失败, 请重试")
		}
	} else {
		if err := s.dao.UpdateGoods(goods, images, specs); err != nil {
			utils.LogError("更新商品失败: " + err.Error())
			return errors.New("更新商品失败, 请重试")
		}
	}

	return nil
}

// DeleteGoods 删除商品
func (s *GoodsServ) DeleteGoods(id string) error {
	goods, err := s.dao.GetGoodsByID(id)
	if err != nil {
		utils.LogError("查询商品失败: " + err.Error())
		return errors.New("校验商品失败")
	}

	if goods.Status == models.STATUS_DEL {
		return nil
	}

	if err := utils.NewAuthEngine(s.ctx).CheckCase(goods.CaseId); err != nil {
		return err
	}

	if err := s.dao.DeleteGoods(id); err != nil {
		utils.LogError("删除商品失败: " + err.Error())
		return errors.New("删除商品失败")
	}

	return nil
}
