<?php

namespace app\admin\model;

use app\admin\library\Auth;
use think\model\relation\HasMany;
use Throwable;
use think\model;
use think\model\relation\BelongsTo;

/**
 * UserMoneyLog 模型
 * 1. 创建余额日志自动完成会员余额的添加
 * 2. 创建余额日志时，请开启事务
 */
class UserMoneyLog extends model
{
    protected $autoWriteTimestamp = true;
    protected $updateTime         = false;

    /**
     * 入库前
     * @throws Throwable
     */
//    public static function onAfterInsert($model): void
//    {
//        $new = new MoneyLogHistory();
//        $new->money_log_id = $model->id;
//        $new->bank_befter = '';
//        $new->bank_after = $model->bank->bank_name;
//        $new->create_time = time();
//        $new->save();
//
//    }

    public static function onAfterUpdate($model): void
    {
        $history  = MoneyLogHistory::where('money_log_id', $model->id)->find();
        $new = new MoneyLogHistory();
        $new->money_log_id = $model->id;
        $new->bank_befter = $history->bank_after ?? '';
        $new->bank_after = $model->bank->bank_name;
        $new->created_by = Auth::instance()->getInfo()['id'];
        $new->create_time = time();
        $new->save();

    }

    public function getMoneyAttr($value): string
    {
        return bcdiv($value, 100, 2);
    }

    public function setMoneyAttr($value): string
    {
        return bcmul($value, 100, 2);
    }

    public function getBeforeAttr($value): string
    {
        return bcdiv($value, 100, 2);
    }

    public function setBeforeAttr($value): string
    {
        return bcmul($value, 100, 2);
    }

    public function getAfterAttr($value): string
    {
        return bcdiv($value, 100, 2);
    }

    public function setAfterAttr($value): string
    {
        return bcmul($value, 100, 2);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function admin(): BelongsTo
    {
        return $this->belongsTo(Admin::class, 'created_by');
    }

    public function scoreLog(): hasMany
    {
        return $this->hasMany(UserScoreLog::class, 'money_log_id');
    }

    public function bank(): BelongsTo
    {
        return $this->belongsTo(Bank::class, 'bank_id');
    }
}