package dao

import (
	"github.com/jinzhu/copier"
	"micro-bundle/internal/model"
	"micro-bundle/pb/bundle"
	"micro-bundle/pkg/app"
	commonErr "micro-bundle/pkg/err"
	"micro-bundle/pkg/msg"
)

func CreateBundle(req *model.BundleProfile) (res *bundle.CommonResponse, err error) {
	res = new(bundle.CommonResponse)
	err = app.ModuleClients.BundleDB.Model(&model.BundleProfile{}).Create(&req).Error
	if err != nil {
		res.Msg = msg.ErrorCreateBundleInfo
		return res, commonErr.ReturnError(err, msg.ErrorCreateBundleInfo, "创建套餐信息失败: ")
	}
	res.Msg = msg.SuccessCreateBundleInfo
	return
}

func UpdateBundle(req *model.BundleProfile) (res *bundle.CommonResponse, err error) {
	res = new(bundle.CommonResponse)
	err = app.ModuleClients.BundleDB.Model(&model.BundleProfile{}).Where("uuid = ?", req.UUID).Updates(req).Error
	if err != nil {
		res.Msg = msg.ErrorUpdateBundleInfo
		return res, commonErr.ReturnError(err, msg.ErrorUpdateBundleInfo, "更新套餐信息失败: ")
	}
	res.Msg = msg.SuccessUpdateBundleInfo
	return
}

func DeleteBundle(uuid string) (res *bundle.CommonResponse, err error) {
	res = new(bundle.CommonResponse)
	err = app.ModuleClients.BundleDB.Where("uuid = ?", uuid).Delete(&model.BundleProfile{}).Error
	if err != nil {
		res.Msg = msg.ErrorDeleteBundleInfo
		return res, commonErr.ReturnError(err, msg.ErrorDeleteBundleInfo, "删除套餐信息失败: ")
	}
	res.Msg = msg.SuccessDeleteBundleInfo
	return
}

func BundleList(req *bundle.BundleListRequest) (res *bundle.BundleListResponse, err error) {
	res = new(bundle.BundleListResponse)
	res.Bundles = make([]*bundle.BundleProfile, 0)
	bundles := make([]*model.BundleProfile, 0)

	query := app.ModuleClients.BundleDB.Model(&model.BundleProfile{})

	if req.Name != "" {
		query = query.Where("name like ?", "%"+req.Name+"%")
	}

	if req.Content != "" {
		query = query.Where("content like ?", "%"+req.Content+"%")
	}

	count := *query

	if err = query.Limit(int(req.PageSize)).Offset(int(req.Page-1) * int(req.PageSize)).Find(&bundles).Error; err != nil {
		return res, commonErr.ReturnError(err, msg.ErrorGetBundleList, "获取套餐列表失败: ")
	}

	_ = copier.CopyWithOption(&res.Bundles, &bundles, copier.Option{DeepCopy: true})

	var total int64

	count.Count(&total)

	res.Total = int32(total)

	return

}

func BundleDetail(uuid string) (res *bundle.BundleProfile, err error) {
	res = new(bundle.BundleProfile)
	bundle := new(model.BundleProfile)
	err = app.ModuleClients.BundleDB.Where("uuid = ?", uuid).First(&bundle).Error
	if err != nil {
		return res, commonErr.ReturnError(err, msg.ErrorGetBundleInfo, "获取套餐信息失败: ")
	}
	_ = copier.CopyWithOption(&res, &bundle, copier.Option{DeepCopy: true})
	return
}