<?php
namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\Validator;
use common\libs\logging\operate\AdminOperate;
use common\models\Ad;
use common\models\AdLocation;
use common\models\Article;
use yii\base\Exception;
use yii\validators\UrlValidator;

/**
 * Login form
 */
class AdForm extends Model
{
    public $id;
    public $title;
    public $image;
    public $type;
    public $lid;
    public $content;
    public $sort;
    public $status;
    public $countryId;

    private $_adModel;

    public function init() {
        parent::init();
        $this->adminOperateLogger = new AdminOperate([
            'fetchClass' => Ad::class,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'title', 'image', 'type', 'lid', 'content', 'sort', 'status', 'countryId'], 'trim'],
            [['id', 'title', 'image', 'type', 'lid', 'content', 'sort', 'status', 'countryId'], 'required'],
//            [['image'], 'url'],
            [['id'], 'exist', 'targetClass'=>Ad::class, 'targetAttribute'=>'ID'],
            [['id'], 'initModel'],
            [['lid'], 'exist', 'targetClass'=>AdLocation::class, 'targetAttribute'=>'ID'],
            [['type'], 'isType'],
            [['content'], 'isContent'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',// 标题
            'image' => 'Image', // 图片
            'type' => 'Type', // 类型
            'lid' => 'Ad', // 广告位
            'content' => 'External link or article ID', // 链接地址或文章ID
            'sort' => 'Order', // 排序
            'status' => 'State', // 状态
            'countryId' => 'Country', // 国家
        ];
    }

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

    /**
     * 初始化广告model类
     * @param $attribute
     */
    public function initModel($attribute){
        $this->_adModel = Ad::findOne(['ID'=>$this->id]);
    }

    /**
     * 校验类型
     * @param $attribute
     */
    public function isType($attribute){
        if(!in_array($this->type, [Ad::TYPE_LINK, Ad::TYPE_ARTICLE])){
            $this->addError($attribute, \Yii::t('ctx', 'typeError')); // 类型错误
        }
    }

    /**
     * 校验内容
     * @param $attribute
     */
    public function isContent($attribute){
        if($this->content == ""){
            $this->addError($attribute, \Yii::t('ctx', 'contentError')); // 内容错误
        }
    }

    /**
     * 添加编辑广告
     * @return Ad|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 Ad();
                $model->CREATE_ADMIN = \Yii::$app->user->id;
                $model->CREATED_AT = Date::nowTime();
            } elseif($this->scenario == 'edit') {
                $this->adminOperateLogger->beforeUpdate($this->_adModel);
                $model = $this->_adModel;
                $model->UPDATE_ADMIN = \Yii::$app->user->id;
                $model->UPDATED_AT = Date::nowTime();
            } else {
                $this->addError('edit', \Yii::t('ctx', 'submissionDoesNotExist'));
                return null;
            }
            $model->TITLE = $this->title;
            $model->IMAGE = $this->image;
            $model->TYPE = $this->type;
            $model->LID = $this->lid;
            $model->CONTENT = $this->content;
            $model->COUNTRY_ID = $this->countryId;
            $model->STATUS = 1;
            if(!$model->save()){
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        if($this->scenario == 'add'){
            $this->adminOperateLogger->afterInsert($model)->clean()->save([
                'optType' => 'Add',
            ]);
        }else{
            $this->adminOperateLogger->afterUpdate($model)->clean()->save([
                'optType' => 'Edit',
            ]);
        }
        return $model;
    }

    /**
     * 排序
     * @return null
     */
    public function sortTo(){
        if(!$this->validate()){
            return null;
        }
        $this->adminOperateLogger->beforeUpdate($this->_adModel);
        $model = $this->_adModel;
        $model->SORT = $this->sort;
        if(!$model->save()){
            $this->addError('sortTo', Form::formatErrorsForApi($model->getErrors()));
            return null;
        }
        $this->adminOperateLogger->afterUpdate($model)->clean()->save([
            'optType' => 'Ad Order', // 广告排序
        ]);
        return $model;
    }

    /**
     * 改变状态
     * @return null
     */
    public function statusTo(){
        if(!$this->validate()){
            return null;
        }
        $model = $this->_adModel;
        $model->STATUS = $this->status;
        if(!$model->save()){
            $this->addError('statusTo', Form::formatErrorsForApi($model->getErrors()));
            return null;
        }
        return $model;
    }

    /**
     * 删除前
     * @param $selected
     */
    public function beforeDelete($selected) {
        $this->adminOperateLogger->fetchClass = Ad::class;
        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
    }
    /**
     * 删除
     * @param $selected
     * @throws Exception
     */
    public function delete($selected) {
        $this->adminOperateLogger->clean()->save([
            'optType' => 'Delete Ad', // 删除广告
        ]);
    }
}
