<?php

namespace App\Models\Task;

use App\Http\Logic\Aside\Project\ProjectLogic;
use App\Models\Base;
use App\Services\Facades\Upload;

class Task extends Base
{
    //设置关联表名
    protected $table = 'gl_task';

    protected $appends = ['project_id_text', 'status_text', 'timeout'];

    const STATUS_WAIT = 0;
    const STATUS_DONGING = 1;
    const STATUS_DOWN = 2;


    public static function statusMap(){
        return [
            self::STATUS_WAIT    => '未开始',
            self::STATUS_DONGING   => '进程中',
            self::STATUS_DOWN  => '已完成',
        ];
    }

    public function getProjectIdTextAttribute(){
        if($this->project_id === null){
            return '';
        }
        $project =  ProjectLogic::instance()->getCacheInfo($this->project_id);
        return $project['title'] ?? '';
    }

    public function getStatusTextAttribute(){
        if($this->status === null){
            return '';
        }
        return self::statusMap()[$this->status] ?? '';
    }

    public function setAttachmentAttribute($value){
        $this->attributes['attachment'] = Upload::url2path($value);
    }

    public function getAttachmentAttribute($value){
        return Upload::path2url($value);
    }

    public function getTimeoutAttribute(){
        if($this->end_at === null){
            return 0;
        }
        if($this->status != self::STATUS_DOWN && strtotime($this->end_at) < time()){
            return floor((time() - strtotime($this->end_at)) / 60);
        }
        return 0;
    }

    public function owner(){
        return $this->hasMany(TaskOwner::class,'task_id','id');

    }

    public function follow(){
        return $this->hasMany(TaskFollow::class,'task_id','id');

    }
}