<?php

namespace Modules\User\Models;

use App\Models\Model;
use App\Traits\OrderByIdDesc;
use Exception;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AccountLog extends Model
{

    use OrderByIdDesc;

    protected $table = 'user_account_logs';

    protected $dates = [
        'settle_at',
    ];

    protected $casts = [
        'source' => 'json',
    ];

    /**
     * Notes   : 账户
     *
     * @Date   : 2021/4/27 11:22 上午
     * @Author : < Jason.C >
     * @return BelongsTo
     */
    public function account(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'account_id');
    }

    public function rule(): BelongsTo
    {
        return $this->belongsTo(AccountRule::class, 'rule_id');
    }

    /**
     * Notes: 冻结一条账户记录
     *
     * @Author: <C.Jason>
     * @Date  : 2019/12/1 10:48 上午
     * @return bool
     * @throws Exception
     */
    public function freeze(): bool
    {
        if ($this->frozen == 0) {
            $this->account->decrement($this->type, $this->amount);
            $this->frozen  = 1;
            $this->balance = $this->account->{$this->type};
            $this->save();

            return true;
        } else {
            throw new Exception('账目已冻结');
        }
    }

    /**
     * Notes: 解冻一条记录
     *
     * @Author: <C.Jason>
     * @Date  : 2019/12/1 10:48 上午
     * @return bool
     * @throws Exception
     */
    public function thaw(): bool
    {
        if ($this->frozen == 1) {
            $this->account->increment($this->type, $this->amount);
            $this->frozen  = 0;
            $this->balance = $this->account->{$this->type};
            $this->save();

            return true;
        } else {
            throw new Exception('已经领取');
        }
    }

    public function getAmountFormatAttribute(): string
    {
        return ($this->amount > 0 ? '+' : '').$this->amount;
    }

}
