<?php
// +----------------------------------------------------------------------
// | 管理员新增
// +----------------------------------------------------------------------
// | Copyright (c) 2018 https://blog.junphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小黄牛 <1731223728@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\admin\auth;
use app\controller\SuperClass\Admin;

class Admin_insert extends Admin
{

    /**
     * @AopBefore(class="app\aop\AdminLogin", function="before")
     * @RequestMapping(route="/admin/auth/admin_insert", method="GET|POST", title="管理员新增")
     * @Ioc(class="\x\Db", name="Db")
    */
    public function run() {
        if (\x\Request::is_ajax()) {
            return $this->_insert();
        }
        $role = $this->Db->name('auth_role')->where('status = 1')->field('id, name')->select();
        $this->assign('role', $role);

        $this->Db->return();
        return $this->display();
    }

    // Ajax处理
    private function _insert() {
        $param = \x\Request::post();
        $vif = $this->_where($param);
        if ($vif !== true) {
            $this->Db->return();
            return false;
        }

        // 新增时间做为盐值
        $param['create_time'] = time();
        $param['pwd'] = md5($param['pwd'].$param['create_time']);

        $res = $this->Db->name('auth_admin')->insert($param);
        $this->Db->return();

        if ($res != false) {
            return $this->returnJson('00', '新增成功！');
        }
        return $this->returnJson('01', '新增失败！');
    }
    
    // 新增条件过滤
    private function _where($param=[]) {
        if (empty($param['name'])) return $this->returnJson('01', '请输入用户名');
        if (empty($param['pwd'])) return $this->returnJson('01', '请输入密码');
        // if (empty($param['phone'])) return $this->returnJson('01', '请输入手机号');

        $res = $this->Db->name('auth_admin')->where('name', $param['name'])->value('id');
        if ($res) return $this->returnJson('01', '用户名已存在!');

        // $res = $this->Db->name('auth_admin')->where('phone', $param['phone'])->value('id');
        // if ($res) return $this->returnJson('01', '手机号已存在!');

        return true;
    }
}

