<?php

namespace App\Http\Controllers;

use App\Events\ExportEvent;
use App\Events\ImportEvent;
use App\Events\TeamAuditEvent;
use App\LaborReport;
use App\LaborReportStatus;
use App\ProcessDailyParticipant;
use App\Services\LaborReportService;
use App\UserDetail;
use App\UserDutyCheck;
use App\UserLabor;
use App\UserWorkgroup;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;


class PersonnelController extends Controller
{
    function __construct()
    {
        app()->bind('LaborReportService',LaborReportService::class);
    }
    //录入补卡
    public function storeReplenishClock(Request $request){
        if(!Gate::allows('人事管理-录入补卡')){ return redirect(url('/'));  }
        $errors=$this->validatorUserDutyCheck($request)->errors();
        if (count($errors)>0)return ['success'=>false,'error'=>$errors];
        $user_id=$request->input('user_id');
        $checked_at=$request->input('checked_at');
        $type=$request->input('type');
        $remark=$request->input('remark');
        $userWorkGroup=$request->input('userWorkGroup');
        $checkedAtDate=Carbon::parse($checked_at)->format('Y-m-d');
        /** @var LaborReportService $laborReportService */
        $laborReportService=app(LaborReportService::class);
        $laborReport=LaborReport::query()->with('userDutyCheck','user.userDetail')
            ->where('user_id',$user_id)
            ->where('created_at','like',$checkedAtDate.'%')
            ->orderBy('id','desc')->first();
        switch ($type) {
            case '进组':
              if ($laborReport && !$laborReport->check_in_at && !$laborReport->user_workgroup_id){ //第一次进组
                  $laborReport->update([
                      'check_in_at'=>$checked_at,
                      'verify_at'=>$checked_at,
                      'group_user_id'=>Auth::user()['id'],
                      'user_workgroup_id'=>$userWorkGroup,
                  ]);
                  LaborReportStatus::query()->create([
                      'labor_report_id'=>$laborReport['id'],
                      'status'=>'已进组',
                      'created_at'=>$checked_at,
                  ]);
                  if ($remark)$laborReportService->addOrUpdateRemark($remark,$laborReport->id);
                  app('LogService')->log(__METHOD__,"录入进组补卡".__FUNCTION__,json_encode($laborReport),Auth::user()['id']);
                  return ['success'=>true,'data'=>$laborReport->userDutyCheck];
              }
              if ($laborReport && $laborReport->user_workgroup_id==$userWorkGroup) return ['result'=>true,'data'=>'已存在进组记录!'];
              if ($laborReport && $laborReport->user_workgroup_id!=$userWorkGroup){ //换组情况
                  if ($laborReport->check_in_at && !$laborReport->check_out_at) return ['result'=>true,'data'=>'该临时工记录还未退组，不可补进组卡(换组)！'];
                  $laborReportStatus=LaborReportStatus::query()->where('labor_report_id',$laborReport->id)
                      ->where('status','已退场')->first();
                  if ($laborReportStatus) return ['result'=>true,'data'=>'该临时工记录已退场，不可补进组卡！'];
                  $newReport=new LaborReport([
                      'user_workgroup_id'=>$userWorkGroup,
                      'user_id'=>$laborReport->user_id,
                      'name'=>$laborReport->user->userDetail->full_name??'',
                      'mobile_phone'=>$laborReport->user->userDetail->mobile_phone??'',
                      'identity_number'=>$laborReport->user->userDetail->identity_number??'',
                      'labor_company_id'=>$laborReport->labor_company_id,
                      'check_in_at'=>$checked_at,
                      'group_user_id'=>Auth::user()['id'],
                      'user_duty_check_id'=>$laborReport->user_duty_check_id,
                  ]);
                  $newReport['enter_number']=$laborReport->enter_number??'';
                  $newReport->save();
                  $laborReportStatus=new LaborReportStatus([
                      'labor_report_id'=>$newReport['id'],
                      'status'=>'已换组',
                  ]);
                  $laborReportStatus->save();
                  $newReport=$newReport->loadMissing('userDutyCheck');
                  if ($remark)$laborReportService->addOrUpdateRemark($remark,$newReport->id);
                  app('LogService')->log(__METHOD__,"录入进组补卡".__FUNCTION__,json_encode($newReport),Auth::user()['id']);
                  return ['success'=>true,'data'=>$newReport->userDutyCheck];
              }
              break;
            case '退组':
//                $laborReport=LaborReport::query()->with('userDutyCheck')
//                    ->where('user_id',$user_id)
//                    ->where('created_at','like',$checkedAtDate.'%')
//                    ->orderBy('id','desc')->first();
                if ($laborReport && !$laborReport->check_out_at){
                    $laborReport->update([
                        'check_out_at'=>$checked_at,
                    ]);
                    LaborReportStatus::query()->create([
                        'labor_report_id'=>$laborReport['id'],
                        'status'=>'已退组',
                        'created_at'=>$checked_at,
                    ]);
                    if ($remark)$laborReportService->addOrUpdateRemark($remark,$laborReport->id);
                    app('LogService')->log(__METHOD__,"录入退组补卡".__FUNCTION__,json_encode($laborReport),Auth::user()['id']);
                    return ['success'=>true,'data'=>$laborReport->userDutyCheck];
                }else  return ['result'=>true,'data'=>'已存在退组记录!'];
            default:
                $userDutyCheck=new UserDutyCheck([
                    'user_id'=>$user_id,
                    'checked_at'=>$checked_at,
                    'type'=>$type,
                    'source'=>'补入',
                    'verify_user_id'=>Auth::user()['id'],
                ]);
                $userDutyCheckBefore=UserDutyCheck::query()->where('user_id',$user_id)->where('checked_at','like',$checkedAtDate.'%')->orderBy('id','desc')->first();
//                if ($userDutyCheckBefore['type']=='登入'&&$userDutyCheck->type=='登入')return ['result'=>true,'data'=>'已存在进场记录！'];
                if ($laborReport && $userDutyCheck->type=='登入')return ['result'=>true,'data'=>'已存在进场记录！'];
                if ($userDutyCheckBefore['type']=='登出'&&$userDutyCheck->type=='登出')return ['result'=>true,'data'=>'已存在出场记录！'];
                $userDutyCheck->save();
                app('LogService')->log(__METHOD__,"录入补卡".__FUNCTION__,json_encode($userDutyCheck),Auth::user()['id']);
                $errorMessage=$this->makeOrUpdateLaborReport($userDutyCheck,$remark);
                if ($errorMessage)return $errorMessage;
                return ['success'=>true,'data'=>$userDutyCheck];
        }
    }
    //补卡创建或修改临时工报表
    public function makeOrUpdateLaborReport($userDutyCheck,$remark){
        $checkedAtDate=Carbon::parse($userDutyCheck->checked_at)->format('Y-m-d');
        $laborReport=LaborReport::query()->where('user_id',$userDutyCheck->user_id)->where('created_at','like',$checkedAtDate.'%')->orderBy('id','desc')->first();
        /** @var LaborReportService $laborReportService */
        $laborReportService=app(LaborReportService::class);
        if (!$laborReport&&$userDutyCheck->type=='登入'){
            $newReport=$userDutyCheck->makeEnteringRecord();
            $laborReportService->addOrUpdateRemark($remark,$newReport->id);
            app('LogService')->log(__METHOD__,"进场创建临时工报表记录__".__FUNCTION__,json_encode([$userDutyCheck]));
//            if ($newReport) event(new ImportEvent($newReport));
        }
        else if(!$laborReport&&$userDutyCheck->type=='登出'){
            //退场时间跨天情况
            $yesterdayDate=Carbon::parse($userDutyCheck->checked_at.':00')->subDays(1)->format('Y-m-d');
            $laborReportYesterday=LaborReport::query()->where('user_id',$userDutyCheck->user_id)->where('created_at','like',$yesterdayDate.'%')->orderBy('id','desc')->first();
            if ($laborReportYesterday&&!$laborReportYesterday['check_out_at']){
                UserDutyCheck::query()->where('user_id',$laborReportYesterday['user_id'])->where('type','登出')->orderBy('id','desc')->delete();
                return ['result'=>true,'data'=>'该临时工还未退组，暂不可补退场卡!'];
            }
            if ($laborReportYesterday){
                $exportReport=$laborReportService->exportReplenishToCreateLaborReportData($laborReportYesterday,$userDutyCheck);
                if ($exportReport->remark) $remark=$exportReport->remark.','.$remark;
                $laborReportService->addOrUpdateRemark($remark,$exportReport->id);
                app('LogService')->log(__METHOD__,"补退场卡修改临时工报表记录__".__FUNCTION__,json_encode([$laborReportYesterday,$userDutyCheck]));
                if ($exportReport) event(new ExportEvent($exportReport));
            }
        }else if($laborReport){
            if (!$laborReport->check_out_at){
                UserDutyCheck::query()->where('user_id',$laborReport->user_id)->where('type','登出')->orderBy('id','desc')->delete();
                return ['result'=>true,'data'=>'该临时工还未退组，暂不可补退场卡!'];
            }
            $exportReport=$laborReportService->exportReplenishToCreateLaborReportData($laborReport,$userDutyCheck);
            if ($exportReport->remark) $remark=$exportReport->remark.','.$remark;
            $laborReportService->addOrUpdateRemark($remark,$exportReport->id);
            app('LogService')->log(__METHOD__,"补退场卡修改临时工报表记录__".__FUNCTION__,json_encode([$laborReport,$userDutyCheck]));
            if ($exportReport) event(new ExportEvent($exportReport));
        }
    }

