<?php

namespace common\models\article;

use common\behaviors\DynamicFormBehavior;
use common\behaviors\XsBehavior;
use common\models\Article;
use yii\helpers\HtmlPurifier;
use yii\helpers\StringHelper;

/**
 * This is the model class for table "{{%article_data}}".
 *
 * @property int $id
 * @property string $intro
 * @property integer $markdown
 */
class University extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%article_university}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['intro'], 'required'],
            [['id', 'markdown'], 'integer'],
            ['markdown', 'default', 'value' => $this->getIsMarkdown()],
            [['intro'], 'string'],
        ];
    }

    /**
     * 没有指定markdown情况下默认编辑器是否为markdown
     * @return int
     */
    public function getIsMarkdown()
    {
        return \Yii::$app->config->get('article_editor_type') == 'markdown' ? 1 : 0;
    }

    public function getProcessedIntro()
    {
        return $this->markdown ? \yii\helpers\Markdown::process($this->intro) : $this->intro;
    }
    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'intro' => '研究方向',
            'markdown' => '是否markdown格式'
        ];
    }

    public function attributeHints()
    {
        return [
            'intro' => '摘要不填时默认截取内容前150个字符'
        ];
    }
    public function behaviors()
    {
        $behaviors = [];
        if (\Yii::$app->config->get('SEARCH_ENGINE') == 'xunsearch') {
            $behaviors[] = XsBehavior::className();
        }
        $behaviors[] = [
            'class' => DynamicFormBehavior::className(),
            'formAttributes' => [
                'intro' => [
                    'type' => 'textarea',
//                    'options' => function ($model) {
//                        return ['widgetOptions' => $model->isNewRecord ? ['type' => config('article_editor_type')] : ['isMarkdown' => $model->markdown]];
//                    }
                ],
            ]
        ];
        return $behaviors;
    }

    // 发布新文章后（摘要为空的话根据内容生成摘要)

    public function afterSave($insert, $changedAttributes)
    {
        $article = Article::findOne(['id' => $this->id]);
        if (!empty($article)) {
            if (empty($article->description)) {
                $article->description = $this->generateDesc($this->getProcessedIntro());
                $article->save();
            }
        }
    }

    // 摘要生成方式
    private function generateDesc($intro)
    {

        if (empty($intro)) {
            return '';
        }
        return StringHelper::truncate(preg_replace('/\s+/', ' ', strip_tags($intro)), 150);
    }
}
