<?php
namespace Manage\Src;

use Dever;
use Dever\Routing\Uri;
use Dever\Session\Oper;
use Dever\String\Encrypt;

class Auth
{
    /**
     * 后台的session名
     *
     * @var string
     */
    private $name;

    /**
     * save
     *
     * @var Dever\Plad\Save
     */
    private $save;

    /**
     * __construct
     *
     * @return mixed
     */
    public function __construct()
    {
        $this->save = new Oper(DEVER_PROJECT, 'cookie');
        $this->name = DEVER_PROJECT . '_manage';
    }

    public function test()
    {
        return array('name' => 'test', 'check' => false, 'data' => array
        (
            0 => array('name' => 'haha1'),
            1 => array('name' => 'haha2'),
        ));
    }

    /**
     * 只获取中间的内容部分
     *
     * @return mixed
     */
    public function loading()
    {
        $set = Dever::input('loading');
        if ($set) {
            Dever::config('base')->url = 'loading=' . $set;
        }

        return $set;
    }

    /**
     * 获取角色
     *
     * @return mixed
     */
    public function role_api()
    {
        $data = Dever::db('manage/role')->alls(array
            (
                /* list和all可以自定义参数
                'option' => array
                (
                'name' => array('yes', 'like')
                ),
                 */
                //'option_name' => '%' . Dever::input('term', 'test') . '%')
                'option_name' => Dever::input('term', 'test'))
        );

        //Dever::debug($data);
        if ($data) {
            return $data;
        }
        return array
            (
            0 => array('id' => -1, 'value' => '没有找到您搜索的数据', 'label' => '没有找到您搜索的数据'),
        );
    }

    public function blur()
    {
        $value = Dever::input('value');

        return 1;
    }

    /**
     * 获取当前登录的管理员信息
     *
     * @return mixed
     */
    public function info($state = true)
    {
        return $this->real($this->data(), $state);
    }

    /**
     * 实时读取信息
     *
     * @return mixed
     */
    public function real($info, $state = true)
    {
        if ($state == true && Dever::config('base')->getAdmin && $info && isset($info['id'])) {
            $admin = Dever::db('manage/admin')->one($info['id']);
            if ($admin['top']) {
                $info['top'] = $admin['top'];
            }
        }

        if (!$info) {
            $info = $this->auth();
            if ($info) {
                $this->save($info);
                Dever::location(Dever::url(''));
            }
        }

        if (isset($info['role']) && $info['role']) {
            $info['role_info'] = Dever::db('manage/role')->one($info['role']);
            $info['rolename'] = '未分组';
            if ($info['role_info']['name']) {
                $info['rolename'] = $info['role_info']['name'];
            }

            $info['self'] = $info['role_info']['self'];
            $info['col_update'] = $info['role_info']['col_update'];
            $info['col_insert'] = $info['role_info']['col_insert'];
            $info['col_select'] = $info['role_info']['col_select'];
        }

        if (isset($info['group']) && $info['group']) {
            $info['group_info'] = Dever::db('manage/group')->one($info['group']);
        }

        return $info;
    }

    /**
     * 获取当前登录的管理员信息
     *
     * @return mixed
     */
    public function data($state = true)
    {
        return $this->save->get($this->name);
    }

    private function auth()
    {
        # 此处可以接入当前的用户系统
        /*
        $user = \CondeAdminUser::GetAdminInfo('manage', '后台管理');

        $info = Dever::load('manage/admin-user', array('where_username' => $user['name']));
        //$info = Dever::load('manage/admin-user', array('where_email' => $user['email']));
        if(!$info)
        {
        $id = Dever::load('manage/admin-insert', array('add_role' => 1, 'add_username' => $user['name'], 'add_email' => $user['email']));
        $info = Dever::load('manage/admin-one', $id);
        }

        return $info;
         */
        return false;
    }

    /**
     * 获取公告
     *
     * @return mixed
     */
    public function notice()
    {
        $admin = $this->info();
        if ($admin && $admin['config'] && isset($admin['config']['id']) && $admin['config']['id'] > 0) {
            $data = Dever::db('manage/notice')->getAll(array('where_config' => $admin['config']['id']));

            return $data;
        }

        return array();
    }

    /**
     * 获取当前登录的管理员信息
     *
     * @return mixed
     */
    public function manage()
    {
        $admin = $this->info();
        if ($admin && $admin['id'] == 1) {
            return '';
        }
        return 'display:none;';
    }

