<?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\User;
use App\UserDetail;
use App\UserDutyCheck;
use App\UserLabor;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

use App\Traits\ServiceAppAop;


class LaborReportService
{
    use ServiceAppAop;
    protected $modelClass=LaborReport::class;
    private function conditionQuery(array $params){
        $user=Auth::user();
        $laborReports=LaborReport::query()
            ->with(['user','userDutyCheck','userWorkgroup.signs','laborCompany','laborReportStatus','laborReports'])->orderBy('labor_reports.id','DESC');
        if (!($params["is_export"] ?? false)&&!($params['id']??null)){
            $laborReports = $laborReports->whereNotIn('labor_reports.enter_number',function ($builder)use($params){
                $builder->select('enter_number')->from('labor_reports')
                    ->leftJoin('labor_report_statuses','labor_reports.id','labor_report_statuses.labor_report_id')
                    ->where('labor_report_statuses.status','已退场');
            });
        }else unset($params['is_export']);
        $columnQueryRules=[
            'enter_number' => ['batch'=>'','timeLimit' => 15],
            'created_at_start' => ['alias' => 'created_at' , 'startDate' => ' 00:00:00'],
            'created_at_end' => ['alias' => 'created_at' , 'endDate' => ' 23:59:59'],
            'identity_number' => ['batch'=>'','timeLimit' => 15],
            'name' => ['batch' => ''],
            'mobile_phone' => ['batch' => ''],
            'user_workgroup_id' => ['multi' => ','],
            'labor_company_id' => ['multi' => ','],
            'id' => ['multi' => ',']
        ];
        $laborReports = app(QueryService::class)->query($params,$laborReports,$columnQueryRules,'labor_reports');
        if((Gate::allows('人事管理-临时工报表-可见全部组')||Gate::allows('人事管理-门卫审核')) && !($params["user_workgroup_id"] ?? false)){
            $laborReports->where(function ($query)use($user){
                $query->whereIn('labor_reports.user_workgroup_id',$user?$user->getPermittingWorkgroupIds(Gate::allows('人事管理-临时工报表-可见全部组')):[])
                    ->orWhereNull('labor_reports.user_workgroup_id');
            });
        }else{
            $laborReports->whereIn('labor_reports.user_workgroup_id',
                $user?$user->getPermittingWorkgroupIds(Gate::allows('人事管理-临时工报表-可见全部组')):[]);
        }
        $laborReports = app(QueryService::class)->query($params,$laborReports,$columnQueryRules,'labor_reports');
        return $laborReports;
    }
    public function paginate(array $params){
        return $this->conditionQuery($params)->paginate($params['paginate'] ?? 50);
    }
    public function get(array $params){
        return $this->conditionQuery($params)->without("userDutyCheck")->get();
    }

    public function getSql(array $params){
        return $this->conditionQuery($params)->selectRaw("labor_reports.*")
            ->leftJoin('user_workgroups','labor_reports.user_workgroup_id','user_workgroups.id')
            ->selectRaw('user_workgroups.name user_workgroup_name')
            ->leftJoin('labor_companies','labor_reports.labor_company_id','labor_companies.id')
            ->selectRaw('labor_companies.name labor_company')
            ->sql();
    }

    //根据进场记录创建临时工报表
    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::query()->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::query()->where('user_id',$userDutyCheck->user_id)->where('created_at','like',$yesterdayDate.'%')->orderBy('id','desc')->first();
            if ($laborReportYesterday){
                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=true;
        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');
        $laborReport=new LaborReport([
            'user_workgroup_id'=>$userWorkgroupID,
            'user_id'=>$user_id,
            'name'=>$name,
            'mobile_phone'=>$mobile_phone,
            'identity_number'=>$identity_number,
            'labor_company_id'=>$labor_company_id,
            '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;
    }
    public function 修改劳务所($param){
        $laborReports=LaborReport::query()->where('enter_number',$param['enter_number'])->get();
        foreach($laborReports as $laborReport){
            $laborReport->labor_company_id=$param['laborCompanyId'];
            $laborReport->update();
        }
        Controller::logS(__METHOD__,'修改临时工报表劳务所'.__FUNCTION__,json_encode($param));
    }
    public function 删除($id){
        $laborReport=LaborReport::query()->where('id',$id)->delete();
        if ($laborReport>0)LaborReportStatus::create([
            'labor_report_id'=>$id,
            'status'=>'已删除',
        ]);
        Controller::logS(__METHOD__,'删除盘点记录时修改盘点任务信息'.__FUNCTION__,json_encode($id));
        return $laborReport;
    }

    public function addOrUpdateRemark($remark,$id){
        return LaborReport::query()->updateOrCreate(['id'=>$id],['remark'=>$remark]);
    }

}
