package withdrawal

import (
	"context"
	"encoding/json"

	"hfb_sys/backend/internal/model"
)

// 转换为用户DTO
func toDTO(w model.WithdrawalRequest) WithdrawalDTO {
	return WithdrawalDTO{
		ID:               w.ID,
		WithdrawNo:       w.WithdrawNo,
		UserID:           w.UserID,
		AmountCent:       w.AmountCent,
		FeeCent:          w.FeeCent,
		ActualAmountCent: w.ActualAmountCent,
		AccountType:      w.AccountType,
		AccountName:      w.AccountName,
		AccountNo:        w.AccountNo,
		BankName:         w.BankName,
		Status:           w.Status,
		ReviewRemark:     w.ReviewRemark,
		CreatedAt:        w.CreatedAt,
		UpdatedAt:        w.UpdatedAt,
		ReviewedAt:       w.ReviewedAt,
		PaidAt:           w.PaidAt,
	}
}

// 转换为管理员详细DTO

// 转换为管理员详细DTO
func (r *Repository) toDetailDTO(ctx context.Context, w model.WithdrawalRequest) (*WithdrawalDetailDTO, error) {
	db := r.db.WithContext(ctx)
	// 查询用户信息
	var user model.User
	db.Select("nickname, phone").First(&user, w.UserID)

	// 查询审核人信息
	var reviewedByName string
	if w.ReviewedBy != nil {
		var admin model.AdminUser
		if err := db.Select("nickname").First(&admin, *w.ReviewedBy).Error; err == nil {
			reviewedByName = admin.Nickname
		}
	}

	// 查询打款人信息
	var paidByName string
	if w.PaidBy != nil {
		var admin model.AdminUser
		if err := db.Select("nickname").First(&admin, *w.PaidBy).Error; err == nil {
			paidByName = admin.Nickname
		}
	}

	// 获取完整账号和收款二维码（管理员可见）
	fullAccountNo := w.AccountNo
	var certificateURLs []string
	if w.PaymentAccountID != nil {
		var paymentAccount model.UserPaymentAccount
		if err := db.First(&paymentAccount, *w.PaymentAccountID).Error; err == nil {
			// 解密账号
			decrypted, err := r.encryptor.Decrypt(paymentAccount.AccountNo)
			if err == nil {
				fullAccountNo = decrypted
			}
			// 解析收款二维码
			if paymentAccount.CertificateURLs != nil {
				json.Unmarshal(paymentAccount.CertificateURLs, &certificateURLs)
			}
		}
	}

	return &WithdrawalDetailDTO{
		ID:               w.ID,
		WithdrawNo:       w.WithdrawNo,
		UserID:           w.UserID,
		UserNickname:     user.Nickname,
		UserPhone:        user.Phone,
		AmountCent:       w.AmountCent,
		FeeCent:          w.FeeCent,
		ActualAmountCent: w.ActualAmountCent,
		PaymentAccountID: w.PaymentAccountID,
		AccountType:      w.AccountType,
		AccountName:      w.AccountName,
		AccountNo:        fullAccountNo,
		BankName:         w.BankName,
		BankBranch:       w.BankBranch,
		CertificateURLs:  certificateURLs,
		Status:           w.Status,
		ReviewedBy:       w.ReviewedBy,
		ReviewedByName:   reviewedByName,
		ReviewedAt:       w.ReviewedAt,
		ReviewRemark:     w.ReviewRemark,
		PaidBy:           w.PaidBy,
		PaidByName:       paidByName,
		PaidAt:           w.PaidAt,
		PaymentProofURL:  w.PaymentProofURL,
		PaymentRemark:    w.PaymentRemark,
		CreatedAt:        w.CreatedAt,
		UpdatedAt:        w.UpdatedAt,
	}, nil
}

// 生成提现单号
