<?php

namespace App;

use App\Traits\ModelLogChanging;
use App\Traits\ModelTimeFormat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Builder;

class Demand extends Model
{
    use ModelLogChanging;
    use ModelTimeFormat;

    protected $fillable = ['authority_id', 'initiator', 'description', 'type', 'status', 'handler'];

    // 需求类型
    protected static $type = ['需求', '问题'];

    // 状态
    protected static $status = ['未处理', '处理中', '已处理'];


    public function authority(): BelongsTo
    {
        return $this->belongsTo(Authority::class);
    }

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

    public function handle(): BelongsTo
    {
        return $this->belongsTo(User::class, 'handler', 'id');
    }

    public function uploadFile(): HasOne
    {
        return $this->hasOne(UploadFile::class, 'table_id', 'id')->where('table_name', 'Demands');
    }

    public function processes(): HasMany
    {
        return $this->hasMany(DemandProcess::class, 'demand_id', 'id');
    }

    public function scopeFilter($query, $filters)
    {
        return $filters->apply($query);
    }

    /**
     * 保存文件创建对应的文件对象
     *
     * @param $fileName
     * @param  $fileSuffix
     * @return Builder|Model
     */
    public function saveFile($fileName,$fileSuffix)
    {
        return UploadFile::query()->create(['table_name' => $this->getTable(), 'table_id' => $this['id'], 'url' => '/files/issue/'.$fileName, 'type' => $fileSuffix]);
    }

    /**
     * 删除需求的同时删除处理过程
     *
     * @return bool|null
     * @throws \Exception
     */
    public function delete()
    {
        $this->processes()->delete();
        return parent::delete();
    }

}
