package service

import (
	"errors"

	"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"
	memberrenwallogstatus "go-admin/common/const/dicts/member_renwal_log_status"
	cDto "go-admin/common/dto"
	"go-admin/pkg/utility"
)

type MemberRenwaLog struct {
	service.Service
}

// GetPage 获取MemberRenwaLog列表
func (e *MemberRenwaLog) GetPage(c *dto.MemberRenwaLogGetPageReq, p *actions.DataPermission, list *[]models.MemberRenwaLog, count *int64) error {
	var err error
	var data models.MemberRenwaLog
	userIds := []int{}

	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("MemberRenwaLogService GetPage error:%s \r\n", err)
		return err
	}

	for _, v := range *list {
		if !utility.ContainsInt(userIds, v.UserId) {
			userIds = append(userIds, v.UserId)
		}
	}

	if len(userIds) > 0 {
		user := make([]models.LineUser, 0)
		e.Orm.Model(&models.LineUser{}).Where("id in (?)", userIds).Find(&user)
		for i := range *list {
			for j := range user {
				if (*list)[i].UserId == user[j].Id {
					(*list)[i].NickName = user[j].Nickname
				}
			}
		}
	}

	return nil
}

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

	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 GetMemberRenwaLog error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

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

// Update 修改MemberRenwaLog对象
func (e *MemberRenwaLog) Update(c *dto.MemberRenwaLogUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.MemberRenwaLog{}
	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("MemberRenwaLogService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

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

	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 RemoveMemberRenwaLog error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// 订单过期作废
func (e *MemberRenwaLog) OrderExpirated() {
	if err := e.Orm.Model(&models.MemberRenwaLog{}).
		Where("status = ? AND expiration_time <now()", memberrenwallogstatus.PENDING).
		Update("status", memberrenwallogstatus.EXPIRED).Error; err != nil {
		e.Log.Errorf("订单过期作废 error:%s \r\n", err)
	}
}
