<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\common\model;

use think\Model;

class Messages extends Model
{
    const STATUS_WAIT = 0;
    const STATUS_PASS = 1;
    const STATUS_UNPASS = -1;

    const STATUS = [
        self::STATUS_WAIT => '待审核',
        self::STATUS_PASS => '已审核',
        self::STATUS_UNPASS => '已拒审'
    ];

    //status_text
    public function getStatusTextAttr($value, $data)
    {
        return self::STATUS[$data['status']]??'';
    }

    //message
    public function getMessageAttr($value, $data)
    {
        return htmlspecialchars($value);
    }

    /**
     * 截取N个字
     * @return mixed|string
     */
    public function getShortText($len = 50)
    {
        if (mb_strlen($this->message, "utf-8") > $len) {
            return subStrCN($this->message, $len) . "...";
        }
        return $this->message;
    }

    /**
     * 获取本消息的回复个数
     */
    public function replyCount()
    {
        return $this->hasMany('Messages', 'to_msg_id')->where('status', self::STATUS_PASS)->count();
    }

    /**
     * 获取管理员后台的回复
     */
    public function adminReplays()
    {
        return $this->hasMany('Messages', 'to_msg_id')->where(['status' => self::STATUS_PASS, 'from_user_id' => 0]);
    }

    public function fromUser()
    {
        return $this->belongsTo('app\common\model\User', 'from_user_id');
    }

    public function toUser()
    {
        return $this->belongsTo('app\common\model\User', 'to_user_id');
    }
}
