<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "group_t".
 *
 * @property integer $id
 * @property string $name
 * @property integer $parent_id
 * @property number $base_pay
 * @property number $job_pay
 * @property number $station_pay
 * @property string $created_at
 * @property string $updated_at
 */
class GroupT extends \common\models\Base
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'group_t';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['parent_id'], 'integer'],
            [['base_pay','job_pay','station_pay'], 'number'],
            [['created_at', 'updated_at'], 'safe'],
            [['name'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'base_pay' => 'Base Pay',
            'job_pay' => 'Job Pay',
            'station_pay' => 'Station Pay',
            'parent_id' => 'Parent ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

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

    static public function getTree($parent_id=0,$level=0)
    {
        $items = GroupT::find()
            ->where('parent_id='.$parent_id)
            ->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,GroupT::getTree($item->id,$level+1));
            $data = $tmp_data;
        }
        return $data;
    }

    public function hasChild($id)
    {
        $items = GroupT::getTree($this->id);
        foreach($items as $item) {
            if($item->id == $id)
                return true;
        }
        return false;
    }

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

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

    public function getPath()
    {
        $path = '';
        if($this->parent_id > 0) {
            $info = $this->parent;
            $path .= $info->getPath();
        }
        return $path.'/'.$this->name;
    }
}
