<?php

namespace App\Modules\UserTask\Services;

use App\Modules\UserTask\Models\Task;
use App\Modules\UserTask\Models\UserRepeatTask;

/**
 * 重复任务
 * @property UserRepeatTask $model
 */
class RepeatTask extends BaseTask
{
    private $model;

    public function __construct(int $uid, ?Task $task)
    {
        $this->model = UserRepeatTask::model($uid);
        parent::__construct($uid, $task);
    }

    public function checkUserTask()
    {
        $date = $this->getDate();
        return $this->model::where('task_id', $this->task->id)
            ->where('uid', $this->uid)
            ->where('date', '>=', $date)
            ->exists();
    }

    public function addUserTask()
    {
        $this->model->create([
            'date' => date('Y-m-d'),
            'uid' => $this->uid,
            'task_id' => $this->task->id,
            'status' => self::under_status,
            'type' => $this->task->reward_type,
            'value' => $this->task->value,
        ]);
    }

    public function findUserTask(int $status)
    {
        $date = $this->getDate();
        return $this->model::where('task_id', $this->task->id)
            ->where('uid', $this->uid)
            ->where('date', '>=', $date)
            ->where('status', $status)
            ->first();
    }

    /**
     * 判断条件是否符合
     * @return bool
     */
    public function judgeUpTo()
    {
        return true;
    }

    /**
     * 处理用户符合任务流程
     */
    public function handleUpToUserTask()
    {
        $user_task = $this->findUserTask(self::under_status);
        if ($user_task && $this->judgeUpTo()) {
            $user_task->status = self::up_status;
            $user_task->save();
        }
    }

    /**
     * 获取日期
     */
    private function getDate()
    {
        $diff_day = $this->task->repeat_cycles - 1;
        if ($diff_day > 0) {
            $date = date('Y-m-d', strtotime("-{$diff_day} days"));
        } else {
            $date = date('Y-m-d');
        }
        return $date;
    }
}
