<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Form;
use common\helpers\snowflake\PageSnowFake;
use common\models\Countries;
use common\models\FreeTemplate;
use Yii;
use yii\base\Exception;

class FreeTemplateForm extends Model
{
    public $modelClass = FreeTemplate::class;

    public $countryId;
    public $freight;
    public $freeShipping;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['countryId', 'freight', 'freeShipping'], 'required'],
            [['countryId'], 'isCountry'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'country_id' => 'Country',
            'freight' => 'Freight',
            'free_shipping' => 'FreeShipping',
        ];
    }

    /**
     * 指定场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'setTransportation' => ['countryId', 'freight', 'freeShipping'],
        ];

        return array_merge($parentScenarios, $customScenarios);
    }

    public function isCountry($attribute){
        $country = Countries::getById($this->countryId);
        if (!$country) {
            $this->addError($attribute, Yii::t('ctx', 'countryDoesNotExist'));
        }
    }

    /**
     * 设置运费模板.
     * @return true
     */
    public function setTransportation(): ?bool
    {
        if (!$this->validate()) {
            return null;
        }

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 删除旧数据
            $this->modelClass::deleteOne($this->countryId);
            // 添加/修改数据
            $model = new FreeTemplate();
            $model->ID = PageSnowFake::instance()->generateId();
            $model->country_id = $this->countryId;
            $model->freight = $this->freight;
            $model->free_shipping = $this->freeShipping;
            if (!$model->save()) {
                $transaction->rollBack();
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('setTransportation', $e->getMessage());
            return null;
        }

        return true;
    }
}
