<?php

namespace Modules\Task\Models\Traits;


use Modules\Task\Facades\TaskFacade;

trait TaskAttribute
{

    /**
     * Notes: 获取任务状态
     *
     * @Author: 玄尘
     * @Date: 2022/10/21 9:52
     */
    public function getUserTask($user): array
    {
        $data = [
            'all' => $this->task_number,
        ];
        if ($user) {
            $timeRange = TaskFacade::getTimeInterval($this->cycle);

            $taskUser = $this->taskUsers()
                ->when($this->cycle != 'one', function ($q) use ($timeRange) {
                    $q->whereBetween('task_at', $timeRange);
                })
                ->byUser($user)
                ->first();

            if ($taskUser) {
                return array_merge($data, [
                    'task_id' => $taskUser->id,
                    'finish'  => $taskUser->status,
                    'total'   => min($taskUser->total, $data['all']),
                ]);
            } else {
                return array_merge($data, [
                    'finish' => 0,
                    'total'  => 0,
                ]);
            }
        } else {
            return array_merge($data, [
                'finish' => 0,
                'total'  => 0,
            ]);
        }
    }

}