    //搜索临时工下打卡信息
    public function checkUserLabors(Request $request){
        if(!Gate::allows('人事管理-录入补卡')){ return redirect(url('/'));  }
        $full_name=$request->input('full_name');
        $userDetail=UserDetail::with(['userDutyChecks'=>function ($query){
            return $query->orderBy('checked_at','DESC')->limit(5);
        }])->where('full_name',$full_name)->get();
        return ['success'=>true,'data'=>$userDetail];
    }

    //考勤
    public function createReplenishClock(){
        if(!Gate::allows('人事管理-录入补卡')){ return view('personnel/checkRelating/index');  }
        $userWorkGroups=UserWorkgroup::query()->get();
        return view('personnel/checking-in/createReplenishClock',compact('userWorkGroups'));
    }

    //打卡审核时判断是否异常
    public function isException(Request $request){
        $id=$request->input('id');
        $checked_at=$request->input('checked_at');
        $type=$request->input('type');
        $user_id=$request->input('user_id');
        if (!$id || !$checked_at || !$type || !$user_id)return ['exception'=>'数据异常！','duration_man_hour'=>''];
        $userDutyCheck=UserDutyCheck::where('user_id',$user_id)->where('checked_at','<',$checked_at)->first();
        if (!$userDutyCheck)return ['exception'=>'','duration_man_hour'=>''];
        $dateStart=Carbon::parse($userDutyCheck->checked_at);
        $dateEnd=Carbon::parse($checked_at);
        $minute=($dateEnd->diffInMinutes($dateStart));
        if ($type=="登入"&&$userDutyCheck->type=="登入"&&$minute>30){
            return ['exception'=>'无出场纪录！','duration_man_hour'=>''];
        }
        if ($type=="登出"&&$userDutyCheck->type=="登出"&&$minute>30){
            return ['exception'=>'无入场纪录！','duration_man_hour'=>''];
        }
        if ($type=="登出"&&$userDutyCheck->type=="登入"&&$minute>=720){
            return ['exception'=>'时间异常！','duration_man_hour'=>''];
        }
        if ($type=="登出"&&$userDutyCheck->type=="登入"){
            return ['exception'=>'','duration_man_hour'=>$minute/60];
        }
        return ['exception'=>'','duration_man_hour'=>''];
    }

