<?php
namespace App\Http\Controllers;

use App\Http\Resources\PermissionResource;
use App\Http\Requests\UsersRequest;
use App\Http\Resources\UserResource;
use App\Laravue\JsonResponse;
use App\Laravue\Models\Installer;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Validator;

class InstallerController extends Controller
{
    //装维人员列表
    public function installerlist (){
      return $this->jsonSuccessData(Installer::where('delete','=','1')
           ->get());
    }

    //用户添加
    public function addinstaller(Request $request){
        $validator = Validator::make($request->all(), $this->getValidationRulesinstaller(false));
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 403);
        }
        $type = new Installer();
        return $this->jsonSuccessData($type->addinstall($request->all()));
    }
    //更新用户操作
    public function updateinstaller(Request $request){
        $uid =  $request->input('uid');//用户id
        $data = $request->all();
        if (is_null($uid)){
            return $this->jsonErrorData(105,'用户id不能为空');
        }
        if ($_POST){
            foreach ($data as $k => $v) {
                if ($k == 'uid') {
                    unset($data[$k]);
                }
            }
            $upin = Installer::where('id','=',(int)$uid)->update($data);
            if($upin !== false){
                return $this->jsonSuccessData($upin);
            }
            return $this->jsonErrorData(105,'更新失败');

        }else{
                return $this->jsonSuccessData(Installer::where('id','=',$uid)->first());
        }
    }

    /*
     *删除用户
     * type 1== 物理 2==逻辑删除
     * */

    public function  deleteinstaller(Request $request){
        $type = $request->input('type');
        $uid = $request->input('uid');
        if(is_null($type)){
            return $this->jsonErrorData(105,'type不能为空');
        }
        if (is_null($uid)){
            return $this->jsonErrorData(105,'uid不能为空');
        }
        if ($type == 1){//物理删除
            return $this->jsonSuccessData(Installer::where('id','=',$uid)->delete());
        }elseif($type == 2){//逻辑删除
            return $this->jsonSuccessData(Installer::where('id','=',$uid)->update(['delete'=>2]));
        }

    }
    //验证用户提交表单

    private function getValidationRulesinstaller($isNew = true){
        return [
            'username'=>'required|unique:installer,username|max:3',
            'name'=> 'required|max:10',
            'phone'=> 'required|regex:/^1[3465789]\d{9}$/|unique:installer,phone|max:11',
            'email' => 'required|email',
            'password' =>'required|max:10',
        ];
    }
}