<?php

namespace backend\modules\goods\models\ars;

use Yii;
use yii\behaviors\TimestampBehavior;
use backend\modules\goods\models\ars\Category;

/**
 * This is the model class for table "atg_attribute".
 *
 * @property int $id
 * @property string $name 属性名
 * @property string $value 属性值
 * @property int $type 类型
 * @property int $sort_order 排序
 * @property int $is_delete 是否删除,1为已删除
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $cat_id 后台商品分类id
 */
class Attribute extends \yii\db\ActiveRecord
{
    //是否删除is_delete
    const IS_DELETE_NO = 0;//未删除
    const IS_DELETE_YES = 1;//已删除
    //类型type
    const TYPE_ATTR = 1;//商品sku属性
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'atg_attribute';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name', 'value'], 'required'],
            [['value'], 'string'],
            [['type', 'sort_order', 'is_delete', 'cat_id'], 'integer'],
            [['name'], 'string', 'max' => 50],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'id',
            'name' => '规格名称',
            'value' => '规格内容(每项以逗号隔开)',
            'type' => '类型',
            'sort_order' => '排序',
            'is_delete' => '是否删除,1为已删除',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'cat_id' => '后台商品分类',
        ];
    }
   

    /**
    * @author linyao
    * @email 602604991@qq.com
    * @created Nov 8, 2019
    *
    * 行为存储创建时间和更新时间
    */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => function() {
                    return time();
                },
            ],
        ];
    }

    /**
     * @return array
     * 数据键值对
     */
    public static function modelColumn()
    {
        return $column = self::find()->select(['name'])->where(['is_delete' => self::IS_DELETE_NO])->indexBy('id')->column();
    }

    public function beforeSave($insert)
    {
        if(!$this->type){
            $this->type = self::TYPE_ATTR;
        }
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'cat_id']);
    }
}