    /**
     * 退出登录
     *
     * @return mixed
     */
    public function quit_api()
    {
        if ($this->info()) {
            $this->save->un($this->name);
        }

        Dever::location('login');
    }

    /**
     * login
     *
     * @return mixed
     */
    public function login_api()
    {
        //$param['where_username'] = Dever::input('username');
        $param['where_email'] = Dever::input('username');

        $password = hash('sha256', Dever::input('password'));

        //print_r($param);die;

        $user = Dever::db('manage/admin')->user($param);

        //print_r($user);die;

        if (!$user) {
            $total = Dever::db('manage/admin')->total();
            if ($total <= 0) {
                $insert['username'] = $param['where_email'];
                $insert['email'] = $param['where_email'];
                $insert['password'] = Dever::input('password');
                $insert['status'] = $insert['state'] = 1;
                Dever::db('manage/admin')->insert($insert);

                $param['time'] = 1;
                $user = Dever::db('manage/admin')->user($param);
            }
        }

        if ($user && $user['password'] == $password) {
            $this->save($user);

            $refer = Dever::input('refer');

            if ($refer) {
                $refer = Encrypt::decode($refer);
                /*
                $url = parse_url(Encrypt::decode($refer));
                $url['path'] = preg_replace('/^\//', '', $url['path']);
                if (empty($url['query'])) {
                    $url['query'] = '';
                }

                if (Uri::$type == '?') {
                    $refer = Dever::url(str_replace($url['path'] . Uri::$type, '', $url['query']));
                } else {
                    $refer = Dever::url($url['path'] . '?' . $url['query']);
                }
                */

                Dever::out($refer);
            } else {
                Dever::out(Dever::url('home'));
            }
        } else {
            Dever::alert('登录失败');
        }
    }

    public function update($id)
    {
        $id = Dever::input('update_where_id');

        $admin = $this->info();
        if ($id > 0 && $id == $admin['id']) {
            $user = Dever::db('manage/admin')->one($id);
            $this->save($user);
        }
    }

    public function save(&$user)
    {
        if ($user['config']) {
            $user['config'] = Dever::db('manage/config')->one($user['config']);
        }
        if ($user['id'] == 1) {
            $user['oper'] = 'all';
            $user['auth'] = 'all';
            $user['top'] = 'all';
        } else {
            $role = Dever::db('manage/role')->get(array('where_id' => $user['role']));

            if ($role) {
                $user['oper'] = array();
                $user['auth'] = array();
                $user['self'] = 2;
                $top = array();
                foreach ($role as $k => $v) {
                    if ($v['oper']) {
                        if (strpos($v['oper'], ',') !== false) {
                            $user['oper'] += explode(',', $v['oper']);
                        } else {
                            $user['oper'][] = $v['oper'];
                        }
                    }
                    if ($v['auth']) {
                        $user['auth'][] = $v['auth'];
                    }
                    if (!$user['top'] && $v['top']) {
                        $top[] = $v['top'];
                    }
                    if ($v['self'] == 1) {
                        $user['self'] = $v['self'];
                    }
                }

                $user['oper'] = implode(',', $user['oper']);
                $user['auth'] = implode(',', $user['auth']);

                if (!$user['top'] && $top) {
                    $user['top'] = implode(',', $top);
                }

                if (strpos($user['oper'], 'all') !== false) {
                    $user['oper'] = 'all';
                }

                if (strpos($user['auth'], 'all') !== false) {
                    $user['auth'] = 'all';
                }

                if (strpos($user['top'], 'all') !== false) {
                    $user['top'] = 'all';
                }
            }
        }

        $this->save->add($this->name, $user, 3600 * 24 * 7);
    }

    /**
     * set
     *
     * @return mixed
     */
    public function set()
    {
        $param['refer'] = Dever::input('refer');

        return $param;
    }

    /**
     * location_login
     *
     * @return mixed
     */
    public function location_login()
    {
        $refer = Encrypt::encode(Dever::url());
        return Dever::location('login?refer=' . $refer);
    }

