<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;


class Adminuser extends Base
{
    public function index( $id = 0, $tab = 0 ){
        if(!checkAuth()){
            echo "<script>parent.window.location.href='/admin/index/index';</script>";
            exit;
        }
        $infoList = Db::name('adminuser')->order('id desc')->select();
        $auth_group = Db::name('auth_group')->column('id,title');

        $this->assign('infoList',$infoList);
        $this->assign('auth_group',$auth_group);

        // 编辑
        if( 3 == $tab ) {
            $info = db('adminuser')->where('id',$id)->find();
            $this->assign('info',$info);
        }
        

        return view();
    }

   
 // datatables插件请求地址
    public function getDataTables() {
       
        //获取请求过来的数据
        $getParam = request()->param();

        $draw = $getParam['draw'];

        //排序
        $orderSql = 'id desc';

        //自定义查询参数
        $extra_search = $getParam['extra_search'];

        // 获取表名
        $tablename = 'adminuser';
        // 总记录数
        $recordsTotal = Db::name($tablename)->count();
        //过滤条件后的总记录数
        $search = $getParam['search']['value'];
        $recordsFiltered = strlen($search) ?  Db::name($tablename)->where($extra_search,'like','%'.$search.'%')->count() : $recordsTotal;

        //分页
        $start = $getParam['start']; //起始下标
        
        $length = $getParam['length']; //每页显示记录数

        //根据开始下标计算出当前页
        $page = intval($start/$length) + 1;
        $config = ['page'=>$page, 'list_rows'=>$length];
        $list = Db::name($tablename)->where($extra_search,'like','%'.$search.'%')->order($orderSql)->paginate(null,false,$config);
        $lists = [];
        if(!empty($list)){
            foreach ($list as $key => $value) {
                $lists[$key] = $value;

                if($lists[$key]['status']==1){
                    $lists[$key]['status'] ="<button class='btn btn-success' id='".$value['id']."'   onclick='changestatus(this);'>启用</button>";
                }else{
                    $lists[$key]['status'] ="<button class='btn btn-warning' id='".$value['id']."'   onclick='changestatus(this);'>禁用</button>";
                }

                $lists[$key]['auth_group_title'] = Db::name('auth_group')->cache(true)->where('id',$value['auth_group_id'])->value('title');
                $lists[$key]['operate'] = "<a href='". url('index',['id'=>$value['id'],'tab'=>3]) ."' title='编辑'><i class='fa fa-edit text-navy'></i></a>&nbsp;&nbsp;
                <a name='delete' href='". url('delete',['id'=>$value['id']]) ."' title='删除'><i class='fa fa-trash-o text-navy'></i></a>";
            }
        }

        $data = array(
            "draw"=>$draw,
            "recordsTotal"=>$recordsTotal, //数据总数
            "recordsFiltered"=>$recordsFiltered, //过滤之后的记录总数
            "data"=>$lists
        );

        echo json_encode($data);
    }

   

    

