<?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\Announcement;
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 wap\assets\AppAsset;

/**
 * 通知控制器
 *
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class AnnouncementController 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 = Announcement::find()
                ->where(['user_id' => $userId, 'status' => 1])
                ->orderBy(['create_time' => SORT_DESC]);

            if (!empty($keywords)) {
                $query->andWhere(['like', 'title', trim($keywords)]);
            }

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

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

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

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

    /**
     * 获取通知html
     */
    private function getAnnounceHtml($models)
    {
        $userId = Yii::$app->user->id;
        $asset = Yii::$app->getAssetManager()->getBundle(AppAsset::className());
        $html = '';
        foreach ($models as &$model) {
            $model['title'] = StringHelper::truncate($model['title'], 14);
            $model['create_time'] = date('Y-m-d', $model['create_time']);
            $url = Url::to(['detail', 'id' => $model['announcement_id']]);
            $color = ($model['is_read'] == Announcement::NOT_READ) ? 'red' : 'gray';
            if ($model['type'] == Announcement::TASK_TYPE) {
                $type = '【任务】';
            } elseif ($model['type'] == Announcement:: RECEIVABLE_TYPE) {
                $type = '【回款】';
            } elseif ($model['type'] == Announcement::REIMBURSE_TYPE) {
                $type = '【报销】';
            }
            $html .= <<<TPL
                    <li>
                    <a href="{$url}">
                        <img src="{$asset->baseUrl}/images/message-{$color}.gif" width="6" height="6">
                        <h4>{$type}{$model['title']}</h4>
                        <p>{$model['create_time']}</p>
                    </a>
                    </li>
TPL;
        }
        return $html;
    }

    /**
     * 详情
     */
    public function actionDetail()
    {
        $request = Yii::$app->request;
        $userId = Yii::$app->user->id;
        $id = (int) $request->get('id');
        $model = Announcement::find()
            ->where(['announcement_id' => $id, 'user_id' => $userId, 'status' => 1])
            ->one();

        if (!$model) {
            throw new NotFoundHttpException('查看的消息不存在');
        }
        //设置已读状态
        if ($model['is_read'] == Announcement::NOT_READ) {
            $model->is_read = Announcement::HAVE_READ;
            $model->save();
        }
        //移除链接和点击查看
        $model->content = preg_replace('/<a.*?>(.*?)<\/a>/i', '$1', $model->content);
        $model->content = str_replace('点击查看', '', $model->content);
        return $this->render('detail', [
                'model' => $model,
        ]);
    }
}
