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

namespace home\models;

use Yii;
use common\models\User;
use home\models\MessageLink;
use yii\base\ErrorException;
use qcbase\models\Auth;

/**
 * This is the model class for table "qc_message".
 *
 * 短消息和通知公告模型
 *
 * @property integer $message_id  (ID)
 * @property string $title  (发送内容的标题)
 * @property text $content  (内容)
 * @property integer $create_time  (发送的时间)
 * @property smallint $status  (当前状态1正常     99逻辑删除)
 * @property integer $user_id  (发送人ID，关联表qc_user)
 * @property string $ip  (发送人IP)
 * @property smallint $type  (默认1：短消息    2：通知公告)
 * @property smallint $is_reply  (1需要回复   0不需要)
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class Message extends \yii\db\ActiveRecord
{
    const STATUS_ENABLE = 1;
    const STATUS_DISABLE = 0;

    public $get_user_names;  //收件人                string
    public $get_user_ids;    //收件人ID              string
    public $replycontent;    //发送的内容             text
    public $send_sers;       //当前信息收件人列表      string

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%message}}';
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        $scenario = parent::scenarios();
        $scenario['insert'] = ['title', 'content', 'status', 'get_user_ids', 'user_id', 'type', 'create_time', 'ip', 'get_user_names' ];
        $scenario['reply']  = ['title', 'content', 'status', 'get_user_ids', 'message_id'];
        $scenario['save']   = ['status', 'message_id'];
        return $scenario;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'get_user_names', 'get_user_ids'], 'required'],
            [['content', 'send_sers', 'replycontent'], 'string'],
            [['create_time', 'status', 'user_id', 'type', 'is_reply'], 'integer'],
            [['title'], 'string', 'max' => 100],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'message_id' => 'ID',
            'title' => '标题',
            'content' => '内容',
            'create_time' => '发送时间',
            'status' => '状态',
            'user_id' => '发送人ID',
            'ip' => '发送人ip',
            'type' => '发送的类型',
            'is_reply' => '回复',
            'send_sers' => '收件人列表',
            'get_user_names' => '收件人',
            'get_user_ids' => '收件人',
        ];
    }

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

    /**
     * 返回状态列表
     */
    public static function getStatusList()
    {
        return [
            self::STATUS_ENABLE => '需要',
            self::STATUS_DISABLE => '不需要',
        ];
    }

    /**
     * 关联qc_user表获取用户的信息
     */
    public function getUserName()
    {
        return $this->hasOne(User::className(), ['user_id' => 'user_id'])->select('user_id, realname');
    }

    /**
     * 关联qc_message_link获取信息通知发送给哪些人员的一对多关联
     */
    public function getMessageLinks()
    {
        return $this->hasMany(MessageLink::className(), ['message_id' => 'message_id']);
    }

    /**
     * 向指定的 个人/部门/用户组 发送 短信息/通知公告
     * string   $title        发送的标题
     * string   $content      发送的内容
     * array    $recipients   指定人员,最小单位人
     * int      $is_reply     默认1需要回复   0不需要回复
     * int      $type         (当前信息通知的类型) 1:短消息  2：通知公告
     *
     * @return bool
     */
    public static function Send($title, $content, $recipients, $scenario, $is_reply = 1, $type = 1)
    {
        $model = new Message();
        if (!empty($recipients)) {
            $model->get_user_names = true;
            $model->get_user_ids = true;
        } else {
            throw new ErrorException('收件人不能为空!');
        }

        $model->title = $title;
        $model->content = $content;
        $model->scenario = $scenario;
        $model->is_reply = $is_reply;
        $model->type = $type;
        $model->create_time = time();
        $model->user_id = Yii::$app->user->identity->user_id;
        $model->ip = Yii::$app->getRequest()->getUserIP();

        if ($model->validate() && $model->save()) {
            $message_id = $model->attributes['message_id'];
            $recipients = is_array($recipients)?$recipients:[$recipients];
            static::insertConsignee($recipients, $message_id, $type);
            return true;
        } else {
            throw new ErrorException($model->getErrors());
        }
    }

    /**
     * 循环向数据库插入指定收件人的信息
     * array  $recipients    指定接收信息通知的人员
     * int    $message_id    收件人所属的信息通知ID
     * int    $type 消息类型  1短消息  2通知公告
     *
     * @return bool
     */
    public function insertConsignee($recipients, $message_id, $type)
    {
        $userId = Yii::$app->user->identity->user_id;
        foreach ($recipients as $to_user_id) {
            $model = new MessageLink();
            $model->isNewRecord = true;
            $model->to_user_id = $to_user_id;
            $model->message_id = $message_id;
            $model->from_user_id = $userId;
            $model->type = $type;
            if ($model->validate() && $model->save()) {
                continue;
            } else {
                throw new ErrorException($model->getErrors());
            }
        }
        return true;
    }

        /**
     * 把字符串转换成数组,并剔除相同的元素
     *
     * @return Array
     */
    public function getArray($string)
    {
        $arr = explode(',', $string);
        $resultArr = array_unique($arr);
        return $resultArr;
    }

    /**
     * 权限审核
     * @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;
    }

}