<?php

namespace App\Http\Controllers;

use App\Events\ClockoutEvent;
use App\Events\GuardAuditEvent;
use App\Events\TeamAuditEvent;
use App\Exports\Export;
use App\LaborReport;
use App\LaborReportStatus;
use App\Services\LaborReportService;
use App\UserDutyCheck;
use App\UserWorkgroup;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Maatwebsite\Excel\Facades\Excel;

class LaborReportController extends Controller
{
    public function __construct()
    {
        app()->singleton('laborReportService',LaborReportService::class);
    }
    /**
     * Display a listing of the resource.
     * @param  Request $request
     * @return void
     * 临时工报表
     */
    public function index(Request $request)
    {
        if(!Gate::allows('人事管理-临时工报表')){ return redirect(url('/'));  }
        $paginateParams=$request->input();
        $user=Auth::user();
        if (!$user)return redirect('/');
        $laravelEchoPrefix = config('database.redis.options.prefix');
        $tokenOfBroadcastEnterAndLeave='';
        if(Gate::allows('人事管理-临时工报表-可见全部组')||Gate::allows('人事管理-门卫审核')){
            $tokenOfBroadcastEnterAndLeave=LaborReport::tokenOfBroadcastEnterAndLeave();
        }
        $userWorkgroupIds=$user->getPermittingWorkgroupIds(Gate::allows('人事管理-临时工报表-可见全部组'));
        $permittingWorkgroups=UserWorkgroup::whereIn('id',$userWorkgroupIds)->get();
        if($permittingWorkgroups->isEmpty())$permittingWorkgroups="[]";
        $laborReports=app('laborReportService')->paginate($request);
//        $laborReports=$laborReports->sortBy('name');按名字排序
        foreach ($laborReports as $laborReport){
            if (!$laborReport->group_user_id){
                //2小时之内组长未审核实行软删除
                $tenMinutesLater=Carbon::parse($laborReport->created_at)->subHours(-2)->format('Y-m-d H:i:s');
                if (Carbon::now()->format('Y-m-d H:i:s')>$tenMinutesLater){
                    $laborReport->delete();
                    $this->log(__METHOD__,"组长未审核该条记录将在10分钟后实行软删除__".__FUNCTION__,$laborReport->toJson(),Auth::user()['id']);
                }
            }
            $addOneHourCheckedAt=Carbon::parse($laborReport->userDutyCheck['checked_at'])->subHours(-1)->format('Y-m-d H:i:s');
            if (!$laborReport->userDutyCheck['verify_user_id']&&Carbon::now()->format('Y-m-d H:i:s')>$addOneHourCheckedAt){
                $laborReport->delete();
                $this->log(__METHOD__,"进场门卫未审核该条记录将在一小时后实行软删除__".__FUNCTION__,$laborReport->toJson(),Auth::user()['id']);
            }
        }
        $userWorkGroups=UserWorkgroup::select('id','name')->get();
        return view('personnel/laborReport/index',compact('laborReports','userWorkGroups','laravelEchoPrefix','permittingWorkgroups','paginateParams','tokenOfBroadcastEnterAndLeave'));
    }
    public function export(Request $request){
        if (!Gate::allows('人事管理-临时工报表')){return redirect(url('/')); }
        ini_set('max_execution_time',3500);
        ini_set('memory_limit','3526M');
        if ($request->checkAllSign){
            $request->offsetUnset('checkAllSign');
            $laborReports=app('laborReportService')->get($request);
        }else{
            $laborReports=app('laborReportService')->some($request);
        }
        $row=[[
            'id'=>'ID',
            'enter_number'=>'进厂编号',
            'user_workgroup_name'=>'小组',
            'name'=>'临时工',
            'mobile_phone'=>'电话',
            'identity_number'=>'身份证号',
            'labor_company'=>'劳务所',
            'enter_at'=>'进场时间',
            'check_in_at'=>'进组时间',
            'check_out_at'=>'退组时间',
            'exit_at'=>'退场时间',
            'verify_at'=>'审核时间',
            'group_user_id'=>'审核人',
            'relax_time'=>'晚饭时间(分)',
            'online_duration'=>'在线时长',
            'working_duration'=>'本次工作时长',
            'remark'=>'备注',
        ]];
        $list=[];
        for ($i=0; $i<count($laborReports);$i++){
            $laborReport=$laborReports[$i];
            $w=[
                'id'=>isset($laborReport->id)?$laborReport->id:'',
                'enter_number'=>isset($laborReport->enter_number)?$laborReport->enter_number:'',
                'user_workgroup_name'=>isset($laborReport->userWorkgroup->name)?$laborReport->userWorkgroup->name:'',
                'name'=>isset($laborReport->name)?$laborReport->name:'',
                'mobile_phone'=>isset($laborReport->mobile_phone)?$laborReport->mobile_phone:'',
                'identity_number'=>isset($laborReport->identity_number)?$laborReport->identity_number:'',
                'labor_company'=>isset($laborReport->labor_company)?$laborReport->labor_company:'',
                'enter_at'=>isset($laborReport->enter_at)?$laborReport->enter_at:'',
                'check_in_at'=>isset($laborReport->check_in_at)?$laborReport->check_in_at:'',
                'check_out_at'=>isset($laborReport->check_out_at)?$laborReport->check_out_at:'',
                'exit_at'=>isset($laborReport->exit_at)?$laborReport->exit_at:'',
                'verify_at'=>isset($laborReport->verify_at)?$laborReport->verify_at:'',
                'group_user_id'=>isset($laborReport->user->name)?$laborReport->user->name:'',
                'relax_time'=>isset($laborReport->relax_time)?$laborReport->relax_time:'',
                'online_duration'=>isset($laborReport->online_duration)?$laborReport->online_duration:'',
                'working_duration'=>isset($laborReport->working_duration)?$laborReport->working_duration:'',
                'remark'=>isset($laborReport->remark)?$laborReport->remark:'',
            ];
            $list[$i]=$w;
        }
        return Excel::download(new Export($row,$list),date('YmdHis', time()).'-临时工报表记录单.xlsx');
    }

