<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use App\Traits\ModelTimeFormat;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;

class LaborReport extends Model
{
    use ModelTimeFormat;
    use SoftDeletes;
    protected $fillable=[
        'id','enter_number','user_workgroup_id','user_id','name','mobile_phone','identity_number','labor_company',
        'check_in_at','verify_at','group_user_id','check_out_at','online_duration','working_duration','created_at','updated_at',
        'user_duty_check_id','relax_time'
    ];
    protected $appends = [
        'is_exportGroup','is_export', 'exit_at','enter_at','sequence', 'amountOfJoined','remark','thisRecordOnlineTime','thisRecordWorkingTime',
        'totalOnlineTime','verifyPerson','userDutyCheckVerifyUserId',
    ];
    protected $tempFields = [
        'temEnteringRecord',
        'sequence',
        'amountOfJoined',
    ];

    static function tokenOfBroadcastEnterAndLeave(){
        return md5('tokenOfListAll'.Carbon::now()->format('Y-m-d'));
    }
    public function userWorkgroup(){
        return $this->belongsTo('App\UserWorkgroup','user_workgroup_id','id');
    }
    public function user(){
        return $this->belongsTo('App\User','group_user_id','id');
    }
    public function userDutyCheck(){
        return $this->belongsTo('App\UserDutyCheck','user_duty_check_id','id');
    }
    public function laborReportStatus(){
        return $this->belongsTo('App\LaborReportStatus','id','labor_report_id');
    }
    public function getRemarkAttribute(){
        return $this->hasOne('App\Sign','signable_id','id')
            ->where('field','remark')->where('signable_type','labor_reports')->value('mark');
    }
    public function setRemarkAttribute($remark,$id){
        Sign::updateOrCreate(['signable_type'=>'labor_reports','signable_id'=>$id,'field'=>'remark'],['mark'=>$remark]);

    }
    public function getIsExportGroupAttribute(){
        return $this['check_out_at']? true:false;
    }

