<?php
namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\models\MessageText;
use common\models\UserInfo;
use yii\base\Exception;

/**
 * Login form
 */
class MessageForm extends Model
{
    public $id;
    public $title;
    public $content;
    public $toUserName;

    private $_userId;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'title', 'content', 'toUserName'], 'trim'],
            [['id', 'title', 'content'], 'required'],
            [['id'], 'exist', 'targetClass'=>MessageText::class, 'targetAttribute'=>'ID'],
            [['toUserName'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_NAME'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'content' => '内容',
            'toUserName' => '发给会员编号',
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'add' => ['title', 'content', 'toUserName'],
            'delete' => ['id'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 添加
     * @return MessageText|null
     * @throws \yii\db\Exception
     */
    public function edit(){
        if(!$this->validate()){
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            if($this->toUserName){
                $toUser = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME'=>$this->toUserName], 'USER_ID');
                $this->_userId = $toUser['USER_ID'];
            } else {
                $this->_userId = null;
            }
            $model = new MessageText();
            $model->TITLE = $this->title;
            $model->CONTENT = $this->content;
            $model->TO_UID = $this->_userId ?? '0';
            $model->ADMIN_ID = \Yii::$app->user->id;
            $model->CREATED_AT = Date::nowTime();
            if(!$model->save()){
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            // 给前台会员发送webSocket消息，通知其抓取消息
            if($this->send() === false){
                throw new Exception('发送失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 给前台会员发送websocket消息，通知其抓取站内信
     */
    public function send(){
        if(!$this->_userId){
            $this->_userId = null;
        }
        return \Yii::$app->swooleAsyncTimer->pushMsgToUser($this->_userId, '有新的消息');
    }

}
