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

namespace home\modules\task\controllers;

use Yii;
use home\controllers\Controller;
use home\modules\task\models\Task;
use home\modules\task\models\Category;
use qcbase\models\TaskStatus;
use common\components\Tool;
use yii\data\ActiveDataProvider;
use common\models\Common;
use home\modules\blog\models\Blog;
use common\behaviors\TreeDeleteFilter;
use home\behaviors\TaskAccessControlFilter;
use home\behaviors\CreateTaskFilter;
use common\models\PermissionScope;
use yii\web\ForbiddenHttpException;

/**
 * 任务控制器
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class TaskController extends Controller
{

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        if (array_key_exists('save', $_POST)) {
            $actions['create']['to'] = ['list'];
        }
        $actions['update']['to'] = ['list'];
        $actions['delete'] = [
            'class' => 'home\actions\TrashDelete',
            'to' => ['list'],
            'trashModel' => 'home\modules\task\models\TaskTrash',
        ];
        $actions['view']['enableScopeAccess'] = false;
        $actions['update']['enableScopeAccess'] = false;

        $actions['create']['layout'] = '//modal';
        $actions['view']['layout'] = '//modal';
        $actions['update']['layout'] = '//modal';

        return $actions;
    }

    /**
     * 控制器的行为事件
     *
     * @key deleteFilter 树结构删除过滤器
     * @key taskAccess 任务权限过滤器
     * @key createFirstTask 建立一级任务过滤器
     */
    public function behaviors()
    {
        $request = Yii::$app->request;
        return [
            'deleteFilter' => [
                'class' => TreeDeleteFilter::className(),
                'only' => ['delete'],
                'errorInfo' => '该任务下存在子任务，无法删除',
            ],
            'taskAccess' => [
                'class' => TaskAccessControlFilter::className(),
                'only' => ['view', 'update', 'detail', 'status', 'delete'],
                'permissions' => ['', '', '', '', ''],
                'id' => ($request->isGet) ? $request->get('id') : $request->post('id'),
                'taskField' => 'task_id',
            ],
            'createFirstTask' => [
                'class' => CreateTaskFilter::className(),
                'only' => ['create'],
                'task' => Yii::$app->request->post('Task'),
                'enableFilter' => function($request) {
                return Yii::$app->request->isPost;
            },
            ],
        ];
    }

    /**
     * 任务首页
     */
    public function actionIndex()
    {
        $user_id = Yii::$app->user->identity->user_id;
        $limit = 6;

        //负责的任务
        $leadTasks = Task::getTask($user_id, 'lead', $limit);

        //参与的任务
        $joinTasks = Task::getTask($user_id, 'join', $limit);

        //关注的任务
        $followTasks = Task::getTask($user_id, 'follow', $limit);

        $taskStatus = TaskStatus::find()->where(['status' => 1, 'list_show' => 1])->orderBy(['sort' => SORT_DESC])->all();

        return $this->render('index',
                [
                'leadTasks' => $leadTasks,
                'joinTasks' => $joinTasks,
                'followTasks' => $followTasks,
                'taskStatus' => $taskStatus,
                'limit' => $limit,
        ]);
    }

    public function actionList()
    {
        return $this->render('list');
    }

    /**
     * 任务列表
     */
    public function actionListIframe()
    {
        if (!Yii::$app->session->get('isSuperAdmin') && !Yii::$app->user->can('task/task/list')) {
            throw new ForbiddenHttpException('权限不足！');
        }
        $tablePrefix = Yii::$app->db->tablePrefix;
        $query = Task::find()
            ->joinWith(['category', 'leader'])
            ->orderBy(['task_id' => SORT_DESC])
            ->indexBy('task_id')
            ->asArray();
        $request = Yii::$app->request;
        $type = $request->get('type');
        $user_id = Yii::$app->user->identity->user_id;
        $showFirst = (int) $request->get('show_first'); //是否只看一级
        //搜索
        $keywords = trim($request->get('keywords'));
        $categoryId = $request->get('category_id');
        $statusId = $request->get('status_id');
        $timeOrder = $request->get('time_order');
        $leaderIds = $request->get('leader');

        if (!empty($type)) {
            $scopeUser = [$user_id];
            if ($type == 'lead') {
                $query->where([$tablePrefix . 'task.leader_id' => $scopeUser]);
                $query->orWhere([$tablePrefix . 'task.leader_id' => 0, $tablePrefix . 'task.user_id' => $scopeUser]);
            } elseif ($type == 'join') {
                $findArr = [];
                foreach ($scopeUser as $u) {
                    $findArr[] = 'FIND_IN_SET(' . (int) $u . ', join_ids)';
                }
                $findStr = implode(' or ', $findArr);
                $query->where($findStr);
                $query->andWhere(['not in', 'leader_id', $scopeUser]);
            } elseif ($type == 'follow') {
                $findArr = [];
                foreach ($scopeUser as $u) {
                    $findArr[] = 'FIND_IN_SET(' . (int) $u . ', follow_ids)';
                }
                $findStr = implode(' or ', $findArr);
                $query->where($findStr);
            } else {
                $query->where([$tablePrefix . 'task.leader_id' => $scopeUser]);
                $query->orWhere([$tablePrefix . 'task.leader_id' => 0, $tablePrefix . 'task.user_id' => $scopeUser]);
            }
            //只取状态为显示的任务
            $showStatus = TaskStatus::getShowListStatus();
            $query->andWhere(['status_id' => $showStatus]);

            if (!empty($categoryId)) {
                $category = Category::findOne($categoryId);
                $query->andWhere(['category_id' => explode(',', $category['child_ids'])]);
            }
        } else {
            //权限范围过滤
            $scopeUser = PermissionScope::getScopeUser('task/task/list');
            $queryStr = Task::getRelatedTaskQueryStr($scopeUser, $tablePrefix . 'task.');
            //获取公共任务
            $publicCategorys = Category::getPublicCategory();
            if (!empty($categoryId)) {
                $category = Category::findOne($categoryId);

                if (in_array($categoryId, $publicCategorys)) {
                    $query->andWhere(['category_id' => explode(',', $category['child_ids'])]);
                } else {
                    $query->where($queryStr)->orderBy(['create_time' => SORT_DESC]);
                    $query->andWhere(['category_id' => explode(',', $category['child_ids'])]);
                }
            } else {
                if (!empty($queryStr)) {
                    $query->where($queryStr)->orderBy(['create_time' => SORT_DESC]);
                    if (!empty($publicCategorys)) {
                        $query->orWhere(['category_id' => Category::getPublicCategory()]);
                    }
                }
            }
        }

        if ($showFirst == 1) {
            $query->andWhere([$tablePrefix . 'task.parent_id' => 0]);
        }


        if (!empty($keywords)) {
            $field = $request->get('search_field');
            if (in_array($field, ['realname', 'username'])) {
                $query->joinWith([
                    'category',
                    'leader' => function ($query) use ($field, $keywords) {
                    $query->where(['like', $field, $keywords]);
                }
                ]);
            } else {
                $query->andWhere(['like', $tablePrefix . 'task.' . $field, trim($keywords)]);
            }
        }

        if (!empty($statusId)) {
            $query->andWhere(['status_id' => $statusId]);
        }

        //时间排序
        if (!empty($timeOrder)) {
            if ($timeOrder == 'today') {
                $startTime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $endTime = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                $query->andWhere(['between', 'end_time', $startTime, $endTime]);
            } elseif ($timeOrder == 'week') {
                $startTime = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
                $endTime = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y'));
                $query->andWhere(['between', 'end_time', $startTime, $endTime]);
            } elseif ($timeOrder == 'month') {
                $startTime = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $endTime = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                $query->andWhere(['between', 'end_time', $startTime, $endTime]);
            } elseif ($timeOrder == 'create') {
                $query->orderBy(['create_time' => SORT_DESC]);
            } elseif ($timeOrder == 'update') {
                $query->orderBy(['update_time' => SORT_DESC]);
            }
        }

        if (!empty($leaderIds)||$leaderIds=='0') {
            $query->andWhere(['leader_id' => explode(',', $leaderIds)]);
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 15,
            ],
        ]);

        $models = ($showFirst == 1) ? $provider->getModels() : Task::toSecondTree($provider->getModels());
        //\common\components\Tool::dump($models);
        $this->layout = '//modal';
        return $this->render('list-iframe',
                [
                'model' => new Task(),
                'models' => $models,
                'pages' => $provider->pagination,
                'get' => $request->get(),
                'typeTitle' => ['lead' => '我负责的', 'join' => '我参与的', 'follow' => '我关注的'],
        ]);
    }

    /**
     * 任务详情
     */
    public function actionDetail()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');

        $model = Task::find()
            ->where(['task_id' => $id])
            ->with(['category', 'user', 'leader', 'parentTask'])
            ->asArray()
            ->one();

        if (!$model) {
            return $this->flash('查看的任务不存在', 'error');
        }

        //获取关联数据
        if (!empty($model['link_id'])) {
            $model['link_data'] = Common::getLinkData($model['link_type'], $model['link_id']);
        }

        //获取顶级父级和父级的关联数据
        if ($model['parent_id'] != 0) {
            $model['topParent'] = Task::getTopParent($model);
            $model['topParent'] = (!empty($model['topParent'])) ? $model['topParent']->attributes : [];
            if (!empty($model['topParent']['link_id'])) {
                $model['topParent']['link_data'] = Common::getLinkData($model['topParent']['link_type'], $model['topParent']['link_id']);
            }
        } else {
            $model['topParent'] = $model;
        }

        //获取任务权限
        $taskPermissions = Task::getTaskPermission($model);
        //var_dump($taskPermissions);

        return $this->render('detail', [
                'model' => $model,
                'taskPermissions' => $taskPermissions,
        ]);
    }

    /**
     * 设置任务的状态
     */
    public function actionStatus()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $statusId = (int) $request->get('status_id');

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if (empty($id)) {
            $data = ['status' => 0, 'info' => '数据错误'];
            return $data;
        }

        //FIND_IN_SET(:user_id,user_ids)
        $task = Task::find()
            ->where(['task_id' => $id])
            ->one();

        $userId = Yii::$app->user->identity->user_id;

        if (!$task) {
            $data = ['status' => 0, 'info' => '任务数据错误'];
            return $data;
        }

        $status = TaskStatus::findOne($statusId);

        if (!$status) {
            $data = ['status' => 0, 'info' => '状态值不存在'];
            return $data;
        }


        $command = Yii::$app->db->createCommand();
        $result = $command->update('{{%task}}', ['status_id' => $status->status_id, 'status_name' => $status->name], 'task_id = :task_id', [':task_id' => $task->task_id])->execute();

        if (0 !== $result) {
            $data = ['status' => 1, 'info' => '设置成功', 'status_name' => $status->name];
        } else {
            $data = ['status' => 0, 'info' => '设置失败'];
        }

        return $data;
    }

    /**
     * ajax获取多级树数据
     */
    public function actionAjaxGetTreeData()
    {
        //$data = [['id' => 1, 'pId' => 0, 'name' => "父节点1", 'url' => 'http://www.baidu.com', 'target' => '_self']];
        $id = (int) Yii::$app->request->get('id');

        $data = Task::getTreeData($id);

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $data;
    }

    /**
     * ajax获取任务数据
     */
    public function actionAjaxGetTask()
    {
        $no = Yii::$app->request->get('no');

        $task = Task::find()
            ->where(['task_no' => $no])
            ->asArray()
            ->one();

        if ($task === null) {
            return ['status' => 0, 'info' => '任务不存在'];
        }

        if (!empty($task['link_id'])) {
            $task['link_data'] = Common::getLinkData($task['link_type'], $task['link_id']);
        }

        $data = ['status' => 1, 'data' => $task];

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $data;
    }

    public function actionGetTreedata()
    {
        $data = Task::obtainLeaderTree(); //部门与用户

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $data;
    }
}