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

namespace home\controllers;

use Yii;
use home\models\Announcement;
use home\models\MessageLink;
use yii\data\ActiveDataProvider;

/**
 * 系统通知控制器
 * 
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class AnnouncementController extends Controller
{
    public function actions()
    {
		return [];
	}

    /**
     * 当前用户的系统消息
     */
    public function actionIndex()
    {
        $model = new Announcement;
		$query = Announcement::find();
        $query->orderBy(['is_read' => SORT_ASC, 'announcement_id' => SORT_DESC]);
        $query->where(['user_id' => Yii::$app->user->identity->user_id, 'status' => 1]);
        $query->andwhere(['not in', 'type', [1, 2]]);

		$request = Yii::$app->request;
		$keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $beginTime = $request->get('begin_time');
		$endTime = $request->get('end_time');

        
        if(!empty($beginTime)) {
			$beginTime = strtotime($beginTime);
			$query->andWhere('create_time >= :beginTime', [':beginTime' => $beginTime]);
		}
		if(!empty($endTime)) {
			$endTime = strtotime($endTime) + 86399;
			$query->andWhere('create_time <= :endTime', [':endTime' => $endTime]);
		}
		if (!empty($keywords) && !empty($field)) {
			$query->andwhere(['like', $field, $keywords]);
		}
        
		$provider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' => 15,
			],
		]);
        return $this->render('index', [
			'get' => $request->get(),
			'model' => $model,
			'models' => $provider->models,
			'pages' => $provider->pagination,
            'action' => '/announcement/index',
            'title'  => '通知列表'
		]);
    }

    /**
     * 当前用户的任务系统消息
     */
    public function actionIndexTask()
    {
        $model = new Announcement;
        $query = Announcement::find();
        $query->orderBy(['is_read' => SORT_ASC, 'announcement_id' => SORT_DESC]);
        $query->where(['user_id' => Yii::$app->user->identity->user_id, 'status' => 1, 'type' => 1]);

        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $beginTime = $request->get('begin_time');
        $endTime = $request->get('end_time');

        if(!empty($beginTime)) {
            $beginTime = strtotime($beginTime);
            $query->andWhere('create_time >= :beginTime', [':beginTime' => $beginTime]);
        }
        if(!empty($endTime)) {
            $endTime = strtotime($endTime) + 86399;
            $query->andWhere('create_time <= :endTime', [':endTime' => $endTime]);
        }
        if (!empty($keywords) && !empty($field)) {
            $query->andwhere(['like', $field, $keywords]);
        }

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

        return $this->render('index', [
            'get' => $request->get(),
            'model' => $model,
            'models' => $provider->models,
            'pages' => $provider->pagination,
            'action' => '/announcement/index-task',
            'title'  => '任务通知列表'
        ]);
    }

    /**
     * 当前用户的回款系统消息
     */
    public function actionIndexReceivable()
    {
        $model = new Announcement;
        $query = Announcement::find();
        $query->orderBy(['is_read' => SORT_ASC, 'announcement_id' => SORT_DESC]);
        $query->where(['user_id' => Yii::$app->user->identity->user_id, 'status' => 1, 'type' => 2]);

        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $beginTime = $request->get('begin_time');
        $endTime = $request->get('end_time');

        if(!empty($beginTime)) {
            $beginTime = strtotime($beginTime);
            $query->andWhere('create_time >= :beginTime', [':beginTime' => $beginTime]);
        }
        if(!empty($endTime)) {
            $endTime = strtotime($endTime) + 86399;
            $query->andWhere('create_time <= :endTime', [':endTime' => $endTime]);
        }
        if (!empty($keywords) && !empty($field)) {
            $query->andwhere(['like', $field, $keywords]);
        }

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

        return $this->render('index', [
            'get' => $request->get(),
            'model' => $model,
            'models' => $provider->models,
            'pages' => $provider->pagination,
            'action' => '/announcement/index-receivable',
            'title'  => '回款通知列表'
        ]);
    }

    /**
     * 通知详情
     */
    public function actionDetail()
    {
        $this->layout = 'modal';

        $id = (int) Yii::$app->request->get('id');
        $model = Announcement::find()
            ->where(['announcement_id' => $id, 'user_id' => Yii::$app->user->id])
            ->one();
        if ($model === null) {
            return $this->flash('查看的通知不存在' ,'error');
        }
        //设置已读状态
        if ($model['is_read'] == 0) {
            $model->is_read = 1;
            $model->save();
        }
        $model['content'] = preg_replace('/<(a.*?)>/', '<$1 target="_blank">', $model['content']);

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

    /**
     * 查看通知时，修改系统通知的状态
     */
    public function actionSetRead()
    {
        $data = [];
        $model = new Announcement;

        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        if (empty($id)) {
            $data = ['status' => '0' ,'info' => '通知ID错误'];
        }

        $model = Announcement::find()
                        ->select('announcement_id')
                        ->where(['status' => 1, 'announcement_id' => $id, 'user_id' => Yii::$app->user->identity->user_id])
                        ->one();
        if (empty($model)) {
            $data = ['status' => '0' , 'info' => '系统通知不存在'];
        }

        $model->scenario = 'update';
        $model->is_read = 1;
        $model->read_time = time();
        if ($model->validate() && $model->save()) {
            $data = ['status' => '1'];
        } else {
            $data = ['status' => '0' ,'info' => $model->getErrors()];
        }
        
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $data;
    }

    /**
     *每隔一段时间查询下自己的未读的任务，回款，系统信息，消息的数目
     * @return type
     */
    public function actionAjax()
    {
        $statistics = [];
        $userId = Yii::$app->user->identity->user_id;
        $anWhere = ['status' => 1, 'user_id' =>$userId, 'is_read' => 0, 'type' =>1];
        $announce = Announcement::find();

        //未读的任务数
        $statistics['taskAmount'] = $announce->where($anWhere)->count();

        //未读的回款数
        $anWhere['type'] = 2;
        $statistics['receivableAmount'] = $announce->where($anWhere)->count();

        //不包含任务和回款的其他未读的系统通知数
        unset($anWhere['type']);
        $statistics['otherAmount'] = $announce
                    ->where($anWhere)
                    ->andWhere(['not in', 'type', [1, 2]])
                    ->count();

        //未读的收件箱的数
        $msgWhere = ['status' => 0, 'to_user_id' => $userId, 'is_read' => 0];
        $statistics['messageAmount'] = MessageLink::find()
                    ->where($msgWhere)
                    ->count();

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

}
