<?php
namespace Manage\Src;

use Dever;

class Menu
{
    /**
     * fast
     *
     * @var array
     */
    private $fast = array();

    /**
     * data
     *
     * @var array
     */
    private $data = array();

    /**
     * __construct
     *
     * @return mixed
     */
    public function __construct()
    {

    }

    public function test_api()
    {
        $data = Dever::db('manage/menu-in', array('where_id' => '2,1'));
        print_r(Dever::sql());die;
    }

    public function checkKey($id = 0)
    {
        $id = Dever::input('where_id');
        $key = Dever::input('update_key');

        if ($key && !$id) {
            $info = Dever::db('manage/menu')->key(array('where_key' => $key));
            if ($info) {
                Dever::alert('该菜单唯一key已被使用，请换一个吧');
            }
        } elseif ($id > 0) {
            $info = Dever::db('manage/menu')->keyId(array('where_key' => $key, 'where_id' => $id));
            if ($info) {
                Dever::alert('该菜单唯一key已被使用，请换一个吧');
            }
        }
    }

    /**
     * menu 从数据库中得到所有菜单，如果为空，则从项目中读取一次
     *
     * @return array
     */
    private function get($auth = '', $state = 2)
    {
        $ms = Dever::input('ms');

        $param = array();

        if ($ms) {
            $param['option_key'] = $ms;
        }
        $menu = Dever::db('manage/menu')->main($param);

        if ($menu) {
            $this->fast = array();
            $child = Dever::db('manage/menu')->child();

            if ($auth && is_array($auth)) {
                $auth = implode(',', $auth);
            }
            
            foreach ($menu as $k => $v) {
                if ($auth && strpos($auth, $k . '.') === false) {
                    unset($menu[$k]);
                    continue;
                }

                $path = Dever::load('manage/project.path', $v['key']);
                if (strpos($path, 'http://') === 0) {
                    unset($menu[$k]);
                    continue;
                }

                if (isset($child[$v['id']])) {
                    foreach ($child[$v['id']] as $i => $j) {
                        if ($auth && strpos($auth, $i) === false) {
                            //unset($child[$parent][$i]);
                            //continue;
                        } else {
                            if ($j['link']) {
                                $j['link'] = Dever::url($j['link'] . '&menu_id=' . $j['id']);
                            }
                            $menu[$k]['child'][$i] = $j;

                            if ($j['fast'] == 1) {
                                $this->fast[$i] = $j;
                            }
                        }
                    }

                    if (!isset($menu[$k]['child'])) {
                        unset($menu[$k]);
                    }
                }
            }
        } elseif (!$ms && $state == 2) {
            # 数据为空，读取一次，后续就得手动读取了
            $this->load();

            $menu = $this->get($auth, 1);
        }

        return $menu;
    }

    /**
     * 清空所有菜单
     *
     * @return array
     */
    public function delete()
    {
        $data = $menu = Dever::db('manage/menu')->all;
        foreach ($data as $k => $v) {

        }
        Dever::out('yes');
    }

    /**
     * 更新菜单
     *
     * @return array
     */
    public function update_api()
    {
        $this->load();

        Dever::out('yes');
    }

    /**
     * 载入从项目中定义好的菜单
     *
     * @return array
     */
    public function load()
    {
        $project = Dever::load('manage/project.get');
        $database = Dever::load('manage/database');
        $top = Dever::load('manage/top');
        $auth = Dever::load('manage/auth');

        foreach ($project as $k => $v) {
            if (isset($v['base']) && isset($v['rel'])) {
                $v['path'] = DEVER_INCLUDE_PATH . $v['rel'];
            }

            $project[$k]['name'] = $v['lang'];
            $config = $database->config($k, $v['path']);

            if ($config) {
                foreach ($config as $i => $j) {
                    $this->sync('top', 'update', $j, $k, $i, $v, $top);
                    $this->sync('auth', 'update_action', $j, $k, $i, $v, $auth);

                    if (!isset($j['menu'])) {
                        $j['menu'] = true;
                    }
                    if (isset($j['manage']) && $j['menu'] != false) {
                        if (is_string($j['menu'])) {
                            $m = $j['menu'];
                        } else {
                            $m = $k;
                        }

                        if ($m == $k) {
                            $key = $k . '.' . $i;
                        } else {
                            $key = $m . '.' . $k . '.' . $i;
                        }
                        $project[$m]['child'][$i]['key'] = $key;
                        $project[$m]['child'][$i]['name'] = $j['lang'];
                        $project[$m]['child'][$i]['link'] = 'project/database/list?project=' . $k . '&table=' . $i . '&menu=' . $m . '&search_option_state=1';
                        $project[$m]['child'][$i]['order'] = isset($j['order']) ? $j['order'] : 1;
                        $project[$m]['child'][$i]['fast'] = isset($j['fast']) ? $j['fast'] : 2;
                    }
                }
            } else {
                unset($project[$k]);
            }
        }

        //print_r($project);die;

        # 将所有数据都记录到菜单中
        if ($project) {
            foreach ($project as $k => $v) {
                if (!isset($v['child'])) {
                    unset($project[$k]);
                    continue;
                }

                if ($v && isset($v['lang']) && $v['child']) {
                    $id = $this->updateMenu($k, $v['lang'], $v['path'] . ':' . $v['name'], -1, $v['order'], 2, (isset($v['icon']) ? $v['icon'] : ''));
                    if ($id > 0) {
                        foreach ($v['child'] as $i => $j) {
                            $this->updateMenu($j['key'], $j['name'], $j['link'], $id, $j['order'], $j['fast']);
                        }
                    }
                }
            }
        }

        return $project;
    }