    public function getVerifyPersonAttribute(){
        if ($this['group_user_id']&&$this['group_user_id']==Auth::user()['id'])
        return Auth::user()['name'];
    }
    public function getUserDutyCheckVerifyUserIdAttribute(){
        return $this['userDutyCheck']['verify_user_id']?$this['userDutyCheck']['verify_user_id']:'';
    }
    //总在线时长
    public function getTotalOnlineTimeAttribute(){
        $laborReports=LaborReport::where('enter_number',$this['enter_number'])->get();
        $totalOnlineTime=$laborReports->reduce(function ($value,$laborReport){
            return ($value??0)+$laborReport['thisRecordOnlineTime'];
        });
        return $totalOnlineTime;
    }
    //总工作时长
    public function getTotalWorkingTimeAttribute(){
        $laborReports=LaborReport::where('enter_number',$this['enter_number'])->orderBy('id','asc')->get();
        $totalWorkingTime=$laborReports->reduce(function ($value,$laborReport){
            return ($value??0)+$laborReport['thisRecordWorkingTime'];
        });
        return $totalWorkingTime;
    }
    //本轮工作起始时间
    public function getThisRoundOnlineStartTimeAttribute(){
        $laborReports=LaborReport::where('enter_number',$this['enter_number'])->orderBy('id','asc')->get();
        foreach ($laborReports as $laborReport){
            if ($laborReport['enter_at']&&$laborReport['check_in_at'])
                return $laborReport['check_in_at'];
        }
    }
    //本轮工作结束时间
    public function getThisRoundOnlineEndTimeAttribute(){
        $laborReports=LaborReport::where('enter_number',$this['enter_number'])->get();
//        $maxId=$laborReports->max('id');
        foreach ($laborReports as $laborReport){
//            if ($laborReport['id']==$maxId&&!$laborReport['exit_at']&&$laborReport['check_out_at']){
//                return $laborReport['check_out_at'];
//            }
            if ($laborReport['exit_at']&&$laborReport['check_out_at'])
                return $laborReport['check_out_at'];
        }
    }
    //本次在线时长
    public function getThisRecordOnlineTimeAttribute(){
        if($this['enter_at']&&!$this['check_out_at']&&!$this['exit_at'])
            return round(Carbon::parse(Carbon::now())->diffInSeconds(Carbon::parse($this['enter_at']))/3600,2);
        if ($this['enter_at']&&$this['check_out_at']&&!$this['exit_at'])
            return round(Carbon::parse($this['check_out_at'])->diffInSeconds(Carbon::parse($this['enter_at']))/3600,2);
        if ($this['enter_at']&&$this['exit_at'])
            return round(Carbon::parse($this['exit_at'])->diffInSeconds(Carbon::parse($this['enter_at']))/3600,2);
        if ($this['check_in_at']&&!$this['enter_at']&&!$this['check_out_at']&&!$this['exit_at'])
            return round(Carbon::parse(Carbon::now())->diffInSeconds(Carbon::parse($this['check_in_at']))/3600,2);
        if ($this['check_in_at']&&!$this['enter_at']&&$this['check_out_at']&&!$this['exit_at'])
            return round(Carbon::parse($this['check_out_at'])->diffInSeconds(Carbon::parse($this['check_in_at']))/3600,2);
        if ($this['check_in_at']&&!$this['enter_at']&&$this['exit_at'])
            return round(Carbon::parse($this['exit_at'])->diffInSeconds(Carbon::parse($this['check_in_at']))/3600,2);
    }
    //本次工作时长
    public function getThisRecordWorkingTimeAttribute(){
        if ($this['check_in_at']&&!$this['check_out_at']&&!$this['relax_time']){
            $workingTime=round(Carbon::parse(Carbon::now())->diffInSeconds(Carbon::parse($this['check_in_at']))/3600,2);
            $checkInTime=Carbon::parse($this['check_in_at'])->format('H');
            $checkOutTime=Carbon::parse(Carbon::now())->format('H');
            return  $this->minusLunchTime($checkInTime,$checkOutTime,$workingTime);
        }
        if ($this['check_in_at']&&$this['check_out_at']&&!$this['relax_time']){
            $workingTime=round(Carbon::parse($this['check_out_at'])->diffInSeconds(Carbon::parse($this['check_in_at']))/3600,2);
            $checkInTime=Carbon::parse($this['check_in_at'])->format('H');
            $checkOutTime=Carbon::parse($this['check_out_at'])->format('H');
            return  $this->minusLunchTime($checkInTime,$checkOutTime,$workingTime);
        }
        if ($this['check_in_at']&&$this['check_out_at']&&$this['relax_time']){
            $workingTime=round(Carbon::parse($this['check_out_at'])->diffInSeconds(Carbon::parse($this['check_in_at']))/3600,2);
            $checkInTime=Carbon::parse($this['check_in_at'])->format('H');
            $checkOutTime=Carbon::parse($this['check_out_at'])->format('H');
            return  $this->minusLunchTime($checkInTime,$checkOutTime,$workingTime)-$this['relax_time']/60;
        }
    }

    //工作时长减午饭休息时间
    public function minusLunchTime($checkInTime,$checkOutTime,$hour){
        if ((int)$checkInTime<=12&&(int)$checkOutTime>=13){
            $hour=$hour-1;
        }
        return $hour;
    }

    //转场序号
    public function getSequenceAttribute()
    {
        if(Arr::has($this->tempFields,'sequence'))return $this->tempFields['sequence'];
        $laborReports=LaborReport::where('enter_number',$this['enter_number'])->orderBy('id','asc')->get();
        foreach($laborReports as $i=>$laborReport){
            if($laborReport['id']==$this['id']){
                $this->tempFields['sequence']=$i+1;
                return $this->tempFields['sequence'];
            }
        }
    }
    public function getAmountOfJoinedAttribute()
    {
        if(Arr::has($this->tempFields,'amountOfJoined'))return $this->tempFields['amountOfJoined'];
        $this->tempFields['amountOfJoined']=LaborReport::where('enter_number',$this['enter_number'])->orderBy('id','asc')->count();
        return $this->tempFields['amountOfJoined'];
    }

    //进场时间
    public function getEnterAtAttribute()
    {
//        if(!$this['enteringRecord'])return null;
//        return $this['enteringRecord']->userDutyCheck['checked_at'];
        $laborReportStatus=LaborReportStatus::where('labor_report_id',$this['id'])->where('status','未审核')->orderBy('id','desc')->first();
        if (empty($laborReportStatus))return null;
        return Carbon::parse($laborReportStatus['created_at'])->format('Y-m-d H:i:s');
    }

