<?php

namespace Modules\Project\Entities;

use Illuminate\Database\Eloquent\Model;

class UserWalletLog extends Model
{
    protected $fillable = ['user_id', 'value', 'type','type_id', 'wallet_type'];

    protected static $modelMap = [
        'order' => Order::class,
        ];

    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            if (!$model->user_id) {
                throw new \Exception('用户信息错误');
            }
        });

        static::saved(function ($model) {
            $sum = $model->where('user_id', $model->user_id)->where('wallet_type', $model->wallet_type)->sum('value');
            UserWallet::where('user_id', $model->user_id)->update([$model->wallet_type => $sum]);
        });
    }

    public function getTypeNameAttribute()
    {
        $arr = [
            UserWallet::CHARGE => '充值',
            UserWallet::PAY_ORDER => '订单支付',
            UserWallet::WITHDRAWAL => '提现',
            UserWallet::ORDER_REWARD => '订单奖励',
            UserWallet::ADMIN_ADD => '后台增加',
            UserWallet::WITHDRAWAL_FAIL_BACK => '提现失败退回',
        ];

        return $arr[$this->type];
    }

    public function __call($method, $parameters)
    {
        if (isset(self::$modelMap[$method])) {
            return $this->belongsTo(self::$modelMap[$method], 'type_id');
        }

        return parent::__call($method, $parameters); // TODO: Change the autogenerated stub
    }
}
