<?php

namespace App\Http\Controllers;
use App\Lib\Captcha;
use Illuminate\Http\Request;
use App\Http\Services\AdminUserService;

class AdminUserController extends BaseController
{
    //数据处理层初始化
    protected $Service;

    /**
     * 构造方法,初始化service
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct() {
        $this->Service = new AdminUserService();
    }

    public function getList(Request $request){

        $search_data['phone'] = $request->input('phone', "");
        $search_data['user_name'] = $request->input('user_name', "");

        $data = $this->Service->getList($search_data);
        return  response()->json($data);
    }

    public function addUser(Request $request){

        $data['phone'] = $request->input('phone', "");
        $data['pwd'] = $request->input('pwd', "");
        $data['user_name'] = $request->input('user_name', "");
        if (!empty($data['phone']) && !preg_match('/^\d{11}$/',$data['phone'])) {
            return $this->respondError(10014, '手机号格式不正确');
        }
        if(empty($data['pwd']) || strlen($data['pwd']) == 0){
            $data['pwd'] = md5($data['phone']);
        }
        if (!empty($data['user_name'])) {
            return $this->respondError(10014, '请输入用户名');
        }

        // 校验重复
        $res = $this->Service->checkRepeat($data['phone']);
        if($res){
            return $this->respondError(10014, '手机号已存在');
        }
        $res = $this->Service->add($data);
        return  response()->json($res);
    }


    public function editUser(Request $request){

        $data['id'] = $request->input('id', "");
        $data['phone'] = $request->input('phone', "");
        $data['pwd'] = $request->input('pwd', "");
        $data['user_name'] = $request->input('user_name', "");
        $data['status'] = $request->input('status', "");
        if (!empty($data['phone']) && !preg_match('/^\d{11}$/',$data['phone'])) {
            return $this->respondError(10014, '手机号格式不正确');
        }
       
        $res = $this->Service->edit($data);
        return  response()->json($res);
    }


    public function delUser(Request $request){

        $id = $request->input('id', ""); //
        if (empty($id)) {
            return $this->respondError(10001, 'id不能为空');
        }
        $req['id'] = $id;
        // $req['is_del']=1;
        $data = $this->Service->Del($req);
        return  response()->json($data);
    }

    public function getUserInfo(Request $request) {
        $userInfo = $request->attributes->get('user_info');

        unset($userInfo['pwd']);

        return $this->respondSuccess($userInfo);
    }


}