    //门卫打卡审核
    public function guardClockAudit(Request $request){
        if(!Gate::allows('人事管理-门卫审核')){ return ["success"=>false,"data"=>"您无此权限操作！！!"];  }
        $id=$request->input('id');
        $userDutyCheckId=$request->input('user_duty_check_id');
        $laborReportStatus=new LaborReportStatus([
            'labor_report_id'=>$id,
            'status'=>'已入场',
        ]);
        $laborReportStatus->save();
        $this->log(__METHOD__,"门卫打卡审核创建当前临时工报表状态".__FUNCTION__,json_encode($laborReportStatus),Auth::user()['id']);
        $userDutyCheck=UserDutyCheck::find($userDutyCheckId);
        $userDutyCheck->verify_user_id=Auth::user()['id'];
        $userDutyCheck->update();
        event(new GuardAuditEvent($userDutyCheck));
        $this->log(__METHOD__,"门卫打卡审核".__FUNCTION__,json_encode($userDutyCheck),Auth::user()['id']);
        return ["success"=>true,"data"=>$userDutyCheck->verify_user_id];
    }
    //打卡组长审核
    public function groupClockAudit(Request $request){
        if(!Gate::allows('人事管理-组长审核')){ return ["success"=>false,"data"=>"您无此权限操作!"];  }
        $id=$request->input('id');
        $laborReport=LaborReport::find($id);
        $laborReport->group_user_id=Auth::user()['id'];
        $laborReport->verify_at=date('Y-m-d H:i:s');
        $laborReport->update();
        $laborReport->verifyPerson=Auth::user()['name'];
        $this->log(__METHOD__,"打卡组长审核".__FUNCTION__,json_encode($laborReport),Auth::user()['id']);
        event(new TeamAuditEvent($laborReport));
        return ["success"=>true,"data"=>$laborReport];
    }
    //打卡组长审核(特定组添加备注)
    public function addRemarkAndGroupClock(Request $request){
        if(!Gate::allows('人事管理-组长审核')){ return ["success"=>false,"data"=>"您无此权限操作!"];  }
        $id=$request->input('id');
        $remark=$request->input('remark');
        if(!$remark){ return ["success"=>false,"data"=>"您还未添加任何备注,请返回添加备注！"];  }
        $laborReport=LaborReport::find($id);
        $laborReport->group_user_id=Auth::user()['id'];
        $laborReport->verify_at=date('Y-m-d H:i:s');
        $laborReport->update();
        $laborReport->setRemarkAttribute($remark,$id);
        $laborReport->verifyPerson=Auth::user()['name'];
        $this->log(__METHOD__,"打卡组长审核并添加相应备注".__FUNCTION__,json_encode($laborReport),Auth::user()['id']);
        event(new TeamAuditEvent($laborReport));
        return ["success"=>true,"data"=>$laborReport];
    }

