<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace wap\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\helpers\Url;
use common\models\Common;
use qcbase\models\TaskStatus;
use home\modules\task\models\Category;

/**
 * 任务表 ({{qc_task}})
 *
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Task extends \home\modules\task\models\Task
{
    /**
     * 获取自己(负责、相关)的任务
     */
    public static function getMyTask($userId = null, $limit = 5, $order = ['create_time' => SORT_DESC])
    {
        $tasks = self::getMyTaskQuery($userId, $limit, $order);

        //取总数
        $countTasks = clone $tasks;
        $countTasks->limit(null);
        $count = $countTasks->count();

        $tasks = $tasks->all();

        return ['tasks' => $tasks, 'count' => $count];
    }

    /**
     * 获取我的任务查询对象
     *
     * @param int $userId 用户id
     * @param int $limit 限制条数
     * @param array $order 排序
     *
     * @return yii\db\Query 查询对象
     */
    public static function getMyTaskQuery($userId = null, $limit = null, $order = ['create_time' => SORT_DESC])
    {
        $userId = $userId == null ? Yii::$app->user->id : $userId;
        $query = static::find()
            ->where('(leader_id = :user_id or (leader_id = 0 and user_id = :user_id) or FIND_IN_SET(:user_id, join_ids))', [':user_id' => $userId])
            ->with('category', 'leader')
            ->orderBy($order)
            ->limit($limit)
            ->asArray()
            ->indexBy('task_id');
        if ($limit !== null) {
            $query->limit($limit);
        }

        //只取状态为显示的任务
        $showStatus = TaskStatus::getShowListStatus();
        $query->andWhere(['status_id' => $showStatus]);

        return $query;
    }


}
