<?php

namespace App\Http\Controllers;

use App\LaborCompany;
use App\ProcessDailyParticipant;
use App\User;
use App\UserDetail;
use App\UserDutyCheck;
use App\UserLabor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserLaborController extends Controller
{
    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $userLabors=UserLabor::query()->with('userDetail')->orderBy('user_id','desc');
        $full_name = $request->user_name ?? false;
        if ($full_name){
            $userLabors->whereHas('userDetail',function($query)use($full_name){
                if (strpos($full_name, ',') || strpos($full_name, '，') || strpos($full_name, ' ')) {
                    $arr = array_filter(preg_split('/[,， ]+/is', $full_name));
                    $query->whereIn('full_name', $arr);
                    unset($full_name);
                } else {
                    $query->where('full_name','like',$full_name.'%');
                }
            });
        }
        $userLabors = $userLabors->paginate($request->paginate ?? 50);
        foreach ($userLabors as $userLabor){
            if($userLabor->userDetail){
                $userLabor->is_relieve_facility=$userLabor->userDetail->hasDutyCheckToken();
            }
        }
        return view('maintenance.userLabor.index',['userLabors'=>$userLabors]);
    }

    public function relieve(Request $request){
        $user_id=$request->input('user_id');
        if (!$user_id) return ['error'=>'传递空值！'];
        $token=Cache::get('dutyCheckTokenUser_'.$user_id);
        if ($token){
            Cache::pull('dutyCheckTokenStr_'.$token);
            Cache::pull('dutyCheckTokenUser_'.$user_id);
        }
        $userLabor=UserLabor::find($user_id);
        $userLabor->is_relieve_facility=$userLabor->getIsRelieveFacilityAttribute();
        return ['success'=>true,'userLabor'=>$userLabor];
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        if(!Gate::allows('临时工-查询')){ return redirect(url('/'));  }
        $userLabor=UserLabor::with(['userDetail','laborCompany'])->find($id);
        return view('maintenance.userLabor.show',['userLabor'=>$userLabor]);
    }
    //获取劳务记录
    public function getWorkRecord(Request $request){
        if(!Gate::allows('临时工-查询')){ return redirect(url('/'));  }
        $user_id=$request->input('user_id');
        if (!$user_id)return ['error'=>'提交ID失败！'];
        $processDailyParticipants=ProcessDailyParticipant::with('processDaily')
            ->where('user_id',$user_id)->orderBy('created_at','DESC')->limit(20)->get();
        return $processDailyParticipants;
    }
    //获取打卡记录
    public function getClockRecord(Request $request){
        if(!Gate::allows('临时工-查询')){ return redirect(url('/'));  }
        $user_id=$request->input('user_id');
        if (!$user_id)return ['error'=>'提交ID失败！'];
        $userDutyChecks=UserDutyCheck::orderBy('checked_at','DESC')->where('user_id',$user_id)->limit(20)->get();
        return $userDutyChecks;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if(!Gate::allows('临时工-编辑')){ return redirect(url('/'));  }
        $userLabor=UserLabor::with(['userDetail','laborCompany'])->find($id);
        $laborCompanies=LaborCompany::query()->select('id','name')->get();
        return view('maintenance.userLabor.edit',['userLabor'=>$userLabor,'laborCompanies'=>$laborCompanies,]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if(!Gate::allows('临时工-编辑')){ return redirect(url('/'));  }
        Validator::make($request->input(),[
            'full_name'=>'required|max:10',
            'mobile_phone'=>['required','integer','digits:11'],
            'gender'=>['required',Rule::in(['男', '女']),],
            'identity_number'=>'nullable',
            'default_hour_price'=>'nullable|min:0|max:999999|numeric',
            'name'=>'nullable',
        ],[
            'required'=>':attribute 不应为空',
            'min'=>':attribute 不得为0或为负',
            'numeric'=>':attribute 必须为数字',
            'max'=>':attribute 输入值过大或过长',
            'integer'=>':attribute 选择错误',
        ],[
            'full_name'=>'姓名',
            'mobile_phone'=>'电话',
            'gender'=>'性别',
            'identity_number'=>'身份证号',
            'default_hour_price'=>'默认计时单价',
            'name'=>'劳务所',
        ])->validate();
        $userDetail=UserDetail::find($id);
        $userDetail->full_name=$request->input('full_name');
        $userDetail->mobile_phone=$request->input('mobile_phone');
        $userDetail->gender=$request->input('gender');
        $userDetail->identity_number=$request->input('identity_number');
        $userDetail->update();
        app('LogService')->log(__METHOD__,"修改用户详情".__FUNCTION__,json_encode($userDetail),Auth::user()['id']);
        $default_hour_price=$request->input('default_hour_price');
        $laborCompanyName=$request->input('name');
        $labor_company_id=LaborCompany::where('name','=',$laborCompanyName)->value('id');
        $userLabor=UserLabor::find($id);
        if ($userLabor->default_hour_price!=$default_hour_price || $userLabor->labor_company_id!=$labor_company_id){
            $userLabor->default_hour_price=$default_hour_price;
            $userLabor->labor_company_id=$labor_company_id;
            $userLabor->update();
            app('LogService')->log(__METHOD__,"修改临时工".__FUNCTION__,json_encode($userLabor),Auth::user()['id']);
        }
        return redirect('maintenance/userLabor')->with('successTip','临时工“'.$userDetail->full_name.'”信息修改成功!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response|array
     */
    public function destroy($id)
    {
        if(!Gate::allows('临时工-删除')){ return redirect(url('/'));  }
        $userDetail=UserDetail::find($id);
        $user=User::find($id);
        $userLabor=UserLabor::find($id);
        if (!$userDetail || !$user || !$userLabor){
            return ['error'=>'未找到对应临时工'];
        }
        $userDetail->delete();
        app('LogService')->log(__METHOD__,"删除用户详情".__FUNCTION__,json_encode($userDetail),Auth::user()['id']);
        $user->delete();
        app('LogService')->log(__METHOD__,"删除临时工用户".__FUNCTION__,json_encode($user),Auth::user()['id']);
        $userLabor->delete();
        app('LogService')->log(__METHOD__,"删除临时工".__FUNCTION__,json_encode($userLabor),Auth::user()['id']);
        return ['success'=>true];
    }
}