    //打卡审核
    public function storeClockAudit(Request $request){
        if(!Gate::allows('人事管理-门卫审核')){ return ["success"=>false,"data"=>"您无此权限操作！！!"];  }
        $id=$request->input('id');
        $type=$request->input('type');
        $userDutyCheck=UserDutyCheck::find($id);
        $userDutyCheck->type=$type;
        $userDutyCheck->verify_user_id=Auth::user()['id'];
        $userDutyCheck->update();
        app('LogService')->log(__METHOD__,"打卡审核".__FUNCTION__,json_encode($userDutyCheck),Auth::user()['id']);
        return ["success"=>true,"data"=>$userDutyCheck->verify_user_id];
    }

    //打卡组长审核
    public function storeGroupAudit(Request $request){
        if(!Gate::allows('人事管理')){ return ["success"=>false,"data"=>"您无此权限操作！！!"];  }
        $id=$request->input('id');
        $userDutyCheck=UserDutyCheck::find($id);
        $workgroup=UserWorkgroup::find($userDutyCheck['workgroup_id']);
        if ($workgroup){
            if(!Gate::allows($workgroup->name)){ return ["success"=>false,"data"=>"您无此权限操作！！!"];  }
        }
        $type=$request->input('type');
        $userDutyCheck->type=$type;
        $userDutyCheck->group_user_id=Auth::user()['id'];
        $userDutyCheck->update();
//        $checkInDate=Carbon::parse($userDutyCheck->checked_at)->format('Y-m-d');where('created_at','like',$checkInDate."%")
        $laborReport=LaborReport::where('user_id',$userDutyCheck->user_id)->where('user_workgroup_id',$workgroup->id)->orderBy('id','desc')->first();
        if (!$laborReport){
            $laborReportNew=LaborReport::createLaborReportData($userDutyCheck);
            app('LogService')->log(__METHOD__,"提交临时工报表记录__".__FUNCTION__,json_encode([$userDutyCheck->user_id,$userDutyCheck->workgroup_id,$userDutyCheck]));
            //验证五分钟之内重新换组情况
            $checkInDateNow=Carbon::parse($laborReportNew->created_at)->format('Y-m-d H');
            $laborReports=LaborReport::where('user_id',$userDutyCheck->user_id)->where('created_at','like',$checkInDateNow."%")->orderBy('created_at','DESC')->limit(2)->get();
            if (count($laborReports)>1){
                $laborReportLast=LaborReport::where('user_id',$userDutyCheck->user_id)->where('created_at','like',$checkInDateNow."%")->orderBy('created_at','ASC')->limit(2)->first();
                $lastDate=Carbon::parse($laborReportLast->created_at);
                $thisDate=Carbon::parse($laborReportNew->created_at);
                $diffDate=$thisDate->diffInMinutes($lastDate);
                if ($diffDate<=5){
                    $laborReportLast->delete();
                }
            }
        }else{
            LaborReport::updateLaborReportVerify($laborReport,$userDutyCheck);
            app('LogService')->log(__METHOD__,"打卡组长审核".__FUNCTION__,json_encode($userDutyCheck),Auth::user()['id']);
        }
        event(new TeamAuditEvent($userDutyCheck));
        return ["success"=>true,"data"=>$userDutyCheck->group_user_id];
    }


