package service

import (
	"database/sql"
	"errors"
	"time"

	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"

	"go-admin/app/admin/models"
	"go-admin/app/admin/service/dto"
	"go-admin/common/actions"
	cDto "go-admin/common/dto"
)

type LineUserProfitLogs struct {
	service.Service
}

// GetPage 获取LineUserProfitLogs列表
func (e *LineUserProfitLogs) GetPage(c *dto.LineUserProfitLogsGetPageReq, p *actions.DataPermission, list *[]models.LineUserProfitLogs, count *int64) error {
	var err error
	var data models.LineUserProfitLogs

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("LineUserProfitLogsService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取LineUserProfitLogs对象
func (e *LineUserProfitLogs) Get(d *dto.LineUserProfitLogsGetReq, p *actions.DataPermission, model *models.LineUserProfitLogs) error {
	var data models.LineUserProfitLogs

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetLineUserProfitLogs error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建LineUserProfitLogs对象
func (e *LineUserProfitLogs) Insert(c *dto.LineUserProfitLogsInsertReq) error {
	var err error
	var data models.LineUserProfitLogs
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("LineUserProfitLogsService Insert error:%s \r\n", err)
		return err
	}
	return nil
}

// Update 修改LineUserProfitLogs对象
func (e *LineUserProfitLogs) Update(c *dto.LineUserProfitLogsUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.LineUserProfitLogs{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("LineUserProfitLogsService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// Remove 删除LineUserProfitLogs
func (e *LineUserProfitLogs) Remove(d *dto.LineUserProfitLogsDeleteReq, p *actions.DataPermission) error {
	var data models.LineUserProfitLogs

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveLineUserProfitLogs error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// GetProfitInfoByApiId 获取盈利统计
// apiId api-user 的id
// totalProfit 总盈利
// todayProfit 今日盈利
func (e *LineUserProfitLogs) GetProfitInfoByApiId(apiId int) (totalProfit, todayProfit sql.NullFloat64) {
	//var totalProfit, todayProfit decimal.Decimal
	e.Orm.Model(&models.LineUserProfitLogs{}).Where("api_id = ?", apiId).Select("SUM(amount) as total_profit").Scan(&totalProfit)
	e.Orm.Model(&models.LineUserProfitLogs{}).Where("api_id = ? AND created_at >= ?", apiId, time.Now().Truncate(24*time.Hour)).Select("SUM(amount) as today_profit").Scan(&todayProfit)
	return
}

// GetProfitInfoByUserId 获取盈利统计
// apiId api-user 的id
// totalProfit 总盈利
// todayProfit 今日盈利
func (e *LineUserProfitLogs) GetProfitInfoByUserId(userId int) (totalProfit, todayProfit sql.NullFloat64) {
	//var totalProfit, todayProfit decimal.Decimal
	e.Orm.Model(&models.LineUserProfitLogs{}).Where("user_id = ?", userId).Select("SUM(amount) as total_profit").Scan(&totalProfit)
	e.Orm.Model(&models.LineUserProfitLogs{}).Where("user_id = ? AND created_at >= ?", userId, time.Now().Truncate(24*time.Hour)).Select("SUM(amount) as today_profit").Scan(&todayProfit)
	return
}