     //添加新用户
    public function add($requireField = '', $requireFieldName = '') {
        
        if(request()->isPost()) {
            $data = input('post.');

            if($_FILES['pic']['tmp_name']){
                $data['pic']=$this->upload();
            }
            
            if (strlen($data['username'])>30 || strlen($data['username'])<6)
              {
                $this->error("用户名必须为6-30位的字符串");
              }
              if(preg_match("/^\d*$/",$data['username']))
              {
                $this->error("用户名必须包含字母,强度:弱");//全数字
              }
             
             if (strlen($data['password'])>30 || strlen($data['password'])<6){
                $this->error("密码必须为6-30位的字符串");
              }
              if(preg_match("/^\d*$/",$data['password']))
              {
                $this->error("密码必须包含字母,强度:弱");//全数字
              }
              if(preg_match("/^[a-z]*$/i",$data['password']))
              {
                $this->error("密码必须包含数字,强度:中");//全字母
              }
              if(!preg_match("/^[a-z\d]*$/i",$data['password']))
              {
               $this->error("密码只能包含数字和字母,强度:强");//有数字有字母 ";
              }
           
            if(preg_match("/^1[345678]{1}\d{9}$/",$data['mobile'])==''){
                $this->error('手机！');
                exit();
            }


            $pattern="/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
            if(preg_match($pattern,$data['email'])==''){
               $this->error('邮箱格式错误！');
                exit();
            }

            

            $newname=$data['username'];
            $searchname=Db::name('adminuser')->where('username',$newname)->find();
        
            if(!empty($searchname)){
                 
                $this->error('用户已存在');
                exit();
            }

            $data['password']=md5($data['password']);
            $id = Db::name('adminuser')->strict(false)->insertGetId($data);

            //添加角色
            $group_access = ['uid' => $id, 'group_id' => $data['auth_group_id']];
            Db::name('auth_group_access')->insert($group_access);

            $this->success('新用户添加成功!',url('index',['tab'=>1]));
        }
    }






    //删除单用户
    public function delete($id = 0) {
        $aduser=db('adminuser');
        $aduserres=$aduser->field('pic')->find($id);
        $aduserImg=IMG_UPLOADS.$aduserres['pic'];
        if(file_exists($aduserImg)){
            @unlink($aduserImg);
         }
        if(Db::name('adminuser')->where('id',$id)->delete()){
            // 删除相应角色
            db('auth_group_access')->where('uid',$id)->delete();
            $this->success('用户删除成功!',url('index',['tab'=>1]));
        }else{
            $this->error('删除失败!');
        }
    }

    public function status(){
       $id=input('param.id');
       $statusres=db('adminuser')->field('id,status')->find($id);
        $artshow=$statusres['status'];
        if($artshow==1){
            db('adminuser')->where(array('id'=>$id))->update(['status'=>0]);
        }else{
            db('adminuser')->where(array('id'=>$id))->update(['status'=>1]);
        }
       $this->success('操作成功',url('index'));  
    }

    // 编辑用户
    public function edit( $id = 0, $requireField = '', $requireFieldName = '' ) {
        if(request()->isPost()) {
            $data = input('post.');

            if($_FILES['pic']['tmp_name']){
                $oldadrts=db('adminuser')->field('pic')->find($data['id']);
                $oldadrtImg=IMG_UPLOADS.$oldadrts['pic'];
                if(file_exists($oldadrtImg)){
                    @unlink($oldadrtImg);
                }
                $data['pic']=$this->upload();
            }
            // 判断密码是否为空
            if(trim($data['password']=='')){
                unset($data['password']);
            }else{
              if (strlen($data['password'])>30 || strlen($data['password'])<6){
               $this->error("密码必须为6-30位的字符串");
              }
              if(preg_match("/^\d*$/",$data['password']))
              {
                $this->error("密码必须包含字母,强度:弱");//全数字
              }
              if(preg_match("/^[a-z]*$/i",$data['password']))
              {
                $this->error("密码必须包含数字,强度:中");//全字母
              }
              if(!preg_match("/^[a-z\d]*$/i",$data['password']))
              {
                $this->error("密码只能包含数字和字母,强度:强");//有数字有字母 ";
              }
                $data['password']=md5($data['password']);
            }
            $result = db('adminuser')->where('id',$id)->strict(false)->update($data);
            if($result !== false){
                // 如果用户角色有变化做相应修改
                if($data['authGroupId'] != $data['auth_group_id']){
                    db('auth_group_access')->where('uid',$id)->setField('group_id',$data['auth_group_id']);
                }
                $this->success('用户信息编辑成功!',url('index'));
            }else{
                $this->error('用户信息编辑失败!');
            }
        }
    }

    //上传图片
    public function upload(){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('pic');
    
    // 移动到框架应用根目录/public/uploads/ 目录下
    if($file){
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            return $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
            die;
        }
    }
}

}
