<?php
namespace App\Services\Admin;
use Illuminate\Support\Facades\DB;
use App\Services\Login\LoginService;

class UserService
{
    public function GetInfoList($arr){
        $list=DB::table('users as a')
            ->select( 'a.id', 'a.cn_name as cname','a.username as uname','a.status','a.created_at','b.group_name','c.department_name','a.ward')
            ->leftJoin('group as b','a.group','=','b.id')
            ->leftJoin('s_department as c','a.department_id','=','c.id');
        if(isset($arr['status'])){
            $list=$list->where(['a.status'=>$arr['status']]);
        }
        if(isset($arr['cname'])){
            $list=$list->where('a.cn_name', 'like', '%'.$arr['cname'].'%');
        }
        if(isset($arr['departmentid'])){
            $list=$list->where('a.department_id', $arr['departmentid']);
        }
        if(isset($arr['ward'])){
            $list=$list->whereRaw("FIND_IN_SET(?, a.ward)", [$arr['ward']]);
        }
        $count=$list->count();
        $list=$list
            ->skip(($arr['page']-1)*$arr['pagesize']) // 跳过前9999条记录
            ->take($arr['pagesize'])->get();
        $result['list']=$list;
        $result['count']=$count;
        return $result;
    }
    public function Save($arr){
        $result=[];
        if($arr['info']['id']){
            $query=DB::table('users')->where(['id'=>$arr['info']['id']])->update([
                'group' => $arr['info']['groupId'],
                'cn_name' => $arr['info']['cname'],
                'username' => $arr['info']['uname'],
                'status'=>$arr['info']['status'],
                'department_id'=> isset($arr['info']['department_id']) ?$arr['info']['department_id']: 0,
                'ward'=> isset($arr['info']['ward']) ?$arr['info']['ward']: null
            ]);
            if($query){
                $result['status']='ok';
                $result['msg']='操作成功';
            }else{
                $result['status']='no';
                $result['msg']='操作失败，没有记录被更新';
            }
        }else{
            $hash = password_hash('111111', PASSWORD_DEFAULT);
            $c=DB::table('users')->where(['username'=>$arr['info']['uname']])->get();
            if(count($c)){
                $result['status']='no';
                $result['msg']='用户名已存在';
                return $result;
            }
            DB::beginTransaction();
            try {
                $id=DB::table('users')->insertGetId([
                    'group' => $arr['info']['groupId'],
                    'cn_name' => $arr['info']['cname'],
                    'username' => $arr['info']['uname'],
                    'pwd' => $hash,
                    'status'=>1,
                    'department_id'=> isset($arr['info']['department_id']) ?$arr['info']['department_id']: 0,
                    'ward'=> isset($arr['info']['ward']) ?$arr['info']['ward']: null
                ]);

                DB::commit(); // 手动提交事务
                if($id){
                    $result['status']='ok';
                    $result['msg']='操作成功';
                }
            } catch (\Exception $e) {
                DB::rollback(); // 发生异常时手动回滚事务
                $result['status']='no';
                $result['msg']='操作失败';
            }

        }

        return $result;
    }
    public function GetDetail($arr){
        $c=DB::table('users')->select(['id','cn_name','username','status','group','img',])->where(['id'=>$arr['id']])->whereIn('status',[0,1])->get();
        if(count($c)){
            $result['info']=$c;
            $result['status']='ok';
            $result['msg']='成功';
        }else{
            $result['status']='no';
            $result['msg']='获取详情失败';
        }
        return $result;
    }
    public function ChangePwd($arr){
        $result=array();
        $s=app()->make(LoginService::class);
        $check=$s->CheckPwd(['userid'=>$arr['id'],'password'=>$arr['oldpwd']]);
        if($check['status']){
            $hash = password_hash($arr['newpwd'], PASSWORD_DEFAULT);
            $u=DB::table('users')->where(['id'=>$arr['id'],'status'=>1])->update(['pwd'=>$hash]);
            if($u){
                $result['status']='ok';
            }else{
                $result['status']='no';
                $result['msg']='修改密码失败';
            }
        }else{
            $result=$check;
        }
        return $result;
    }
    //重置密码
    public function resetPwd($group,$password,$userid)
    {
        $result=array();
      //  dd($group);
        if($group==1){
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $u=DB::table('users')->where(['id'=>$userid,'status'=>1])->update(['pwd'=>$hash]);
            if($u){
                return \Yz::return(true,'操作成功',[]);
            }else{
                return \Yz::echoError1('操作失败');
            }
        }else{
            return \Yz::echoError1('权限不足');
        }
    }

    //检查用户是否有某个目录的权限
    //参数['userid'=>$userid,'group'=>$group,'url'=>$url]
    public function CheckMenuAuth($arr){
        $list=['index','dashboard'];
        $q=DB::select("select * from users where id=? and `group` =?",[$arr['userid'],$arr['group']]);
        if(count($q)==1){
            if(in_array($arr['url'],$list)){
                return \Yz::Return(true,'',[]);
            }
            $check=DB::select("select * from (select menu_id from group_menu where group_id=? ) as a inner JOIN (select id from menu where url = ? ) as b on a.menu_id=b.id
",[$arr['group'],$arr['url']]);
            if(count($check)>0){
               return \Yz::Return(true,'',[]);
            }else{
                return  \Yz::echoError1('暂无权限');
            }
        }else{
            return \Yz::echoError1('权限不匹配');
        }
    }

    //修改自身信息
    public function ChangInfo($arr){
        $u=DB::table('users')->where(['id'=>$arr['userid']])->update([
            'cn_name'=>$arr['name'],
            'img'=>$arr['headimg'],
        ]);
        if($u>0){
            return \Yz::Return(true,'操作成功',[]);
        }else{
            return  \Yz::echoError1('更新失败');
        }
    }
}
