<?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\Blog;
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 yii\helpers\ArrayHelper;
use common\models\User;
use home\models\Attachment;

/**
 * 日志控制器
 *
 * @author HuLimin http://blog.u-bo.com
 * @since 0.1
 */
class BlogController extends Controller
{

    /**
     * 首页
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        $scopeUser = PermissionScope::getScopeUser('blog/blog/index');

        if ($request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $linkId = $request->get('link_id');
            $linkType = $request->get('link_type');
            $userId = $request->get('user_id');
            $startTime = $request->get('startTime');
            $endTime = $request->get('endTime');
            $date = $request->get('date');
            if (!empty($date)) {
                $startTime = $endTime = $date;
            }
            $startTime = $startTime ? strtotime($startTime . ' 00:00:00') : 0;
            $endTime = $endTime ? strtotime($endTime . ' 23:59:59') : 0;
            
            $query = Blog::find()
                ->with('user')
                ->orderBy(['work_time' => SORT_DESC, 'update_time' => SORT_DESC])
                ->asArray();

            if (!empty($scopeUser)) {
                $userId = in_array($userId, $scopeUser) ? $userId : Yii::$app->user->id;
            }
            else {
                $userId = !empty($userId) ? $userId : Yii::$app->user->id;
            }

            $query->where(['user_id' => $userId]);

            //如果指定了关联信息，则只调取关联信息的
            if (!empty($linkId) && !empty($linkType)) {
                $query->andWhere(['link_id' => $linkId, 'link_type' => $linkType]);
            }

            if (!empty($startTime) && !empty($endTime)) {
                $query->andWhere(['between', 'work_time', $startTime, $endTime]);
            }

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

            $models = $provider->getModels();
            $html = $this->getListHtml($models);

            $data = [
                'status' => 1,
                'content' => $html,
                'totalPage' => $provider->pagination->pageCount,
            ];
            return $data;
        } else {
            $users = User::find()
                ->select('user_id,realname');

            if (!empty($scopeUser)) {
                $users = $users->where(['user_id' => $scopeUser]);
            }
            $users = $users->all();

            $firstDayOfWeek = date("Y-m-d", mktime(0, 0 , 0, date("m"), date("d") - date("N") + 1, date("Y")));
            $lastDayOfWeek = date("Y-m-d", mktime(23, 59, 59, date("m"), date("d") - date("N") + 7, date("Y")));

            return $this->render('index', [
                'firstDayOfWeek' => $firstDayOfWeek,
                'lastDayOfWeek' => $lastDayOfWeek,
                'userId' => Yii::$app->user->id,
                'users' => $users,
            ]);
        }
    }

    /**
     * 获取html内容
     *
     * @param $models 日志数据
     */
    private function getListHtml($models)
    {
        $userId = Yii::$app->user->id;
        $html = '';
        foreach ($models as &$model) {
            $linkInfo = [];
            $linkName = '';
            $linkTypeName = '';
            $model['title'] = StringHelper::truncate($model['title'], 14);
            $model['work_time'] = date('m/d', $model['work_time']);
            $model['user']['realname'] = StringHelper::truncate($model['user']['realname'], 4, '');
            $url = Url::to(['detail', 'id' => $model['blog_id']]);
            $linkInfo = Common::getLinkData($model['link_type'], $model['link_id']);
            $linkName = ArrayHelper::getValue($linkInfo, 'name');
            $linkTypeName = ArrayHelper::getValue($linkInfo['link_type'], 'name');
            $fileIcon='';
            if(!empty($model['attach_ids'])){
                $fileIcon='icon-paper-clip';
            }
            $html .= <<<TPL
                <li>
                    <a href="{$url}">
                        <p class="{$fileIcon}">&nbsp;{$model['title']}</p>
                        <p class="c6">【{$linkTypeName}】{$linkName}</p>
                        <span><i class="icon-user">{$model['user']['realname']}</i> <em><br>{$model['work_time']} {$model['workload']}H</em></span>
                        <i class="icon-angle-right"></i>
                    </a>
                </li>
TPL;
        }
        return $html;
    }

