<?php

namespace Modules\Project\Entities;

use Modules\Base\Entities\BaseModel;

class Card extends BaseModel
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'org', 'code', 'type', 'name', 'number', 'branch', 'phone', 'is_default',
    ];

    /**
     * 用户
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 银行卡信息
     */
    public function bank()
    {
        return $this->belongsTo(Bank::class, 'code', 'code');
    }

    /**
     * {@inheritdoc}
     */
    protected static function boot()
    {
        parent::boot();
        static::saving(function (self $model) {
        });

        static::creating(function (self $model) {
            //static::setDefault($model);
        });

        static::saved(function (self &$model) {
            static::setDefault($model);
        });

        static::deleted(function (self $model) {
            if ($model->is_default) {
                static::where('user_id', $model->user_id)
                    ->limit(1)
                    ->update(['is_default' => 1]);
            }
        });
    }

    protected static function setDefault($table)
    {
        if ($table->is_default) {
            static::where('user_id', $table->user_id)
                ->where('id', '<>', $table->id)
                ->update(['is_default' => 0]);
        } else {
            $count = static::where('user_id', $table->user_id)
                ->where('is_default', 1)
                ->count();
            if ($count < 1) {
                static::where('user_id', $table->user_id)
                    ->where('id', $table->id)
                    ->update(['is_default' => 1]);
                $table->is_default = 1;
            }
        }
    }
}
