<?php 
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/15/015
 * Time: 19:18
 */

namespace backend\modules\ib\controllers;

use Yii;
use backend\models\NoticeApi;
use backend\models\searches\NoticeSearch;

class NoticeController extends BaseController
{
    /**
     * 公告首页
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * ajax获取公告列表
     * @return \yii\web\Response
     */
    public function actionNoticeAjax()
    {
        $searchModel = new NoticeSearch();
        $request = \Yii::$app->getRequest()->getQueryParams();
        $request['type'] = 1;
        $dataProvider = $searchModel->search($request);
        return $this->asJson($searchModel->outResult($dataProvider));
    }

    /**
     * 获取未读公告数
     */
    public function actionFindNotReadCount()
    {
        $params = [];
        $params['member_id'] = $this->getMemberId();

        $noticeApi = new NoticeApi();
        $rs = $noticeApi->findNotReadCount($params['member_id'], 1);
        return $this->asJson((int)$rs['data']['unReadNum']);
    }

    /**
     * 获取公告详细信息
     */
    public function actionNview()
    {
        $request = \Yii::$app->getRequest()->getQueryParams();
        $params = [];
        $params['id'] = isset($request['id']) ? (int)$request['id'] : '';
        $params['member_id'] = $this->getMemberId();
        $params['is_admin'] = 0;

        $noticeApi = new NoticeApi();
        $rs = $noticeApi->view($params);
        return $this->render('view', ['data' => $rs['data']]);
    }

    /**
     * 最新的公告
     */
    public function actionLastUnreadNotice()
    {
        $params['member_id'] = $this->getMemberId();
        $params['type'] = 1;
        
        $noticeApi = new NoticeApi();
        $rs = $noticeApi->lastUnreadNotice($params);
        
        $cachePrefix = 'last_unread_notice-';
        
        $noticeId = Yii::$app->cache->get($cachePrefix . $params['member_id']);
        if ($noticeId && isset($rs['data']['notice']['id']) && $noticeId == $rs['data']['notice']['id']) {
            return $this->asJson(['code' => 0]);    
        }
        
        if (isset($rs['data']['notice']['id'])) {
            Yii::$app->cache->set($cachePrefix . $params['member_id'], $rs['data']['notice']['id'], 86400 * 30);
        }
        
        return $this->asJson($rs);
    }
}
