<?php

namespace App\Http\Controllers;

use App\Http\Api\StudioApi;
use App\Http\Api\TaskApi;
use App\Http\Resources\TaskResource;
use App\Models\Project;
use App\Models\Task;
use App\Models\TaskAssignee;
use App\Services\AuthService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;

class TaskController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        //
        $user = AuthService::current($request);
        if (! $user) {
            return $this->error(__('auth.failed'), 401, 401);
        }

        switch ($request->input('view')) {
            case 'all':
                $table = Task::whereNotNull('owner_id');
                break;
            case 'instance':
                $table = Task::where('type', 'instance');
                break;
            case 'studio':
                $table = Task::where('owner_id', $user['user_uid']);
                break;
            case 'project':
                $projects = Project::where('uid', $request->input('project_id'))
                    ->orWhereJsonContains('path', $request->input('project_id'))
                    ->select('uid')
                    ->get();
                $table = Task::whereIn('project_id', $projects);
                break;
            default:
                // code...
                break;
        }
        if ($request->has('executor_id_includes')) {
            $table = $table->whereIn(
                'executor_id',
                explode(',', $request->input('executor_id_includes'))
            );
        }
        if ($request->has('executor_id_not-includes')) {
            $table = $table->whereNotIn(
                'executor_id',
                explode(',', $request->input('executor_id_not-includes'))
            );
        }
        if ($request->has('assignees_id_includes')) {
            $assigneesId = explode(',', $request->input('assignees_id_includes'));
            $assigneesTasks = TaskAssignee::whereIn('assignee_id', $assigneesId)
                ->select('task_id')->get();
            $table = $table->whereIn('id', $assigneesTasks);
        }
        if ($request->has('assignees_id_not-includes')) {
            $assigneesId = explode(',', $request->input('assignees_id_includes'));
            $assigneesTasks = TaskAssignee::whereIn('assignee_id', $assigneesId)
                ->select('task_id')->get();
            $table = $table->whereNotIn('id', $assigneesTasks);
        }
        // 指派给
        if ($request->has('assignees_id_null')) {
            $table = $table->doesntHave('task_assignees');
        }
        if ($request->has('assignees_id_not-null')) {
            $table = $table->has('task_assignees');
        }

        if ($request->input('sign_up_equals') === 'true') {
            $table = $table->whereNull('assignees_id')
                ->whereNull('executor_id');
        }
        /**某人参与的 */
        if ($request->has('participants_id_includes')) {
            $id = explode(',', $request->input('participants_id_includes'));
            $tasks_id = TaskAssignee::whereIn('assignee_id', $id)->select('task_id')->get();
            $table = $table->where(function ($query) use ($id, $tasks_id) {
                $query->whereIn('executor_id', $id)
                    ->orWhereIn('id', $tasks_id);
            });
        }

        if ($request->has('participants_id_not-includes')) {
            $id = explode(',', $request->input('participants_id_includes'));
            $tasks_id = TaskAssignee::whereIn('assignee_id', $id)->select('task_id')->get();
            $table = $table->where(function ($query) use ($id, $tasks_id) {
                $query->whereNotIn('executor_id', $id)
                    ->orWhereNotIn('id', $tasks_id);
            });
        }

        if ($request->has('keyword')) {
            $table = $table->where('title', 'like', '%'.$request->input('keyword').'%');
        }
        if ($request->has('status') && $request->input('status') !== 'all') {
            $table = $table->whereIn('status', explode(',', $request->input('status')));
        }
        $count = $table->count();

        $table = $table->orderBy(
            $request->input('order', 'created_at'),
            $request->input('dir', 'asc')
        );

        $table = $table->skip($request->input('offset', 0))
            ->take($request->input('limit', 1000));

        $result = $table->get();

        return $this->ok(
            [
                'rows' => TaskResource::collection(resource: $result),
                'count' => $count,
            ]
        );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        //
        $user = AuthService::current($request);
        if (! $user) {
            return $this->error(__('auth.failed'), 401, 401);
        }
        $studioId = StudioApi::getIdByName($request->input('studio_name'));

        if (! self::canEdit($user['user_uid'], $studioId)) {
            return $this->error(__('auth.failed'), 403, 403);
        }
        $new = Task::firstOrNew(
            [
                'id' => $request->input('id'),
            ],
            [
                'owner_id' => $studioId,
                'creator_id' => $user['user_uid'],
                'project_id' => $request->input('project_id'),
            ],
        );

        if (Str::isUuid($request->input('id'))) {
            $new->id = $request->input('id');
        } else {
            $new->id = Str::uuid();
        }
        $new->title = $request->input('title');
        $new->editor_id = $user['user_uid'];
        $new->parent_id = $request->input('parent_id');
        $new->type = $request->input('type');
        // 处理任务顺序
        if ($request->input('parent_id')) {
            $maxOrder = Task::where('parent_id', $request->input('parent_id'))
                ->max('order');
        } else {
            $maxOrder = Task::where('project_id', $request->input('project_id'))
                ->max('order');
        }
        if ($maxOrder === null) {
            $new->order = 1;
        } else {
            $new->order = $maxOrder + 1;
        }
        $new->save();

        return $this->ok(new TaskResource($new));
    }

    /**
     * Display the specified resource.
     *
     * @return Response
     */
    public function show(Task $task)
    {
        //
        return $this->ok(new TaskResource($task));
    }

    /**
     * Update the specified resource in storage.
     *
     * @return Response
     */
    public function update(Request $request, Task $task)
    {
        //
        $user = AuthService::current($request);
        if (! $user) {
            return $this->error(__('auth.failed'), 401, 401);
        }
        if (! self::canUpdate($user['user_uid'], $task)) {
            return $this->error(__('auth.failed'), 403, 403);
        }
        if ($request->has('title')) {
            $task->title = $request->input('title');
        }
        if ($request->has('description')) {
            $task->description = $request->input('description');
        }
        if ($request->has('category')) {
            $task->category = $request->input('category');
        }
        if ($request->has('progress')) {
            $task->progress = $request->input('progress');
        }
        if ($request->has('assignees_id')) {
            $delete = TaskAssignee::where('task_id', $task->id)->delete();
            $assigneesData = [];
            foreach ($request->input('assignees_id') as $key => $id) {
                $assigneesData[] = [
                    'id' => Str::uuid(),
                    'task_id' => $task->id,
                    'assignee_id' => $id,
                    'editor_id' => $user['user_uid'],
                ];
            }
            TaskAssignee::insert($assigneesData);
        }
        if ($request->has('roles')) {
            $task->roles = json_encode($request->input('roles'), JSON_UNESCAPED_UNICODE);
        }
        if ($request->has('executor_id')) {
            $task->executor_id = $request->input('executor_id');
        }
        if ($request->has('executor_relation_task_id')) {
            $task->executor_relation_task_id = $request->input('executor_relation_task_id');
        }
        if ($request->has('project_id')) {
            $task->project_id = $request->input('project_id');
        }
        if ($request->has('pre_task_id')) {
            TaskApi::setRelationTasks(
                $task->id,
                explode(',', $request->input('pre_task_id')),
                $user['user_uid'],
                'pre'
            );
        }
        if ($request->has('next_task_id')) {
            TaskApi::setRelationTasks(
                $task->id,
                explode(',', $request->input('next_task_id')),
                $user['user_uid'],
                'next'
            );
        }
        if ($request->has('is_milestone')) {
            $task->is_milestone = $request->input('is_milestone');
        }
        if ($request->has('order')) {
            $task->order = $request->input('order');
        }

        $task->editor_id = $user['user_uid'];
        $task->save();

        return $this->ok(new TaskResource($task));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return Response
     */
    public function destroy(Request $request, Task $task)
    {
        //
        $user = AuthService::current($request);
        if (! $user) {
            return $this->error(__('auth.failed'), 401, 401);
        }
        if (! self::canEdit($user['user_uid'], $task->owner)) {
            return $this->error(__('auth.failed'), 403, 403);
        }
        $task->delete();
        if ($task->trashed()) {
            return $this->ok('ok');
        } else {
            return $this->error('fail', 500, 500);
        }
    }

    public static function canEdit($user_uid, $owner_uid)
    {
        return $user_uid === $owner_uid;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  string  $user_uid
     * @param  Task  $task
     * @return bool
     */
    public static function canUpdate($user_uid, $task)
    {
        if ($user_uid === $task->owner_id) {
            return true;
        }
        if ($user_uid === $task->executor_id) {
            return true;
        }
        if (TaskAssignee::where('task_id', $task->id)
            ->where('assignee_id', $user_uid)
            ->exists()
        ) {
            return true;
        }

        return false;
    }
}
