<?php
namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\models\Article;
use common\models\ArticleCategory;
use yii\base\Exception;

/**
 * Login form
 */
class ArticleForm extends Model
{
    public $id;
    public $title;
    public $cid;
    public $sort;
    public $content;
    public $countryId;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'title', 'cid', 'content'], 'trim'],
            [['id', 'title', 'cid', 'content', 'countryId'], 'required'],
            [['countryId'], 'string'],
            [['id'], 'exist', 'targetClass'=>Article::class, 'targetAttribute'=>'ID'],
            [['cid'], 'exist', 'targetClass'=>ArticleCategory::class, 'targetAttribute'=>'ID'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',//标题
            'cid' => 'Type', // 分类
            'content' => 'Content', // 内容
            'sort' => 'Sort', // 排序
            'countryId' => 'Country', // 国家
        ];
    }

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

    /**
     * 申请
     * @return Article|null
     * @throws \yii\db\Exception
     */
    public function edit()
    {
        if(!$this->validate()){
            return null;
        }

        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            if($this->scenario == 'add'){
                $model = new Article();
                $model->CREATED_AT = Date::nowTime();
            } elseif($this->scenario == 'edit') {
                $model = Article::findOne(['ID'=>$this->id]);
            }  elseif($this->scenario == 'sort') {
                $model = Article::findOne(['ID'=>$this->id]);
            } else {
                $this->addError('edit', \Yii::t('ctx', 'sceneDoesNotExist'));// 提交场景不存在
                return null;
            }
            $model->TITLE = $this->title;
            $model->CID = $this->cid;
            $model->CONTENT = '';
            $model->STATUS = 1;
            $model->SORT = $this->sort;
            $model->COUNTRY_ID = $this->countryId;
            if(!$model->save()){
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }

            // 暂时把内容写入到文件中
            $path = \Yii::getAlias('@common/runtime/articleContent/').$model->ID;
            file_put_contents($path, $this->content);
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 排序
     * @return Article
     */
    public function sortTo(): ?Article
    {
        if (!$this->validate()) {
            return null;
        }

        $model = Article::findOne(['ID' => $this->id]);
        $model->SORT = $this->sort;
        if (!$model->save()) {
            $this->addError('sortTo', Form::formatErrorsForApi($model->getErrors()));
            return null;
        }
        return $model;
    }
}