    private function sync($key, $update, $data, $k, $i, $project, $model)
    {
        if (isset($data[$key]) && is_array($data[$key])) {
            # 加入头部左侧控制权限的菜单
            if ($key == 'top') {
                $data[$key]['name'] = $project['lang'] . '-' . $data[$key]['name'];
            }

            if (isset($data[$key]['type']) && $data[$key]['type'] == 2) {
                $id = false;
            } else {
                $id = $model->{$update}($data[$key]);
            }

            if (strpos($data[$key]['data'], '/')) {
                $parent = Dever::load($data[$key]['data']);
            } else {
                $parent = Dever::load($k . '/' . $i . '-' . $data[$key]['data']);
            }

            //print_r($data[$key]);die;

            if ($parent) {
                if (!$id) {
                    foreach ($parent as $k => $v) {
                        if (isset($v['child']) && $v['child']) {
                            $param = array();
                            $param['project'] = $project['name'];
                            $param['project_name'] = $project['lang'];
                            $param['key'] = $data[$key]['key'] . '_' . $v['id'];
                            $param['name'] = $v[$data[$key]['col']];
                            $param[$key] = -1;
                            $param['value'] = $v['id'];
                            $pid = $model->{$update}($param);

                            foreach ($v['child'] as $k1 => $v1) {
                                $param = array();
                                $param['project'] = $project['name'];
                                $param['project_name'] = $project['lang'];
                                $param['key'] = $data[$key]['key'] . '_' . $v1['id'];
                                $param['name'] = $v1[$data[$key]['col']];
                                $param[$key] = $pid;
                                $param['value'] = $v1['id'];
                                $model->{$update}($param);
                            }
                        }
                    }
                } elseif ($id) {
                    foreach ($parent as $v) {
                        $param = array();
                        if ($key == 'auth') {
                            $param['project'] = $project['name'];
                            $param['project_name'] = $project['lang'];
                        }

                        $param['key'] = $data[$key]['key'] . '_' . $v['id'];
                        $param['name'] = $v[$data[$key]['col']];
                        $param[$key] = $id;
                        $param['value'] = $v['id'];
                        $model->{$update}($param);
                    }
                }
            }
        }
    }

    /**
     * 更新菜单到数据库
     *
     * @return array
     */
    public function updateMenu($key, $name, $link, $menu, $order, $fast, $icon = '')
    {
        if (!$key) {
            return;
        }
        $info = Dever::db('manage/menu')->key(array('where_key' => $key));
        if (!$info) {
            $update['add_key'] = $key;
            $update['add_name'] = $name;
            $update['add_link'] = $link;
            $update['add_menu_id'] = $menu;
            $update['add_reorder'] = $order;
            $update['add_fast'] = $fast;
            $update['add_state'] = 1;
            $update['add_type'] = 2;
            if ($icon) {
                $update['add_icon'] = $icon;
            }
            $info['id'] = Dever::db('manage/menu')->insert($update);
        }
        /*
        elseif($link != $info['link'])
        {
        $update['set_link'] = $link;
        $id = $update['where_id'] = $info['id'];
        Dever::load('manage/menu-update', $update);
        }
         */

        return $info['id'];
    }