    //组长点击退组
    public function groupExport(Request $request){
        if(!Gate::allows('人事管理-组长审核')){ return ["success"=>false,"data"=>"您无此权限操作！"];  }
        $id=$request->input('id');
        $laborReport=LaborReport::find($id);
        $laborReportStatus=new LaborReportStatus([
            'labor_report_id'=>$id,
            'status'=>'已退组',
        ]);
        $laborReportStatus->save();
        $this->log(__METHOD__,"报表记录退组对应状态".__FUNCTION__,json_encode($laborReportStatus),Auth::user()['id']);
        $check_out_at=Carbon::now()->format('Y-m-d H:i:s');
        $check_in_at=$laborReport->check_in_at;
        $laborReport->check_out_at=$check_out_at;
        $online_duration=round(Carbon::parse($check_out_at)->diffInSeconds(Carbon::parse($check_in_at))/3600,2);
        $laborReport->working_duration=$this->minusLunchTime($laborReport,$online_duration);
        if ($laborReport['enter_at']){
            $enter_at=$laborReport['enter_at'];
            $laborReport->online_duration=round(Carbon::parse($check_out_at)->diffInSeconds(Carbon::parse($enter_at))/3600,2);
        }else{
            $laborReport->online_duration=$online_duration;
        }
        $laborReport->update();
        $laborReport->is_exportGroup=$laborReport->getIsExportGroupAttribute();
        $this->log(__METHOD__,"退组".__FUNCTION__,json_encode($laborReport),Auth::user()['id']);
        event(new ClockoutEvent($laborReport));
        return ["success"=>true,"data"=>$laborReport];
    }

    //晚19点后组长点击退场，判断是否有晚餐情况
    public function groupExportEnsure(Request $request){
        if(!Gate::allows('人事管理-组长审核')){ return ["success"=>false,"data"=>"您无此权限操作！"];  }
        $id=$request->input('id');
        $relax_time=$request->input('relax_time');
        if(!$relax_time){ return ["success"=>false,"data"=>"未选择确切晚饭时间,请重新选择!"];  }
        $laborReport=LaborReport::find($id);
        $laborReportStatus=new LaborReportStatus([
            'labor_report_id'=>$id,
            'status'=>'已退组',
        ]);
        $laborReportStatus->save();
        $this->log(__METHOD__,"报表记录退组对应状态".__FUNCTION__,json_encode($laborReportStatus),Auth::user()['id']);
        $check_out_at=Carbon::now()->format('Y-m-d H:i:s');
        $check_in_at=$laborReport->check_in_at;
        $laborReport->check_out_at=$check_out_at;
        $online_duration=round(Carbon::parse($check_out_at)->diffInSeconds(Carbon::parse($check_in_at))/3600,2);
        if ($relax_time){
            $laborReport->relax_time=$relax_time;
            $laborReport->working_duration=$this->minusLunchTime($laborReport,$online_duration)-$relax_time/60;//减去晚饭时间
        }else{
            $laborReport->working_duration=$this->minusLunchTime($laborReport,$online_duration);
        }
        if ($laborReport->enter_at){
            $enter_at=$laborReport['enter_at'];
            $laborReport->online_duration=round(Carbon::parse($check_out_at)->diffInSeconds(Carbon::parse($enter_at))/3600,2);
        }else{
            $laborReport->online_duration=$online_duration;
        }
        $laborReport->update();
        $laborReport->is_exportGroup=$laborReport->getIsExportGroupAttribute();
        $this->log(__METHOD__,"退组".__FUNCTION__,json_encode($laborReport),Auth::user()['id']);
        event(new ClockoutEvent($laborReport));
        return ["success"=>true,"data"=>$laborReport];
    }

    //工作时长减午饭休息时间
    public function minusLunchTime($laborReport,$hour){
        $checkInTime=$laborReport->check_in_at;
        $checkOutTime=$laborReport->check_out_at;
        $checkOutTime=Carbon::parse($checkOutTime)->format('H');
        $checkInTime=Carbon::parse($checkInTime)->format('H');
        if ((int)$checkInTime<=12&&(int)$checkOutTime>=13){
            $hour=$hour-1;
        }
        return $hour;
    }
}