    public function getEnteringRecordAttribute()
    {
//        if($this['temEnteringRecord'])return $this['temEnteringRecord'];
//        if($this->laborReportStatus['status']=='已入场'||$this->laborReportStatus['status']=='未审核')
//        {
//            $laborReport=$this;
//            if(empty($laborReport))
//                $laborReport=LaborReport::with(['laborReportStatus'=>function($query){
//                    return $query->whereIn('status',['已入场','未审核']);
//                }])->whereNotNull('deleted_at')->where('enter_number',$this['enter_number'])->first();
//            if(empty($laborReport)){
//                if(!$this['enter_number']){
//                    $laborReport=LaborReport::with(['laborReportStatus'=>function($query){
//                        return $query->whereIn('status',['已入场','未审核']);
//                    }])->whereNotNull('deleted_at')->where('user_id',$this['user_id'])->first();
//                    if(!$laborReport) return null;
//                    $laborReport=LaborReport::with(['laborReportStatus'=>function($query){
//                        return $query->where('status','已退场');
//                    }])->whereNotNull('deleted_at')->where('enter_number',$laborReport['enter_number'])->first();
//                    if ($laborReport->isEmpty())return null;
//                }
//            }
////            $this['temEnteringRecord']=$laborReport;
//            return $laborReport;
//        }
        $laborReport=LaborReport::with(['laborReportStatus'=>function($query){
            return $query->whereIn('status',['已入场','未审核']);
        }])->where('user_id',$this['user_id'])->orderBy('id','desc')->first();
        if(empty($laborReport))return null;
        return $laborReport;

    }

    public function getExitAtAttribute()
    {
        $laborReportStatus=LaborReportStatus::where('labor_report_id',$this['id'])->where('status','已退场')->orderBy('id','desc')->first();
        if (empty($laborReportStatus))return null;
        return Carbon::parse($laborReportStatus['created_at'])->format('Y-m-d H:i:s');
    }

    //创建或获取进场编号
    public function makeOrGetEnteringNumber()
    {
        if($this['enteringRecord']&&$this['enteringRecord']['enter_number'])
            return $this['enteringRecord']['enter_number'];
        $enteringNumber=date("ymd").str_pad($this['id']>99999?$this['id']%99999:$this['id'],4,"0",STR_PAD_LEFT);
        $this['enter_number']=$enteringNumber;
        return $enteringNumber;
    }

