<?php
/**
 * @desc: 栏目模型
 * @Author: Dr.Xing <ezfwork@foxmail.com>
 * @Since: 2018/2/1 15:04
 */

namespace app\common\model;

use think\Model;

class Channel extends Model
{
    protected $name = 'channel';

    protected function base(&$query){
        if(\think\Session::has("user_site_id")) {
            $query->where(['status' => 'normal', 'site_id' =>\think\Session::get("user_site_id")]);
        }else{
            $query->where(['status'=>'normal', 'site_id'=>0]);
        }
        $query->order('weigh DESC, id DESC');
    }

    /**
     * 生成菜单
     * @param string $active 激活项
     * @return array
     */
    public static function getNav($active='index')
    {
        $list = self::all();
        $result = [];
        foreach ($list as $key => &$v)
        {
        	if($v['pid']==0 ) {
                $sub = [];
                foreach($list as $sk => $sv){
                    if($sv['pid'] == $v['id']) {
                        $sub[] = [
                        	'text' => $sv['name'],
                        	'url' =>  $sv['type']=='redirect' ? $sv['redirect'] :
                                        ($sv['diyname']!=''? 
		                                   url('index/channel/index', ['name'=>$sv['diyname']]) :
		                                   url('index/channel/index', ['id'=>$sv['id']])
                                        ),
                            'active' => false,
                            'child' => 0,
                        ];
                    }
                }

                $result[] = [
                    'text' => $v['name'],
                    'url' =>  $v['type']=='redirect' ? $v['redirect'] :
                                ($v['diyname']!=''? 
                                   url('index/channel/index', ['name'=>$v['diyname']]) :
                                   url('index/channel/index', ['id'=>$v['id']])
                                ) ,
                    'active' => false,
                	'child' => count($sub),
                	'sub' => $sub
                ];
            }
        }

        return $result;
    }

}