    //去往任务审核
    public function missionAudit(Request $request){
        if(!Gate::allows('人事管理-任务审核')){ return redirect(url('/'));  }
        $processDailyParticipants=ProcessDailyParticipant::with(['processDaily','user_detail'=>function($builder){
            return $builder->with(['user'=>function($builder){return $builder->with(['userWorkgroups']);},'userLabor'=>function($builder){return $builder->with(['laborCompany']);}]);
        }])->orderBy('id','DESC');
        $start_date=$request->input('start_date');
        $end_date=$request->input('end_date');
        $full_name=$request->input('full_name');
        $mobile_phone=$request->input('mobile_phone');
        if ($start_date) {
            $processDailyParticipants->whereHas('processDaily',function (Builder $builder)use($start_date){
                $start_date=$start_date." 00:00:00";
                $builder->where('date','>=',$start_date);
            });
        }
        if ($end_date) {
            $processDailyParticipants->whereHas('processDaily',function (Builder $builder)use($end_date){
                $end_date=$end_date." 23:59:59";
                $builder->where('date','<=',$end_date);
            });
        }
        if ($full_name){
            $processDailyParticipants->whereHas('user_detail',function (Builder $builder)use($full_name){
                $builder->where('full_name',$full_name);
            });
        }
        if ($mobile_phone){
            $processDailyParticipants->whereHas('user_detail',function (Builder $builder)use($mobile_phone){
                $builder->where('mobile_phone',$mobile_phone);
            });
        }
        $processDailyParticipants=$processDailyParticipants->paginate($request->input('paginate')?$request->input('paginate'):50);
        foreach ($processDailyParticipants as $processDailyParticipant){
            if ($processDailyParticipant->processDaily){
                $processController=new ProcessController();
                $processDailyParticipant=$processController->countParticipantManHour($processDailyParticipant,$processDailyParticipant->processDaily->date);
            }
        }
        // 前往任务审核
        return view('personnel/checking-in/missionAudit',['processDailyParticipants'=>$processDailyParticipants,'request'=>$request->input()]);
    }

