<?php
namespace app\admin\controller;

use app\common\controller\AdminBaseController;
use app\common\model\NavModel;
use think\Db;
use think\facade\Cache;

/**
 * 前台导航
 */
class NavController extends AdminBaseController {

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        Cache::rm('frontend_navs');
    }

    protected function navlist(){
        $nav_list = NavModel::order('path asc')->all();

        foreach ($nav_list as $key=>$vo) {

            $level = str_word_count($vo['path'], 0, '-');

            $str = str_repeat('--', $level-1);

            $nav_list[$key]['str'] = $str;
        }

        return $nav_list;
	}

    public function index() {
        return $this->fetch();
    }

    public function getMenus() {
        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = $this->navlist();
        return $res;
    }

    public function changeShow()
    {
        return parent::switchOperate(new NavModel());
    }

    public function updateField() {
        return parent::fieldUpdate(new NavModel());
    }

    /**
     * 添加导航
     * @param string $pid
     * @return mixed
     */
    public function add($pid = '') {
        if ($this->request->isPost()) {
            $data = $this->request->param();

            $rule = NavModel::create($data);

            $id = $rule->id;

            if ($id) {
                $path = '0-'.$id;

                if ($data['pid']) {
                    $ppath = NavModel::where('id',$data['pid'])->value('path');
                    $path = $ppath.'-'.$id;
                }

                Db::name('nav')->where('id',$id)->setField('path',$path);

                $res['code'] = 1;
                $res['msg'] = '添加成功！';
                $res['url'] = url('index');
            } else {
                $res['code'] = 0;
                $res['msg'] = '添加失败！';
            }

            return $res;
        } else {
            $categorys = Db::name('category')->field('id,name,path')->where('status',1)->all();
            $pages = Db::name('page')->field('id,title')->all();

            return $this->fetch('add', ['pid' => $pid,'nav_list'=> $this->navlist(),'categorys'=>$categorys,'pages'=>$pages]);
        }
    }

    /**
     * 删除菜单
     * @param $id
     */
    public function delete($id) {
        if (NavModel::destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}
