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

namespace wap\controllers;

use Yii;
use wap\controllers\Controller;
use wap\models\Task;
use yii\db\Query;
use common\models\Common;
use yii\web\NotFoundHttpException;
use yii\data\ActiveDataProvider;
use yii\helpers\StringHelper;
use yii\helpers\Url;
use common\models\PermissionScope;
use home\modules\task\models\Category;
use home\modules\blog\models\Blog;
use home\models\Attachment;

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

    /**
     * 首页
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        if ($request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $keywords = $request->get('keywords');

            $query = Task::getMyTaskQuery();
            if (!empty($keywords)) {
                $query->andWhere(['like', 'name', trim($keywords)]);
            }
            $provider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => [
                    'pageSize' => 10,
                ],
            ]);
            $models = $provider->getModels();

            $html = $this->getTaskListHtml($models);

            $data = [
                'status' => 1,
                'content' => $html,
                'totalPage' => $provider->pagination->pageCount,
            ];

            return $data;
        } else {
            return $this->render('index', [
            ]);
        }
    }

    /**
     * 我的任务
     */
    public function actionMyTask()
    {
        $request = Yii::$app->request;
        if ($request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $tablePrefix = Yii::$app->db->tablePrefix;
            $userId = Yii::$app->user->id;
            $keywords = $request->get('keywords');

            $query = Task::find()
                ->joinWith(['category', 'leader'])
                ->orderBy(['task_id' => SORT_DESC])
                ->indexBy('task_id')
                ->asArray();

            $scopeUser = PermissionScope::getScopeUser('task/task/list');
            $queryStr = Task::getRelatedTaskQueryStr($scopeUser, $tablePrefix . 'task.', ['lead', 'join']);
            //获取公共任务
            $publicCategorys = Category::getPublicCategory();

            if (!empty($queryStr)) {
                $query->where($queryStr)->orderBy(['create_time' => SORT_DESC]);
                if (!empty($publicCategorys)) {
                    $query->orWhere(['category_id' => Category::getPublicCategory()]);
                }
            }
            if (!empty($keywords)) {
                $query->andWhere(['like', $tablePrefix . 'task.name', trim($keywords)]);
            }
            //echo $query->createCommand()->sql;

            $provider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => [
                    'pageSize' => 10,
                ],
            ]);
            $models = $provider->getModels();
            $html = $this->getTaskListHtml($models);

            $data = [
                'status' => 1,
                'content' => $html,
                'totalPage' => $provider->pagination->pageCount,
            ];

            return $data;
        } else {
            return $this->render('my-task', [
            ]);
        }
    }

    /**
     * 获取任务html内容
     *
     * @param $models 任务数据
     */
    private function getTaskListHtml($models)
    {
        $userId = Yii::$app->user->id;
        $html = '';
        foreach ($models as &$model) {
            $model['name'] = StringHelper::truncate($model['name'], 14);
            $model['create_time'] = date('Y-m-d', $model['create_time']);
            $model['leader_name'] = isset($model['leader']) ? '负责人 : ' . $model['leader']['realname'] : '';
            $url = Url::to(['detail', 'id' => $model['task_id']]);
            $class = ($model['leader_id'] == $userId || ($model['leader_id'] == 0 && $model['user_id'] == $userId)) ? 'class="task-respons"' : '';
            $html .= <<<TPL
                    <li {$class}>
                    <a href="{$url}">
                        <h4>{$model['name']}</h4>
                        <p>{$model['create_time']}<span class="project-leader">{$model['leader_name']}</span></p>
                        <i class="icon-angle-right"></i>
                    </a>
                    </li>
TPL;
        }
        return $html;
    }

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

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

        if (!$model) {
            throw new NotFoundHttpException('查看的任务不存在');
        }

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

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

    /**
     * 日志
     */
    public function actionBlog()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $linkId = $request->get('link_id');
        $linkType = $request->get('link_type');
        $userId = $request->get('user_id');
        $category = $request->get('category');
        $scopeUser = '';

        $linkData = Common::getLinkData($linkType, $linkId);
        if (empty($linkData)) {
            return ['status' => 0, 'info' => '关联信息不存在'];
        }

        $childIds = explode(',', $linkData['child_ids']);

        $scopeUser = PermissionScope::getScopeUser('task/task/view-blog');

        $linkIds = (new Query)
            ->from(Task::tableName())
            ->select('task_no')
            ->where(['task_id' => $childIds])
            ->column();

        $query = Blog::find()
            ->with('user')
            ->where(['link_type' => $linkType, 'link_id' => $linkIds])
            ->asArray();
        if ($category == 'user') {
            $query->orderBy(['user_id' => SORT_ASC, 'work_time' => SORT_DESC, 'create_time' => SORT_DESC]);
        } else {
            $query->orderBy(['work_time' => SORT_DESC, 'create_time' => SORT_DESC]);
        }

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

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);
        $models = $provider->getModels();
        $html = $this->getTaskBlogHtml($models);

        $data = [
            'status' => 1,
            'content' => $html,
            'totalPage' => $provider->pagination->pageCount,
        ];

        return $data;
    }

    /**
     * 获取任务html内容
     *
     * @param $models 任务数据
     */
    private function getTaskBlogHtml($models)
    {
        $html = '';
        foreach ($models as &$model) {
            $model['content'] = (!empty($model['content'])) ? $model['content'] : $model['title'];
            $model['work_time'] = date('m/d', $model['work_time']);
            $model['remark'] = (!empty($model['remark'])) ? '[批示]：' . $model['remark'] : '[批示]：';
            $model['user']['realname'] = StringHelper::truncate($model['user']['realname'], 4, '');
            //获取附件html
            $attachHtml = '';
            if (!empty($model['attach_ids'])) {
                $attachHtml = '<p class="c6">[附件]：';
                $attachs = Attachment::find()
                    ->select('attach_id, file_name')
                    ->where(['attach_id' => explode(',', $model['attach_ids'])])
                    ->all();
                foreach ($attachs as $attach) {
                    $attachHtml .= '<a class="icon-download-alt" href="' . Url::to('@web/index.php?r=attachment/download&id=' . $attach['attach_id']) . '">' . StringHelper::truncate($attach['file_name'], 15) . '</a>&nbsp;&nbsp;';
                }
                $attachHtml .= '</p>';
            }

            $html .= <<<TPL
                <li>
                <div class="blog-content">{$model['content']}</div>
                {$attachHtml}
                <p class="c6">{$model['remark']}</p>
                <span><i class="icon-user"> {$model['user']['realname']}</i><em><br>{$model['work_time']}<br>{$model['workload']}H</em></span>
                </li>
TPL;
        }
        return $html;
    }
}