package service

import (
	"errors"
	"time"

	"github.com/go-admin-team/go-admin-core/logger"
	"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"
	memberbalancechangesource "go-admin/common/const/dicts/member_balance_change_source"
	memberwithdrawallogstatus "go-admin/common/const/dicts/member_withdrawal_log_status"
	cDto "go-admin/common/dto"
)

type MemberWithdrawalLog struct {
	service.Service
}

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

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

	userIds := make([]int, 0)
	users := make([]models.LineUser, 0)

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

	if err := e.Orm.Model(&models.LineUser{}).Where("id IN (?)", userIds).Find(&users).Error; err != nil {
		e.Log.Errorf("MemberWithdrawalLogService GetPage error:%s \r\n", err)
	}

	for index := range *list {
		for _, v := range users {
			if (*list)[index].UserId == v.Id {
				(*list)[index].UserName = v.Username
				(*list)[index].NickName = v.Nickname
			}
		}
	}

	return nil
}

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

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

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

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

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

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

// 审核
func (e *MemberWithdrawalLog) Process(req *dto.MemberWithdrawalLogApprovedReq) error {
	data := models.MemberWithdrawalLog{}

	if err := e.Orm.Model(&data).Where("id =?", req.Id).First(&data).Error; err != nil {
		return err
	}

	if data.Status != memberwithdrawallogstatus.PENDING {
		return errors.New("已审核请勿重复审核")
	}

	if req.Approval == 1 {
		data.Status = memberwithdrawallogstatus.APPROVED
	} else {
		data.Status = memberwithdrawallogstatus.REJECTED
	}

	if err := e.Orm.Model(&data).
		Where("status =?", memberwithdrawallogstatus.PENDING).
		Updates(map[string]interface{}{"status": data.Status, "remark": req.Remark}).Error; err != nil {
		return err
	}

	return nil
}

// 确认到账
func (e *MemberWithdrawalLog) Confirm(req *dto.MemberWithdrawalLogConfirmReq) error {
	data := models.MemberWithdrawalLog{}

	if err := e.Orm.Model(&data).Where("id =?", req.Id).First(&data).Error; err != nil {
		return err
	}

	if data.Status != memberwithdrawallogstatus.APPROVED {
		return errors.New("未审核请勿确认到账")
	}

	if req.ConfirmVal == 1 {
		data.Status = memberwithdrawallogstatus.SUCCESS
	} else {
		data.Status = memberwithdrawallogstatus.FAILED
	}

	balanceLog := models.MemberBalanceLog{
		UserId:       data.UserId,
		ChangeSource: memberbalancechangesource.WITH_DRAW,
		ChangeType:   2,
	}

	err := e.Orm.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&data).
			Where("status =?", memberwithdrawallogstatus.APPROVED).
			Updates(map[string]interface{}{"status": data.Status, "confirm_time": time.Now(), "hash": req.Hash, "remark": req.Remark}).Error; err != nil {
			return err
		}

		//提现成功 扣除冻结金额
		if data.Status == memberwithdrawallogstatus.SUCCESS {
			totalAmount := data.Amount.Add(data.Fee)
			balanceLog.Amount = totalAmount

			if err := tx.Exec("UPDATE member_balance set total_amount=total_amount-?,frozen_amount=frozen_amount-? where user_id=? and total_amount>=? and frozen_amount>=?", totalAmount, totalAmount, data.UserId, totalAmount, totalAmount).Error; err != nil {
				logger.Error("提现修改用户余额失败", err)
				return err
			}

			if err := tx.Create(&balanceLog).Error; err != nil {
				logger.Error("提现保存资金记录失败", err)
				return err
			}
		}

		return nil
	})

	return err
}