    /**
     * 新增或更新日志
     */
    public function actionCreate()
    {
        $this->model = new Blog();
        $this->model->scenario = 'insert';
        $request = Yii::$app->request;
        $userId = Yii::$app->user->id;

        if ($request->isPost) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $post = Yii::$app->request->post('Blog');

            //如果是已写过日志则更新
            $blog = (!empty($post['blog_id'])) ? Blog::find()->where(['blog_id' => $post['blog_id'], 'user_id' => $userId])->one() : Blog::getLinkDayBlog($post['work_time'], $post['link_type'],
                $post['link_id']);
            if ($blog) {
                $this->model = $blog;
                $this->model->scenario = 'update';
            }

            $this->model->load(Yii::$app->request->post());
            if ($this->model->save()) {
                $data = ['status' => 1, 'info' => ($blog ? '保存' : '新增') . '日志成功', 'url' => Url::to(['index'])];
            } elseif ($this->model->hasErrors()) {
                $firstError = reset($this->model->getFirstErrors());
                $data = ['status' => 0, 'info' => $firstError];
            }
            return $data;
        }

        $linkId = $request->get('link_id');
        $linkType = $request->get('link_type');
        $linkData = Common::getLinkData($linkType, $linkId);

        if (empty($linkData)) {
            throw new NotFoundHttpException('关联信息不存在');
        }
        $work_time = $request->get('work_time');
        $work_time = (empty($work_time)) ? date('Y-m-d') : $work_time;
        if ($blog = Blog::getLinkDayBlog($work_time, $linkType, $linkId)) {
            $this->model = $blog;
        }
        //获取附件
        $attachs = Attachment::find()
            ->select('attach_id, file_name')
            ->where(['attach_id' => explode(',', $this->model['attach_ids'])])
            ->all();


        return $this->render('create', [
            'model' => $this->model,
            'linkData' => $linkData,
            'linkId' => $linkId,
            'linkType' => $linkType,
            'attachs' => $attachs,
        ]);
    }

    /**
     * 检查当前日期有没有写过日志
     */
    public function actionBlogCheck()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $userId = Yii::$app->user->id;
        $linkType = $request->get('link_type');
        $linkId = $request->get('link_id');
        $workTime = $request->get('work_time');

        $blog = blog:: getLinkDayBlog($workTime, $linkType, $linkId);

        if ($blog) {
            //获取附件html
            $attachHtml = '';
            if (!empty($blog['attach_ids'])) {
                $attachs = Attachment::find()
                    ->select('attach_id, file_name')
                    ->where(['attach_id' => explode(',', $blog['attach_ids'])])
                    ->all();
                foreach ($attachs as $attach) {
                    $attachHtml .= ' <tr class="file-tr" data-attach-id="' . $attach['attach_id'] . '"> <td></td> <td  class="icon-download-alt"><a href="' . Url::to('@web/index.php?r=attachment/download&id=' . $attach['attach_id']) . '">' .  StringHelper::truncate($attach['file_name'],15) . '</a><buttton type="button" class="btn btn-default btn-filedelete delete-file icon-trash"></button></td> </tr>';
                }
            }
            $data = ['haveWrite' => 1, 'blog' => ['blog_id' => $blog['blog_id'], 'title' => $blog['title'], 'workload' => $blog['workload'], 'attach_ids' => $blog['attach_ids'], 'attach_html' => $attachHtml, 'content' => $blog['content']]];

        } else {
            $data = ['haveWrite' => 0];
        }
        return $data;
    }

    /**
     * 详情
     */
    public function actionDetail()
    {
        $model = new Blog();
        $request = Yii::$app->request;
        $id = (int) $request->getQueryParam('id');

        if (empty($id) || !$model = call_user_func([$model, 'findOne'], $id)) {
            throw new NotFoundHttpException('要查看的日志不存在');
        }

        if ($model->user_id == Yii::$app->user->id) {
            return $this->redirect(['create', 'link_id' => $model['link_id'], 'link_type' => $model['link_type'], 'work_time' => date('Y-m-d', $model['work_time'])]);
        }

        //权限范围过滤
        $scopeUser = PermissionScope::getScopeUser('blog/blog/detail');

        if (!empty($scopeUser)) {
            if (!in_array($model->user_id, $scopeUser)) {
                throw new ForbiddenHttpException('没有权限查看此日志');
            }
        }

        if ($request->isPost) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $remark = $request->post('remark');
//            $model->scenario='detail';//$scenario['detail'] = ['remark', 'read_time', 'read_user_id'];
            $model->remark = $remark;
            $model->scenario='detail';
            if (false !== $model->save()) {
                $data = ['status' => 1, 'info' => '批示成功'];
            } else {
                $data = ['status' => 0, 'info' => '批示失败，请稍后再试'];
            }
            return $data;
        }

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

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