    /**
     * menu 生成左侧的菜单 此处应加上权限来显示是否管理员有该菜单的权限
     *
     * @return array
     */
    public function left($state = false)
    {
        if ($this->data) {
            return $this->data;
        }

        $auth = '';
        if ($state == false) {
            # 需要验证权限
            $auth = Dever::load('manage/auth.admin');
        }
        //$auth = 'manage_admin';
        $menu = $this->get($auth);

        $this->data = $menu;

        return $menu;

        /*
    //$auth = 'manage_admin,image_thumb';

    foreach($project as $k => $v)
    {
    if($auth && strpos($auth, $k . '_') === false)
    {
    unset($project[$k]);
    continue;
    }

    if($auth && strpos($auth, $k . '_' . $i) === false)
    {
    //unset($project[$k]['child'][$i]);
    continue;
    }

    if(!isset($v['child']))
    {
    unset($project[$k]);
    continue;
    }
    if($k == 'manage')
    {
    $project[$k]['child']['manage_project'] = array
    (
    'name' => '管理菜单设置',
    'link' => Dever::load('manage/menu.link#project'),
    'order' => 1,
    );

    $project[$k]['child']['manage_log'] = array
    (
    'name' => '管理操作日志',
    'link' => Dever::load('manage/menu.link#log'),
    'order' => 1,
    );

    //print_r($project[$k]);die;
    }
    //array_multisort($v['child_order'], SORT_DESC, $v['child']);
    $order = array();
    foreach($project[$k]['child'] as $i => $j)
    {
    $order[] = $j['order'];
    }
    array_multisort($order, SORT_DESC, $project[$k]['child']);
    }

    //此处加缓存吧，不过要针对用户，加到session中也可以

    return $project;
     */
    }

    /**
     * menu 获取快捷管理菜单
     *
     * @return array
     */
    public function fast()
    {
        $this->left();
        return $this->fast;
    }

    /**
     * menu 对一些固定的菜单，生成其链接
     *
     * @return array
     */
    public function link()
    {
        return array
            (
            'project' => Dever::url('project/list?menu=manage&table=manage_project'),
            'log' => Dever::url('log/list?menu=manage&table=manage_log'),
            'logout' => Dever::url('auth.quit?t=1'),
            'index' => Dever::url('home?t=1'),
        );
    }

    /**
     * getLink
     *
     * @return array
     */
    public function getLink($param)
    {
        $extend = '';
        if (is_array($param)) {
            $key = $param[0];
            $type = $param[1];
            $extend = isset($param[2]) ? $param[2] : '';
        } else {
            $key = $param;
            $type = 'list';
        }
        $info = Dever::load('manage/menu-one', array('option_key' => $key));

        $link = '';
        if ($info) {
            $link = $info['link'] . '&menu_id=' . $info['id'] . '&' . $extend;

            if ($type != 'list') {
                $link = str_replace('project/database/list', 'project/database/' . $type, $link);
            }
        }

        $link = Dever::url($link);

        return $link;
    }

    /**
     * database
     *
     * @return array
     */
    public function database()
    {
        $this->config();

        $result = array();

        $method = $this->project . '/' . $this->table . '-list';

        $data = Dever::load($method);

        //print_r($data);die;
        //print_r(Helper::page("current"));die;

        if ($data) {
            foreach ($data as $k => $v) {
                $result[$k] = '<tr>';

                foreach ($this->config['manage']['list'] as $ki => $vi) {
                    if (isset($v[$vi['col']]) && $v[$vi['col']]) {
                        if (isset($vi['value'])) {
                            $eval = '$value = ' . str_replace('{col}', $v[$vi['col']], $vi['value']) . ';';

                            eval($eval);

                            if ($value) {
                                $v[$vi['col']] = $value;
                            }

                        } elseif (isset($vi['modal'])) {
                            $v[$vi['col']] = '<a href="#" data-toggle="modal" data-target="#DEVER_modal" onclick="$(\'#DEVER_modal_body\').html($(this).next().html())">' . $vi['modal'] . '</a><div style="display:none;">' . $v[$vi['col']] . '</div>';
                        } elseif (isset($vi['option'])) {
                            $v[$vi['col']] = $vi['option'][$v[$vi['col']]];
                        }

                        $result[$k] .= '<td>' . $v[$vi['col']] . '</td>';
                    } elseif ($vi['col'] == 'manage' && isset($vi['value']) && is_array($vi['value'])) {
                        $result[$k] .= '<td>';
                        foreach ($vi['value'] as $kj => $vj) {
                            $result[$k] .= '<a href="' . $this->url($kj, $v['id']) . '" class="oper_' . $kj . '">' . $vj . '</a>';
                        }
                        $result[$k] .= '</td>';

                    }
                }

                $result[$k] .= '</tr>';
            }
        }

        return $result;
    }
}
