<?php
namespace Factory\Admin;

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(false, 'session');
        $this->name = 'factory';
    }

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

        return $info;
    }

    public function check()
    {
        $sign = Dever::input('sign');
        if ($sign) {
            $sign = Dever::checkLogin($sign);
            if ($sign && isset($sign['uid']) && $sign['uid'] > 0) {
                $user = Dever::db('factory/member')->getManage(array('factory_id' => $sign['uid'], 'role_id' => '1'));
                if ($user) {
                    $this->save($user);
                    Dever::location('home', 'factory');
                }
            }
        }

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

        return $admin;
    }

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

        return $set;
    }

    public function config()
    {
        $config = Dever::db('main/factory_config')->find();

        $config['refer'] = Dever::input('refer');

        $config['login_url'] = Dever::url("factory/admin/auth.login");

        $config['mcode_url'] = Dever::url("factory/admin/auth.getMcode?json=1");

        return $config;
    }

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

    /**
     * 获取手机随机验证码
     * @return mixed
     */
    public function getMcode_api()
    {
        $mobile = $this->checkMobile();

        $user = Dever::db('factory/member')->find(array('mobile' => $mobile));
        if (!$user) {
            Dever::alert('该手机号还未注册');
        }

        $code = Dever::load('passport/reg')->mcode($mobile);

        $msg = '验证码已发送至您的手机，请注意查收，十分钟之内有效';
        $debug = Dever::config('base', 'project')->mobileCode['debug'];
        if ($debug) {
            $msg .= '::' . $code;
        }
        return $msg;
    }

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

        Dever::location('login');
    }

    /**
     * 登录
     *
     * @return mixed
     */
    public function login_api()
    {
        $where['mobile'] = $this->checkMobile();
        $this->checkMcode($where['mobile']);
        $user = Dever::db('factory/member')->find($where);

        if (!$user) {
            Dever::alert('登录失败，手机号错误，请重新输入');
        }

        if ($user) {
            $this->save($user);
            $refer = Dever::input('refer');
            if ($refer) {
                $refer = Encrypt::decode($refer);
                Dever::out($refer);
            } else {
                Dever::out(Dever::url('home'));
            }
        } else {
            Dever::alert('登录失败');
        }
    }

    /**
     * 验证手机号
     * @return mixed
     */
    private function checkMobile()
    {
        $rule = Dever::rule('mobile');

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

        if (!$mobile) {
            Dever::alert('手机号不能为空');
        }
        if (!preg_match($rule, $mobile)) {
            Dever::alert('手机号码格式错误');
        }

        return $mobile;
    }

    /**
     * 验证验证码
     * @return mixed
     */
    private function checkMcode($mobile)
    {
        $code = Dever::input('mcode');
        if (!$code) {
            Dever::alert('请输入验证码');
        }
        $code = Dever::load('passport/reg')->mcode($mobile, $code);
        if (!$code) {
            Dever::alert('验证码输入错误');
        }
    }

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

    /**
     * cookie 处理cookie
     *
     * @return array
     */
    public function cookie()
    {
        $cookie = $_COOKIE;
        $array = array();
        # 判断手机版
        $mobile = Dever::mobile();
        if ((isset($cookie['left_menu']) && $cookie['left_menu'] == 'close') || $mobile) {
            $array['wrapper'] = 'enlarged forced';
        } else {
            $array['wrapper'] = 'forced';
        }
        return $array;
    }

    /**
     * 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('admin/auth.quit'),
            'index' => Dever::url('home'),
            'console' => Dever::url('console'),
        );
    }

    /**
     * location_login
     *
     * @return mixed
     */
    public function location_login()
    {
        $refer = Encrypt::encode(Dever::url());
        $admin = $this->info();
        if ($admin) {
            Dever::location('home', 'factory');
        }
        return Dever::location('factory/login?refer=' . $refer);
    }

    # 编辑员工
    public function edit_api()
    {
        $admin = $this->info();
        if (!$admin) {
            Dever::alert('您没有权限修改');
        }
        $id = $admin['id'];
        $name = Dever::input('name');
        $mobile = Dever::input('mobile');

        if ($name) {
            $update['name'] = $name;
        } else {
            Dever::alert('姓名不能为空');
        }

        if ($mobile) {
            $update['mobile'] = $mobile;
            $check = Dever::db('factory/member')->find(array('mobile' => $mobile, 'factory_id' => $admin['factory_id']));
            if ($check && $id && $id != $check['id']) {
                Dever::alert('电话已存在');
            } elseif ($check && !$id) {
                Dever::alert('电话已存在');
            }
        } else {
            Dever::alert('电话不能为空');
        }

        $update['factory_id'] = $admin['factory_id'];

        if ($id) {
            $update['where_id'] = $id;
            Dever::db('factory/member')->update($update);
        } else {
            $id = Dever::db('factory/member')->insert($update);
        }
        $user = Dever::db('factory/member')->find($id);
        $this->save($user);

        return '操作成功';
    }

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

        $data = array
        (
            'console' => array
            (
                'icon' => 'home',
                'name' => '概况',
                'link' => Dever::url('console', 'factory'),
            ),

            'order' => array
            (
                'icon' => 'app',
                'name' => '订单处理',
                'child' => array
                (
                    'order' => array
                    (
                        'name' => '订货单处理',
                        'link' => Dever::url('order', 'factory'),
                    ),
                ),
            ),

            'stat' => array
            (
                'icon' => 'date',
                'name' => '结算对账',
                'child' => array
                (
                    'stat' => array
                    (
                        'name' => '对账单',
                        'link' => Dever::url('stat', 'factory'),
                    ),
                ),
            ),

            'set' => array
            (
                'icon' => 'set',
                'name' => '基础设置',
                'child' => array
                (
                    'set' => array
                    (
                        'name' => '企业资质',
                        'link' => Dever::url('set', 'factory'),
                    ),
                    'msg' => array
                    (
                        'name' => '消息通知',
                        'link' => Dever::url('msg', 'factory'),
                    ),
                    'user' => array
                    (
                        'name' => '账号管理',
                        'link' => Dever::url('user', 'factory'),
                    ),
                    'help' => array
                    (
                        'name' => '帮助文档',
                        'link' => Dever::url('help', 'factory'),
                    ),
                ),
            ),
        );

        $role = explode(',', $info['role_id']);

        $type = false;
        if (!in_array(1, $role)) {
            $type = array(1,2,6);
            unset($data['set']['child']['set']);
            unset($data['set']['child']['user']);
            if (!in_array(2, $role)) {
                unset($data['order']);
                unset($type[1]);
            }
            if (!in_array(4, $role)) {
                unset($data['stat']);
                unset($type[2]);
            }
            $type = implode(',', $type);
        }

        $this->msg = 0;

        /*
        if ($info && Dever::project('message')) {
            $this->msg = Dever::load('message/lib/data')->num($info['factory_id'], 4, $type);
        } else {
            $this->msg = 0;
        }
        */

        return $data;
    }

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

        $html = '';
        foreach ($data as $k => $v) {
            if (!isset($v['key'])) {
                $v['key'] = $k;
            }
            $v['icon'] = $v['icon'] ? "layui-icon layui-icon-" . $v['icon'] : "layui-icon layui-icon-home";
            $cur = 'layui-nav-itemed';
            if ($k == 'console') {
                $cur = 'layui-this';
            }
            $html .= '<li data-name="'.$v['key'].'" class="layui-nav-item menu_group '.$cur.'">';

            if (isset($v['child']) && $v['child']) {
                $link = 'href="javascript:;"';
            } else {
                $link = 'lay-href="'.$v['link'].'"';
            }
            $html .= '<a '.$link.' lay-tips="'.$v['name'].'" lay-direction="2">';
            $html .= '<i class="'.$v['icon'].'"></i><cite>'.$v['name'].'</cite></a>';

            $html .= $this->getMenuChild($v);

            $html .= '</li>';
        }
        $html .= '';

        return $html;
    }

    public function getMenuChild($v)
    {
        $html = '';

        if (isset($v['child']) && $v['child']) {
            $html .= '<dl class="layui-nav-child">';
            foreach ($v['child'] as $k1 => $v1) {
                if (!isset($v1['key'])) {
                    $v1['key'] = $k1;
                }
                $html .= '<dd data-name="'.$v1['key'].'">';
                if (isset($v1['child']) && $v1['child']) {
                    $html .= '<a href="javascript:;">'.$v1['name'].'</a><dl class="layui-nav-child">';
                    foreach ($v1['child'] as $k2 => $v2) {
                        if (!isset($v2['key'])) {
                            $v2['key'] = $k2;
                        }
                        $html .= '<dd data-name="'.$v2['key'].'"><a lay-href="'.$v2['link'].'">'.$v2['name'].'</a></dd>';
                    }
                    $html .= '</dl>';
                } else {
                    if ($k1 == 'msg' && $this->msg) {
                        $v1['name'] .= '<span class="layui-badge">'.$this->msg.'</span>';
                    }
                
                    $html .= '<a lay-href="'.$v1['link'].'">'.$v1['name'].'</a>';
                }



                $html .= '</dd>';


            }
            $html .= '</dl>';
        }

        return $html;
    }
}
