<?php namespace Manage\Lib;
use Dever;
use Dever\Project;
class Menu
{
    # 初始化菜单
    public function init()
    {
        $app = Project::read();
        foreach ($app as $k => $v) {
            $base = $v['path'] . 'table/manage/core.php';
            if (is_file($base)) {
                $core = include $base;
                if ($core) {
                    $this->add($k, $core);
                }
            }
        }
        return 'ok';
    }
    private function add($app, $core)
    {
        if (isset($core['system'])) {
            foreach ($core['system'] as $k => $v) {
                $where = array();
                $where['key'] = $k;
                $data = $where;
                $data['name'] = $v['name'];
                $data['sort'] = $v['sort'];
                $data['partition'] = $v['partition'] ?? 'database';
                $data['relation_table'] = $v['relation_table'];
                $data['relation_field'] = $v['relation_field'];
                $data['relation_user_table'] = $v['relation_user_table'];
                Dever::db('system')->up($where, $data);
            }
        }
        if (isset($core['menu'])) {
            foreach ($core['menu'] as $k => $v) {
                $where = array();
                if (isset($v['app'])) {
                    $app = $v['app'];
                }
                $where['app'] = $app;
                $where['key'] = $k;
                if (isset($v['parent'])) {
                    $parent = Dever::db('menu')->find(array('key' => $v['parent']));
                    if ($parent) {
                        $where['parent_id'] = $parent['id'];
                        $where['system_id'] = $parent['system_id'];
                    }
                }
                if (isset($v['system'])) {
                    $system = Dever::db('system')->find(array('key' => $v['system']));
                    if ($system) {
                        $where['system_id'] = $system['id'];
                    }
                }
                $data = $where;
                $data['name'] = $v['name'];
                $data['icon'] = $v['icon'];
                $data['sort'] = $v['sort'];
                if (isset($v['show'])) {
                    $data['show'] = $v['show'];
                }
                if (isset($v['badge'])) {
                    $data['badge'] = $v['badge'];
                }
                if (isset($v['path'])) {
                    $data['path'] = $v['path'];
                } else {
                    $data['path'] = 'main';
                }
                if (isset($v['link'])) {
                    $data['link'] = $v['link'];
                }
                Dever::db('menu')->up($where, $data);
            }
        }
    }
    public function getAll()
    {
        $data = Dever::db('menu')->select(array('parent_id' => '0'));
        return $data;
    }
}