package system

import (
	"errors"
	"sundynix-go/global"
	common "sundynix-go/model/commom/request"
	"sundynix-go/model/system"
	systemReq "sundynix-go/model/system/request"

	"gorm.io/gorm"
)

type ClientService struct{}

var ClientServiceApp = new(ClientService)

func (s *ClientService) SaveClient(client system.Client) error {
	if !errors.Is(global.DB.Where("client_id = ?", client.ClientId).First(&system.Client{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在重复clientId，请修改clientId")
	}
	return global.DB.Create(&client).Error
}

func (s *ClientService) UpdateClient(client system.Client) error {
	return global.DB.Model(&client).Where("id = ?", client.Id).Updates(&client).Error
}

func (s *ClientService) GetClientList(info systemReq.GetClientList) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Current - 1)
	db := global.DB.Model(&system.Client{})
	var clientList []system.Client
	if info.ClientId != "" {
		db = db.Where("client_id = ?", info.ClientId)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Find(&clientList).Error
	return clientList, total, err
}

func (s *ClientService) DeleteClientByIds(ids common.IdsReq) (err error) {
	return global.DB.Where("id IN (?)", ids.Ids).Delete(&system.Client{}).Error
}

func (s *ClientService) GetClientById(id string) (client system.Client, err error) {
	var c system.Client
	err = global.DB.Where("id = ?", id).First(&c).Error
	return c, err
}

func (s *ClientService) GetClientByClientId(clientId string) (client *system.Client, err error) {
	var c system.Client
	err = global.DB.Where("client_id = ?", clientId).First(&c).Error
	return &c, err
}