    /**
     * init
     *
     * @return mixed
     */
    public function init()
    {
        if (isset($this->load)) {
            return;
        }

        $this->load = true;
        $admin = $this->info();
        if (!$admin) {
            return $this->location_login();
        }

        if ($admin['id'] == 1) {
            return;
        }

        $menu = Dever::input('menu');
        $project = Dever::input('key');
        $table = Dever::input('table');
        $menu_id = Dever::input('menu_id');

        if ($menu_id && $menu_id > 0) {
            $menu = Dever::db('manage/menu')->info($menu_id);

            if (!$menu) {
                Dever::alert('没有该权限');
            }

            if ($menu['key']) {
                if (isset($admin['auth']) && $admin['auth']) {
                    if ($admin['auth'] == 'all' || $admin['auth'] == '') {
                        return;
                    }

                    $admin['auth'] = explode(',', $admin['auth']);

                    if (!in_array($menu['key'], $admin['auth'])) {
                        Dever::alert('您没有操作权限');
                    }
                } else {
                    Dever::alert('您没有操作权限');
                }
            } else {
                Dever::alert('您没有操作权限');
            }
        } else {
            //Dever::alert('您没有操作权限');
        }
    }

    # 得到当前管理员的权限
    public function admin()
    {
        $admin = $this->info();
        return $admin['auth'] == 'all' ? '' : explode(',', $admin['auth']);
    }

    # 得到当前头部菜单的权限
    public function top()
    {
        $admin = $this->info();
        return $admin['top'] == 'all' ? '' : $admin['top'];
        return $admin['top'] == 'all' ? '' : explode(',', $admin['top']);
    }

    # 设置头部菜单的权限
    public function _setTop($info)
    {
        if ($info) {
            $info['key'] = explode('_', $info['key']);
            $count = count($info['key']);
            if ($count > 2) {
                foreach ($info['key'] as $k => $v) {
                    if ($k+1 < $count) {
                        $key[] = $v;
                    }
                }
                $key = implode('_', $key);
            } else {
                $key = $info['key'][0];
            }

            $data = $this->data();

            $this->save->add($this->name . '_topgetv1_' . $key . '_a' . $data['id'], $info, 3600 * 24 * 365);
        }
    }

    # 得到当前头部菜单
    public function getTop($key)
    {
        $state = false;
        if (is_array($key)) {
            $key = $key[0];
            $state = true;
        }

        $data = $this->data();

        $key = str_replace('/', '-', $key);
        $data = $this->save->get($this->name . '_topgetv1_' . $key . '_a' . $data['id']);

        # 当数据不存在时，先从数据库里取出一个最新的
        if (!$data && $state == true) {
            $info = Dever::db('manage/top')->key(array('where_key' => $key));
            if ($info) {
                $data = Dever::db('manage/top')->getOne(array('where_top_id' => $info['id']));
            }
        }

        return $data;
    }

    public function config()
    {
        $admin = $this->info();

        if (!$admin && $id = Dever::input('auth')) {
            $admin['config']['id'] = $id;
        }
        if ($admin['config'] && $admin['config']['id'] > 0) {
            $admin['config'] = Dever::db('manage/config')->info(array('where_id' => $admin['config']['id']));
        }
        $state = isset($admin['config']) && $admin['config'];
        $admin['config']['title'] = ($state && $admin['config']['title']) ? $admin['config']['title'] : Dever::config('base')->name . '';
        $admin['config']['info'] = ($state && $admin['config']['info']) ? $admin['config']['info'] : Dever::config('base')->name . ' 欢迎您';
        $admin['config']['content'] = ($state && $admin['config']['content']) ? $admin['config']['content'] : '欢迎您使用本系统';
        $admin['config']['template'] = ($state && $admin['config']['template']) ? $admin['config']['template'] : 1;

        return $admin['config'];
    }

