<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DwbsUser;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    //获取用户列表
    public function list(Request $request){
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);
        $search_name=$request->input('search_name');
        $data=User::where(function($query){
            $query->whereNotNull('phone')
                ->orWhereNotNull('openId');
        });
        if($search_name){
            $data->where(function($query)use($search_name){
                $query->where('phone','like','%'.$search_name.'%')
                    ->orWhere('nickname','like','%'.$search_name.'%');
            });
        }
        $count=$data->count();
        $list=$data->select('name','nickname','phone','status','id','avatar')->orderBy('id','desc')->skip($num)->take($page_size)->get();

        foreach ($list as $k=>$v){
            $list[$k]->phone=mb_substr($v->phone,0,3).'********';
        }
        return $this->success_list($list,'成功',$count);
    }
    //导出用户列表
    public function export(Request $request){
        return $this->success([]);
    }
    //禁用 | 启用 用户
    public function disabled(Request $request){
        $user=User::where('id',$request->input('id'))->first();
        $user->status = $user->status ? 0 : 1;
        $res=$user->save();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }

    //修改客户信息
    public function editUserInfo(Request $request){
        $id=$request->input('id');
        $nickname=$request->input('nickname');
        $area_code=$request->input('area_code');
        $phone=$request->input('phone');
        $user=User::withTrashed()->where('phone',$phone)->first();
        if(!empty($user) && $user->id!=$id){
            return $this->error('450001','手机号已注册');
        }
        $dwbsUser=DwbsUser::withTrashed()->where('mobile',$phone)->first();
        if(!empty($dwbsUser)){
            return $this->error('450001','手机号已注册系统账号');
        }
        $res=User::where('id',$id)->update([
            'nickname'=>$nickname,
            'area_code'=>$area_code,
            'phone'=>$phone,
        ]);
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
}
