<?php


namespace App\Services;


use App\Events\ExportEvent;
use App\Events\ImportEvent;
use App\Http\Controllers\Controller;
use App\LaborReportStatus;
use App\LaborCompany;
use App\LaborReport;
use App\Services\common\QueryService;
use App\UserDetail;
use App\UserDutyCheck;
use App\UserLabor;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;


class LaborReportService
{
    private function conditionQuery(Request $request){
        $user=Auth::user();
        $laborReports=LaborReport::query()->with(['user','userDutyCheck','userWorkgroup'])->orderBy('id','DESC')->whereIn('user_workgroup_id',
            $user?$user->getPermittingWorkgroupIds(Gate::allows('人事管理-临时工报表-可见全部组')):[]);
        $laborStatus=LaborReportStatus::select('labor_report_id')->where('status','已退场')->get();
        $enterNumbers=[];
        foreach ($laborStatus as $laborId){
            $enterNumber=LaborReport::where('id',$laborId['labor_report_id'])->value('enter_number');
            if($enterNumber!=null)
            array_push($enterNumbers,$enterNumber);
        }
        if (!$request->is_export){
            $laborReports->whereNotIn('enter_number',$enterNumbers);
        }else $request->offsetUnset('is_export');
        $columnQueryRules=[
            'enter_number' => ['timeLimit' => 15],
            'created_at_start' => ['alias' => 'created_at' , 'startDate' => ' 00:00:00'],
            'created_at_end' => ['alias' => 'created_at' , 'endDate' => ' 23:59:59'],
            'identity_number' => ['timeLimit' => 15]
        ];
        $laborReports = app(QueryService::class)->query($request,$laborReports,$columnQueryRules);
        if(Gate::allows('人事管理-临时工报表-可见全部组')||Gate::allows('人事管理-门卫审核')){
            $laborReports->orWhereNull('user_workgroup_id');
        }
        return $laborReports;
    }
    public function paginate(Request $request){
        return $this->conditionQuery($request)->paginate($request->paginate ?? 50);
    }
    public function get(Request $request){
        return $this->conditionQuery($request)->get();
    }
    public function some(Request $request){
        return LaborReport::query()->orderBy('id','DESC')
                        ->whereIn('id',explode(',',$request->data))->get();
    }
    //根据进场记录创建临时工报表
    public function makeLaborReportByUserDutyCheck($userDutyCheck){
        $dateNow=Carbon::now()->format('Y-m-d');
        $laborReport=LaborReport::where('user_id',$userDutyCheck->user_id)->where('created_at','like',$dateNow.'%')->orderBy('id','desc')->first();
        if (!$laborReport){
            $newReport=$userDutyCheck->makeEnteringRecord();
            Controller::logS(__METHOD__,"进场创建临时工报表记录__".__FUNCTION__,json_encode([$userDutyCheck]));
            if ($newReport){
                event(new ImportEvent($newReport));
            }
        }
    }
    //根据进出场打卡记录 创建或者更新临时工报表记录
    public function makeOrChangeLaborReportByUserDutyCheck($userDutyCheck,$importAndExportQRCodeType){
        $dateNow=Carbon::now()->format('Y-m-d');
        $laborReport=LaborReport::where('user_id',$userDutyCheck->user_id)->where('created_at','like',$dateNow.'%')->orderBy('id','desc')->first();
        //判断当前日期下临时工是否有临时工报表记录并且是进场打卡
        if ($userDutyCheck->type=='登入'&&$importAndExportQRCodeType=='import'){
            $newReport=$userDutyCheck->makeEnteringRecord();
            Controller::logS(__METHOD__,"进场创建临时工报表记录__".__FUNCTION__,json_encode([$userDutyCheck]));
            if ($newReport) event(new ImportEvent($newReport));
        }
        if(!$laborReport&&$importAndExportQRCodeType=='export'){
            //退场时间跨天情况
            $yesterdayDate=Carbon::now()->subDays(1)->format('Y-m-d');
            $laborReportYesterday=LaborReport::where('user_id',$userDutyCheck->user_id)->where('created_at','like',$yesterdayDate.'%')->orderBy('id','desc')->first();
            if (!$laborReportYesterday->check_out_at&&$laborReportYesterday['user_workgroup_id']){
                UserDutyCheck::where('user_id',$laborReportYesterday->user_id)->where('type','登出')->where('checked_at','like',Carbon::now()->format('Y-m-d H:i').'%')->orderBy('id','desc')->delete();
                return "<h1 style='color: darkred;text-align:center'>您还未退组，暂不可退场，请联系组长!</h1>";
            }
                $exportReport=LaborReport::exitAndChangeLaborReport($laborReportYesterday,$userDutyCheck);
                Controller::logS(__METHOD__,"退场更改临时工报表信息__".__FUNCTION__,json_encode([$laborReportYesterday,$userDutyCheck]));
                if ($exportReport) event(new ExportEvent($exportReport));
        }
        if($laborReport&&$importAndExportQRCodeType=='export'){
            if (!$laborReport['check_out_at']&&$laborReport['user_workgroup_id']){
                UserDutyCheck::where('user_id',$laborReport->user_id)->where('type','登出')->where('checked_at','like',Carbon::now()->format('Y-m-d H:i').'%')->orderBy('id','desc')->delete();
                return "<h1 style='color: darkred;text-align:center'>您还未退组，暂不可退场，请联系组长!</h1>";
            }
            $exportReport=LaborReport::exitAndChangeLaborReport($laborReport,$userDutyCheck);
            Controller::logS(__METHOD__,"退场更改临时工报表信息__".__FUNCTION__,json_encode([$laborReport,$userDutyCheck]));
            if ($exportReport) event(new ExportEvent($exportReport));
        }
    }

