<?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\Message;

/**
 * This is the model class for table "qc_message_link".
 * 
 * 短消息和通知公告关联模型
 *
 * @property integer $link_id  (ID)
 * @property integer $message_id  (通知公告ID，关联表qc_messages)
 * @property integer $from_user_id  (发送人ID)
 * @property integer $to_user_id  (接收人ID)
 * @property integer $read_time  (阅读时间)
 * @property smallint $is_read  (是否阅读   0没有  1已阅读)
 * @property smallint $status  (状态  0默认   99逻辑删除)
 * @property smallint $type  (默认1：短消息    2：通知公告)
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class MessageLink extends \yii\db\ActiveRecord
{

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['message_id', 'from_user_id', 'to_user_id', 'read_time', 'is_read', 'status', 'type'],'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'link_id'      => 'ID',
            'message_id'   => '信息ID',
            'from_user_id' => '发送者ID',
            'to_user_id'   => '接收人ID',
            'read_time'    => '阅读时间',
            'is_read'      => '是否阅读',
            'status'       => '状态',
            'type'         => '类型',
        ];
    }

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

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

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

    /**
     * 关联qc_message表获取用户的信息
     */
    public function getMessage()
    {
        return $this->hasOne(Message::className(), ['message_id' => 'message_id'])->select('message_id, title, type, is_reply, create_time');
    }

    /**
     * 获取 未查看和总数 的对比
     * @param type $message_id  对哪条信息通知进行统计,id值
     * @return string  返回一个对比的数值
     */
    public static function getContrast($message_id)
    {
        $countAll = static::find()
                        ->where(['message_id' => $message_id])
                        ->count();
        $countNotRead = static::find()
                            ->where(['message_id' => $message_id, 'is_read' => 1])
                            ->count();
        return $countNotRead."/".$countAll;
    }

    /**
     * 查看短消息或通知的时候更新阅读时间和状态
     *
     * @param int $link_id  信息的ID值
     * @return bool
     */
    public static function UpdateRead($link_id)
    {
        $MessageLink = static::findOne($link_id);
        if (empty($MessageLink->is_read)) {
            $MessageLink->read_time = time();
            $MessageLink->is_read = 1;
            if ($MessageLink->save()) {
                return true;
            } else {
                throw new ErrorException($MessageLink->getErrors());
            }
        }
    }

    /**
     * 查找自己收到的系统信息
     *
     * @param int $user_id  接收信息的用户ID
     * @param int $limit    一次查询几条
     * @param int $order    排序规则
     * @return  array
     */
    public static function gainMessage($user_id, $limit = 5, $order = ['is_read' => SORT_ASC, 'link_id' => SORT_DESC])
    {
        $message = static::find()
                        ->select('link_id, message_id')
                        ->where(['status' => 0, 'to_user_id' => $user_id])
                        ->orderBy($order)
                        ->with('message')
                        ->asArray()
                        ->limit($limit)
                        ->all();
        return $message;
    }

    /**
     * 查看当前这条发送给那些人
     *
     * @param int $message_id  d当前息ID
     * @return array
     */
    public static function findReceivers($message_id)
    {
        $recipients = static::find()
                        ->select('to_user_id')
                        ->where(['message_id' => $message_id])
                        ->with('toName')
                        ->asArray()
                        ->all();
        $showReceiver = '';
        if (count($recipients) == 1 ) {
            $showReceiver .= $recipients[0]['toName']['realname'];
        } else {
            foreach ($recipients as $v) {
                $showReceiver .= $v['toName']['realname'].'，';
            }
        }
        return $showReceiver;
    }

}