<?php

namespace common\models;

use common\helpers\Date;
use Yii;
use yii\base\Exception;

/**
 * This is the model class for table "{{%MESSAGE}}".
 *
 * @property string $ID
 * @property string $USER_ID 会员ID
 * @property string $TEXT_ID 站内信内容ID
 * @property int $IS_READ 是否已读
 * @property int $IS_DEL 是否删除
 * @property int $CREATED_AT 创建时间
 * @property int $READ_AT 已读时间
 * @property int $DELETED_AT 删除时间
 */
class Message extends \common\components\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%MESSAGE}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['USER_ID', 'TEXT_ID', 'CREATED_AT'], 'required'],
            [['IS_READ', 'IS_DEL', 'CREATED_AT', 'READ_AT', 'DELETED_AT'], 'integer'],
            [['ID', 'USER_ID', 'TEXT_ID'], 'string', 'max' => 32],
            [['ID'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'USER_ID' => '会员ID',
            'TEXT_ID' => '站内信内容ID',
            'IS_READ' => '是否已读',
            'IS_DEL' => '是否删除',
            'CREATED_AT' => '创建时间',
            'READ_AT' => '已读时间',
            'DELETED_AT' => '删除时间',
        ];
    }

    /**
     * 获取未读数量
     * @param $userId
     * @return int|string
     */
    public static function unreadNum($userId){
        return static::findUseSlaves()->where('USER_ID=:USER_ID AND IS_READ=0 AND IS_DEL=0', [':USER_ID'=>$userId])->asArray()->count();
    }

    /**
     * 抓取消息
     * @param $userId
     * @return bool
     * @throws \yii\db\Exception
     */
    public static function pullMsgByUser($userId){
        // 获取会员最后一次抓取信息的时间
        $userInfo = UserInfo::findUseSlaves()->select('PULLED_AT')->where('USER_ID=:USER_ID', [':USER_ID'=>$userId])->asArray()->one();
        if(!$userInfo){
            return false;
        }
        $allMessageText = MessageText::findUseSlaves()->select('ID')->where('CREATED_AT>=:LAST_PULL_TIME AND IS_DEL=0', [':LAST_PULL_TIME'=>$userInfo['PULLED_AT']])->asArray()->all();

        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $insertData = [];
            foreach($allMessageText as $messageText){
                $insertData[] = [
                    'USER_ID' => $userId,
                    'TEXT_ID' => $messageText['ID'],
                    'CREATED_AT' => Date::nowTime(),
                ];
            }
            Message::batchInsert($insertData);
            // 更新最后抓取时间
            $oneUserAr = UserInfo::findOne(['USER_ID'=>$userId]);
            $oneUserAr->PULLED_AT = Date::nowTime();
            if(!$oneUserAr->save()){
                throw new Exception('更新抓取消息时间失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return false;
        }

        return true;
    }
}
