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

namespace home\models;

use Yii;
use qcbase\models\Auth;
use yii\base\ErrorException;

/**
 * This is the model class for table "qc_announcement".
 * 
 * 系统通知模型
 *
 * @property integer $announcement_id  (ID)
 * @property string $title  (标题)
 * @property string $content  (通知内容)
 * @property integer $create_time  (发送时间)
 * @property integer $read_time  (阅读时间)
 * @property smallint $is_read  (0未读   1已读)
 * @property integer $user_id  (接收人ID)
 * @property smallint $status  (状态 1正常  99逻辑删除（屏蔽）)
 * @property smallint $type  (通知类型 默认1  1任务 2回款 3报销  ...)
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class Announcement extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%announcement}}';
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        $scenario = parent::scenarios();
        $scenario['insert'] = ['title', 'content', 'user_id', 'type', 'create_time'];
        $scenario['update'] = ['announcement_id, is_read', 'read_time'];
        return $scenario;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['content', 'title', 'create_time', 'user_id'], 'required'],
            [['create_time', 'read_time', 'is_read', 'user_id', 'status', 'type'], 'integer'],
            [['title'], 'string', 'max' => 100],
            [['content'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'announcement_id' => 'ID',
            'title' => '标题',
            'content' => '内容',
            'create_time' => '发送时间',
            'read_time' => '阅读时间',
            'is_read' => '是否已读',
            'user_id' => '收信人ID',
            'status' => '状态',
            'type' => '类型',
        ];
    }

    /**
     * 搜索所需信息
     */
    public function search()
    {
        return [
            'keywords' => [
                'title' => '标题',
            ],
        ];
    }

    /**
     * 向用户发送系统通知
     * string   $title       发送的标题
     * string   $content     发送的内容
     * array    $recipients  收件人数组
     * int      $type        (通知类型 默认1  1任务 2回款 3报销  ...)
     * string   $scenario    验证规则
     *
     * @return bool
     */
    public static function Send ($title, $content, $recipients, $type = 1, $scenario = 'insert')
    {
        $model = new Announcement;
        if (empty($title) || empty($content) || empty($recipients)) {
            throw new ErrorException('标题/内容/收件人/不能为空!');
        }
        $recipients = is_array($recipients)?$recipients:[$recipients];
        foreach ($recipients as $user_id) {
            $model = new Announcement();
            $model->title = $title;
            $model->content = $content;
            $model->user_id = $user_id;
            $model->type = $type;
            $model->scenario = $scenario;
            $model->create_time = time();
            $model->read_time = 0;
            $model->is_read = 0;
            $model->status = 1;
            if ($model->validate() && $model->save()) {
                continue;
            } else {
                throw new ErrorException($model->getErrors());
            }
        }
        return true;
    }

    /**
     * 查找自己的系统信息
     */
    public static function gainAnnouncement ($user_id, $limit = 5, $order = ['is_read' => SORT_ASC, 'announcement_id' => SORT_DESC])
    {
        $announcement = static::find()
            ->select('announcement_id, title, create_time')
            ->where(['status' => 1, 'user_id' => $user_id])
            ->orderBy($order)
            ->asArray()
            ->limit($limit)
            ->all();
        return $announcement;
    }

    /**
     * 查找自己的系统信息
     *
     * int      $user_id   发件人ID
     * int      $type      通知类型 通知类型 默认1  1任务 2回款 3报销
     * array    $order     排序规则
     *
     * @return bool
     */
    public static function equal($user_id, $type, $order = ['create_time' =>SORT_DESC])
    {
        $time = static::find()
            ->select('create_time')
            ->where(['status' => 1, 'user_id' => $user_id, 'type' => $type])
            ->orderBy($order)
            ->one();
        $timeDate = !empty($time->create_time)?date('Y-m-d',$time->create_time):date('Y-m-d');
        $actualDate = date('Y-m-d');
        return ($timeDate == $actualDate)?true:false;
    }

    /**
     * 权限审核
     * @param  string  $url     操作URL
     * @param  integer $user_id 用户ID
     */
    public static function readAccess($url = null, $user_id = 0)
    {
        if (empty($url)) {
            return false;
        }
        empty($user_id) ? $user_id = \Yii::$app->user->id : $user_id;
        //非超级管理员，需要检测权限
        if (Yii::$app->session->get('isSuperAdmin')) {
            return true;
        }
        //检测是否具有某一特定权限
        if (Auth::checkAccess($url, $user_id)) {
            return true;
        }
        return false;
    }
}