    //去往打卡审核
    public function clockAudit(){
        if(!Gate::allows('人事管理')){ return redirect(url('/'));  }
        $user=Auth::user();
        if (!$user)return redirect('/');
        $userWorkgroupIds=$user->getPermittingWorkgroupIds();
//        $users=User::whereHas("userWorkgroups",function (Builder $query)use(&$userWorkgroupIds){
//            $query->whereIn("id",$userWorkgroupIds);
//        })->get();
        $permittingWorkgroups=UserWorkgroup::whereIn('id',$userWorkgroupIds)->get();
        if($permittingWorkgroups->isEmpty())$permittingWorkgroups="[]";

//        $user_ids=array_column($users->toArray(),'id');
        $dateNow=Carbon::now()->addDays(1)->format('Y-m-d');
        $beforeYesterdayDate=Carbon::now()->addDays(-2)->format('Y-m-d');
        $userDutyChecks=UserDutyCheck::with(['userWorkgroup','userLabor.laborCompany','userDetail'])->whereIn("workgroup_id",$userWorkgroupIds)
            ->whereBetween('checked_at',[$beforeYesterdayDate,$dateNow])->orderBy('checked_at','DESC')->get();
        $laravelEchoPrefix = config('database.redis.options.prefix');
        return view('personnel/checking-in/clockAudit',['userDutyChecks'=>$userDutyChecks,'laravelEchoPrefix'=>$laravelEchoPrefix,'permittingWorkgroups'=>$permittingWorkgroups]);
    }

    public function validatorUserDutyCheck(Request $request){
        $validator=Validator::make($request->input(),[
            'user_id'=>'required',
            'checked_at'=>'required|date_format:Y-m-d H:i',
            'type'=>'required',
        ],[
            'date_format'=>':attribute 格式错误',
        ],['checked_at'=>'日期'
            ,'type'=>'补卡类型']);
        return $validator;
    }
    //打卡审核类型
    public function updateDutyCheckType(Request $request){
        if(!Gate::allows('人事管理-审核类型')){return ['success'=>'false','fail_info'=>'没有权限'];}
        $userDutyCheckId=$request->input('id');
        $userDutyCheckType=$request->input('type');
        if (is_null($userDutyCheckId) or is_null($userDutyCheckType)){
            return ['success'=>false,'fail_info'=>'传参错误'];
        }
        $userDutyCheck=UserDutyCheck::find($userDutyCheckId);
        $userDutyCheck->type=$userDutyCheckType;
        $userDutyCheck->update();
        $laborReport=LaborReport::where('user_workgroup_id',$userDutyCheck->workgroup_id)->where('user_id',$userDutyCheck->user_id)->orderBy('id','desc')->first();
        if ($laborReport&&$userDutyCheck->type){
            LaborReport::updateLaborReportData($laborReport,$userDutyCheck);
            app('LogService')->log(__METHOD__,"更新临时工报表记录__".__FUNCTION__,json_encode([$laborReport,$userDutyCheck]));
        }
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>true,'data'=>$userDutyCheck];
    }

    //任务审核
    public function storeMissionAudit(Request $request){
        if(!Gate::allows('人事管理-任务审核')){ return redirect(url('/'));  }
        $id=$request->input('id');
        if (!$id)return ['error'=>'提交审核失败！'];
        $processDailyParticipant=ProcessDailyParticipant::find($id);
        if (!$id)return ['error'=>'未找到对应记录！'];
        $processDailyParticipant->status='已审核';
        $processDailyParticipant->update();
        app('LogService')->log(__METHOD__,"任务审核".__FUNCTION__,json_encode($processDailyParticipant),Auth::user()['id']);
        return;
    }
}