    //补卡出场更新临时工报表信息
    public function exportReplenishToCreateLaborReportData($laborReport,$userDutyCheck){
        $laborReportStatus=new LaborReportStatus([
            'labor_report_id'=>$laborReport['id'],
            'status'=>'已退场',
            'created_at'=>$userDutyCheck['checked_at'],
        ]);
        $laborReportStatus->save();
        $check_in_at=$laborReport->check_in_at;
        $exit_at=$userDutyCheck->checked_at;
        $online_duration=round(Carbon::parse($exit_at)->diffInSeconds(Carbon::parse($check_in_at))/3600,2);
        $laborReport->user_duty_check_id=$userDutyCheck->id;
        if ($laborReport->enter_at){
            $enter_at=$laborReport['enter_at'];
            $laborReport->online_duration=round(Carbon::parse($exit_at)->diffInSeconds(Carbon::parse($enter_at))/3600,2);
        }else{
            $laborReport->online_duration=$online_duration;
        }
        $laborReport->update();
        $laborReport->is_export=$laborReport->getIsExportAttribute();
        return $laborReport;
    }
    //当天第一次进工作组更新临时工报表
    public function enterGroupAndUpdateLaborReport($laborReport,$userWorkgroupID){
        $laborReport->user_workgroup_id=$userWorkgroupID;
        $laborReport->check_in_at=date('Y-m-d H:i:s');
        $laborReport->update();
        return $laborReport;
    }

    //换组添加临时工报表数据
    public function changeGroupAndMakeLaborReport($user_id,$userWorkgroupID){
        $laborReportBefore=LaborReport::where('user_id',$user_id)->orderby('id','desc')->first();
        if ($laborReportBefore&&$laborReportBefore['status']!='已退场')$userDutyCheck=$laborReportBefore->userDutyCheck;
        if ($laborReportBefore&&!$laborReportBefore['group_user_id']){
            if ($laborReportBefore['user_workgroup_id']!=$userWorkgroupID){
                $laborReportBefore['user_workgroup_id']=$userWorkgroupID;
                $laborReportBefore['check_in_at']=Carbon::now()->format('Y-m-d H:i:s');
                $laborReportBefore->update();
                return $laborReportBefore;
            }
        }
        $userDetail=UserDetail::find($user_id);
        $name=$userDetail['full_name'];
        $mobile_phone=$userDetail['mobile_phone'];
        $identity_number=$userDetail['identity_number'];
        $labor_company_id=UserLabor::where('user_id',$user_id)->value('labor_company_id');
        $labor_company=LaborCompany::where('id',$labor_company_id)->value('name');
        $laborReport=new LaborReport([
            'user_workgroup_id'=>$userWorkgroupID,
            'user_id'=>$user_id,
            'name'=>$name,
            'mobile_phone'=>$mobile_phone,
            'identity_number'=>$identity_number,
            'labor_company'=>$labor_company,
            'check_in_at'=>date('Y-m-d H:i:s'),
            'user_duty_check_id'=>$userDutyCheck->id,
        ]);
        $laborReport['enter_number']=$laborReport->makeOrGetEnteringNumber();
        $laborReport->save();
        $laborReportStatus=new LaborReportStatus([
            'labor_report_id'=>$laborReport['id'],
            'status'=>'已换组',
        ]);
        $laborReportStatus->save();
        return $laborReport;
    }

}
