<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "menu_t".
 *
 * @property integer $id
 * @property string $name
 * @property string icon
 * @property string $path
 * @property integer $parent_id
 * @property integer $order_id
 * @property string $created_at
 * @property string $updated_at
 */
class MenuT extends \common\models\Base
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'menu_t';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['parent_id','order_id'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['name','icon'], 'string', 'max' => 50],
            [['path'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'icon' => 'Icon',
            'path' => 'Path',
            'parent_id' => 'Parent ID',
            'order_id' => 'Order ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function getMenus()
    {
        return $this->hasMany(MenuT::className(),['parent_id'=>'id']);
    }

    public function getParent()
    {
        return $this->hasOne(MenuT::className(),['id'=>'parent_id']);
    }

    public function getGroups()
    {
        return $this->hasMany(GroupT::className(),['id'=>'group_id'])
            ->viaTable('group_menu_t',['menu_id'=>'id']);
    }

    static public function getTree($parent_id=0,$level=0)
    {
        $items = MenuT::find()
            ->where('parent_id='.$parent_id)
            ->orderBy('order_id ASC')
            ->all();
        $data = array();
        foreach($items as $item) {
            $tmp_str = '';
            if($level > 1)
                $tmp_str .= str_repeat('　　',$level-1);
            if($level > 0)
                $tmp_str .= str_repeat('　　',1);
            $tmp_str .= $item->name;
            $item->name = $tmp_str;
            $data[] = $item;
            $tmp_data = array_merge($data,MenuT::getTree($item->id,$level+1));
            $data = $tmp_data;
        }
        return $data;
    }
}