    /**
     * oper的判断
     *
     * @param uri string
     * @return mixed
     */
    public function oper($type = 1)
    {
        $oper = '';
        $admin = $this->info();
        //$role['oper'] = '1,2,3,4,5';
        if ($admin && isset($admin['oper']) && $admin['oper'] != 'all') {
            if (strpos(',' . $admin['oper'], ',' . $type) !== false) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * 获取当前uri的类型
     *
     * @param uri string
     * @return mixed
     */
    private function table($table, $project)
    {
        if ($table == 'other') {
            $table = '';
        } else {
            $path = Dever::load('manage/src/project.path', $project);
            $config = Dever::database(DEVER_PATH . $path . 'database/' . $table . '.php');
            $table = $config['lang'];
        }

        return $table;
    }

    /**
     * check
     *
     * @return mixed
     */
    public function check($id)
    {
        $id = Dever::input('update_where_id');

        # 先验证email是否已经存在
        $email = Dever::input('update_email');

        $info = Dever::db('manage/admin')->one(array('option_email' => $email));

        if ($id > 0 && $info && $info['id'] != $id) {
            Dever::alert('该邮箱已经存在');
        } elseif ($id < 0 && $info) {
            Dever::alert('该邮箱已经存在');
        }
    }

    /**
     * 获取当前uri的类型
     *
     * @param uri string
     * @return mixed
     */
    public function type($uri)
    {
        if (strpos($uri, '.') !== false) {
            $type = 3;
        } elseif (strpos($uri, '-') !== false) {
            $type = 2;
        } else {
            $type = 1;
        }
        return $type;
    }

    /**
     * 获取所有权限列表，并进行统计处理
     *
     * @return mixed
     */
    public function get($state = true)
    {
        $result = Dever::load('manage/src/menu.left', $state);
        $result['state'] = 1;

        return $result;
    }

    /**
     * 修改当前管理员的密码
     *
     * @return mixed
     */
    public function password()
    {
        $admin = $this->info();

        $new = Dever::input('new');
        $old = Dever::input('old');

        if ($admin && $admin['id'] > 0 && $new && $old && $new != $old && hash('sha256', ($old)) == $admin['password']) {
            $param['set_password'] = $new;

            $param['where_id'] = $admin['id'];
            Dever::db('manage/admin')->password($param);

            $admin['password'] = hash('sha256', ($new));
            $this->save->add($this->name, $admin);
            return '修改成功';
        } else {
            return '修改失败';
        }
    }

    /**
     * 更新数据到数据库
     *
     * @return array
     */
    public function update_action($param = array())
    {
        if (isset($param['key'])) {
            $info = Dever::db('manage/auth')->key(array('where_key' => $param['key']));
            //print_r($info);die;
            if (!$info) {
                $update['add_project'] = $param['project'];
                $update['add_project_name'] = $param['project_name'];

                $update['add_key'] = $param['key'];
                $update['add_name'] = $param['name'];
                $update['add_auth_id'] = isset($param['auth']) ? $param['auth'] : -1;
                $update['add_value'] = $param['value'];
                $update['add_state'] = isset($param['state']) ? $param['state'] : 1;

                $info['id'] = Dever::db('manage/auth')->insert($update);
            } else {
                $update['set_project'] = $param['project'];
                $update['set_project_name'] = $param['project_name'];
                $update['set_name'] = $param['name'];
                $update['set_value'] = $param['value'];
                $update['set_state'] = isset($param['state']) ? $param['state'] : 1;
                $update['where_id'] = $info['id'];
                Dever::db('manage/auth')->update($update);
            }

            return $info['id'];
        }

        return false;
    }

    /**
     * 同步子权限更新到数据库
     *
     * @return array
     */
    public function sync($param = array())
    {
        if (isset($param[0]) && isset($param[1])) {
            $key = $param[1]['key'];

            $info = Dever::db('manage/auth')->key(array('where_key' => $key));

            if ($info) {
                $update['value'] = Dever::input('where_id', $param[0]);

                $update['name'] = Dever::input('name', '-u');

                $update['top'] = $info['id'];

                $update['key'] = $key . '_' . $update['value'];

                $update['state'] = Dever::input('state', '-u');

                $this->update_action($update);
            }
        }
    }

    /**
     * 获取所有的项目精细权限
     *
     * @return array
     */
    public function all()
    {
        $data = Dever::db('manage/auth')->main;

        if ($data) {
            $child = Dever::db('manage/auth')->child;

            foreach ($data as $t => $d) {
                foreach ($d as $k => $v) {
                    if (isset($child[$v['id']])) {
                        $c = 0;
                        foreach ($child[$v['id']] as $i => $j) {
                            $data[$t][$k]['child'][$i] = $j;
                            $c++;
                        }

                        if (!isset($data[$t][$k]['child'])) {
                            unset($data[$t][$k]);
                        }
                    }
                }
                $data[$t]['state'] = 1;
            }

        }

        return $data;
    }

    /**
     * opt push
     *
     * @return mixed
     */
    public function opt($param = false)
    {
        $opt = new Opt;
        $opt->push($param);
    }

    /**
     * opt push
     *
     * @return mixed
     */
    public function opt_api($param = false)
    {
        $opt = new Opt;
        $opt->push($param);
    }

    /**
     * opt push
     *
     * @return mixed
     */
    public function api($param = false)
    {
        $api = new Api;
        $api->push($param);
    }

    /**
     * opt push
     *
     * @return mixed
     */
    public function api_api($param = false)
    {
        $api = new Api;
        $api->push($param);
    }
}