    public function getIsExportAttribute(){
        $laborReportStatus=LaborReportStatus::where('labor_report_id',$this['id'])->orderBy('id','desc')->first();
        return $laborReportStatus['status']=='已退场'?true:false;
    }

//出场更新临时工报表信息
    static function exitAndChangeLaborReport($laborReport,$userDutyCheck){
        $laborReportStatus=new LaborReportStatus([
            'labor_report_id'=>$laborReport['id'],
            'status'=>'已退场',
        ]);
        $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;
    }

















//修改临时工报表审核时间
//    static function updateLaborReportVerify($laborReport,$userDutyCheck){
//        $date=date('Y-m-d H:i:s');
//        $laborReport['verify_at']=$date;
//        $laborReport['group_user_id']=$userDutyCheck->group_user_id;
//        $laborReport->update();
//        return;
//    }
//    //添加临时工报表数据
//    static function createLaborReportData($userDutyCheck){
//        $userDetail=UserDetail::find($userDutyCheck->user_id);
//        $name=$userDetail['full_name'];
//        $mobile_phone=$userDetail['mobile_phone'];
//        $identity_number=$userDetail['identity_number'];
//        $labor_company_id=UserLabor::where('user_id',$userDutyCheck->user_id)->value('labor_company_id');
//        $labor_company=LaborCompany::where('id',$labor_company_id)->value('name');
//        if ($userDutyCheck->type=='登入'){
//            $check_in_at=$userDutyCheck['checked_at'];
//        }
//        $date=date('Y-m-d H:i:s');
//        $laborReport=new LaborReport([
//            'enter_number'=>Uuid::uuid1(),
//            'user_workgroup_id'=>$userDutyCheck->workgroup_id,
//            'user_id'=>$userDutyCheck->user_id,
//            'name'=>$name,
//            'mobile_phone'=>$mobile_phone,
//            'identity_number'=>$identity_number,
//            'labor_company'=>$labor_company,
//            'check_in_at'=>$check_in_at,
//            'verify_at'=>$date,
//            'group_user_id'=>$userDutyCheck->group_user_id,
//        ]);
//        $laborReport->save();
//        $number_id=$laborReport->id;
//        $enter_number=$userDutyCheck->workgroup_id.date ("ymd").str_pad($number_id>99999?$number_id%99999:$number_id,4,"0",STR_PAD_LEFT);
//        $laborReport->enter_number=$enter_number;
//        $laborReport->update();
//        return $laborReport;
//    }
//    //修改临时工报表数据
//    static function updateLaborReportData($laborReport,$userDutyCheck){
//            //正常打卡情况
//            if($userDutyCheck->type=='登出'){
//                $laborReport->check_out_at=$userDutyCheck->checked_at;
//                $checkInDate=Carbon::parse($laborReport['check_in_at']);
//                $checkOutDate=Carbon::parse($userDutyCheck->checked_at);
//                $hour=($checkOutDate->diffInSeconds($checkInDate))/3600; //在线时长
//                $laborReport['online_duration']=$hour;
//                $laborReport['working_duration']=$hour;
//                $laborReport->update();
//            }
//        $date=Carbon::parse($laborReport['check_in_at'])->format('Y-m-d');
//        $userDutyCheckOld=UserDutyCheck::where('user_id',$userDutyCheck->user_id)->orderBy('checked_at','DESC')->limit(10)->first();
//        //补卡情况
//        if ($userDutyCheck->type=='登入'&&$userDutyCheckOld->checked_at>$userDutyCheck->checked_at&&$userDutyCheck->checked_at<$date." 11:00".":00"){
//            $laborReport['check_in_at']=$userDutyCheck['checked_at'];
//            $checkInDate=Carbon::parse($laborReport['check_in_at']);
//            if ($laborReport->check_out_at){
//                $checkOutDate=Carbon::parse($laborReport->check_out_at);
//                $hour=($checkOutDate->diffInSeconds($checkInDate))/3600; //在线时长
//                $laborReport['online_duration']=$hour;
//            }
//            $laborReport->update();
//        }
//        if ($userDutyCheck->type=='登入'&&$userDutyCheckOld->checked_at<$userDutyCheck->checked_at){
//            $userDutyCheck->save();
//            $laborReport['working_duration']=$laborReport['online_duration'];
//            $laborReport->update();
//        }
//        if ($userDutyCheck->type=='登出'&&$userDutyCheckOld->checked_at<$userDutyCheck->checked_at){
//            $laborReport->check_out_at=$userDutyCheck->checked_at;
//            $checkInDate=Carbon::parse($laborReport['check_in_at']);
//            $checkOutDate=Carbon::parse($userDutyCheck->checked_at);
//            $hour=($checkOutDate->diffInSeconds($checkInDate))/3600; //在线时长
//            $laborReport['online_duration']=$hour;
//            $laborReport['working_duration']=$hour;
//            $laborReport->update();
//        }
//
//        if ($laborReport&&$laborReport->check_out_at){
//            $userDutyCheckStart=UserDutyCheck::where('user_id',$laborReport->user_id)->where('workgroup_id',$laborReport->user_workgroup_id)->where('checked_at','>=',$date." 11:00".":00")
//                ->where('checked_at','<=',$date." 14:00:00")->where('type','登出')->first();
//            $userDutyCheckEnd=UserDutyCheck::where('user_id',$laborReport->user_id)->where('workgroup_id',$laborReport->user_workgroup_id)->where('checked_at','>=',$date." 11:00".":00")
//                ->where('checked_at','<=',$date." 14:00:00")->where('type','登入')->first();
//            $beginTime=Carbon::parse($userDutyCheckStart['checked_at']);
//            $endTime=Carbon::parse($userDutyCheckEnd['checked_at']);
//            $lunchHour=($endTime->diffInSeconds($beginTime))/3600;
//            if($userDutyCheck->type=='登入'&&$userDutyCheck->checked_at<=$date." 14:00:00"){
//                $laborReport['working_duration']=$laborReport['online_duration'];
//            }else if($userDutyCheck->type=='登出'&&$userDutyCheck->checked_at<=$date." 14:00:00"){
//                $laborReport['working_duration']=$laborReport['online_duration'];
//            }else{
//                $laborReport['working_duration']=$laborReport['online_duration']-$lunchHour;
//            }
//            $laborReport->update();
//        }
//        return;
//    }
}
