<?php

namespace App\Http\Controllers;

use App\Events\ClockinEvent;
use App\LaborCompany;
use App\LaborReport;
use App\Services\LaborReportService;
use App\User;
use App\UserDetail;
use App\UserDutyCheck;
use App\UserLabor;
use App\UserWorkgroup;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use Ramsey\Uuid\Uuid;

class UserDutyCheckController extends Controller
{
    function __construct()
    {
        app()->bind('LaborReportService', LaborReportService::class);
    }

    //校验二维码进入进出场打卡页面
    public function importAndExportClock(Request $request)
    {
        $importAndExportQRCodeType = $request->input('importAndExportQRCodeType');
        $qrCode_refresh_everyday = config('hr.qrCode_refresh_everyday');
        $qrCode_refresh = config('hr.qrCode_refresh');
        if ($qrCode_refresh_everyday) {
            $key = $request->input('key');
            if (!$key) return "<h1 style='color: red;text-align:center'>当前二维码失效,请重新扫码!</h1>";
            $date = md5(date('Y-m-d'));
            if ($key != $date) return "<h1 style='color: red;text-align:center'>当前二维码失效,请重新扫码!</h1>";
        }
        if ($qrCode_refresh) {
            $key = $request->input('key');
            if (!$key) return "<h1 style='color: red;text-align:center'>当前二维码失效,请重新扫码!</h1>";
            $date = date('Y-m-d H:i:s');
            if ($key < $date) return "<h1 style='color: red;text-align:center'>当前二维码失效,请重新扫码!</h1>";
        }

        $userLaborToken = $request->cookie('userLaborToken');
        $user_id = Cache::get('dutyCheckTokenStr_'.$userLaborToken);
        if (!$user_id) app('LogService')->log(__METHOD__, "进出场扫码(未绑定设备)__" . __FUNCTION__, json_encode($importAndExportQRCodeType));
        if ($userLaborToken && $user_id) {
            $userDetail = UserDetail::find($user_id);
            if($userDetail){
                if($importAndExportQRCodeType=='import') return redirect('personnel/checking-in/userDutyCheck/updateUserLaborCompanies/' . $userDetail->mobile_phone)->with("importAndExportQRCodeType", $importAndExportQRCodeType);
                $userDutyCheck = $this->importAndExportDutyCheck($user_id, $importAndExportQRCodeType);
                $error=$this->hasError($userDutyCheck);
                if ($error) return $error;
                $laborReportService = app('LaborReportService');
                $errorMessage = $laborReportService->makeOrChangeLaborReportByUserDutyCheck($userDutyCheck, $importAndExportQRCodeType);
                if ($errorMessage) return $errorMessage;
                $laravelEchoPrefix = config('database.redis.options.prefix');
                $log=[
                    'importAndExportQRCodeType'=>$importAndExportQRCodeType,
                    'userDetail'=>$userDetail,
                ];
                app('LogService')->log(__METHOD__, "进出场扫码__" . __FUNCTION__, json_encode($log));
                return response()->view('personnel/checking-in/importAndExportSuccess', ['full_name' => $userDetail->full_name, 'checked_at' => $userDutyCheck->checked_at, 'type' => $userDutyCheck->type, 'laravelEchoPrefix' => $laravelEchoPrefix]);

            }
        }
        return view("personnel/checking-in/importAndExportClock", compact('importAndExportQRCodeType'));
    }

    //输入手机号提交进场打卡
    public function storeClock(Request $request)
    {
        $importAndExportQRCodeType = $request->input('importAndExportQRCodeType');
        $mobile_phone = $request->input('mobile_phone');
        $this->validatorPhone($request)->validate();
        $userDetail = UserDetail::query()->where('mobile_phone', $mobile_phone)->first();
        if (!$userDetail) return redirect('personnel/checking-in/userDutyCheck/createUserDetail/' . $mobile_phone)->with("importAndExportQRCodeType", $importAndExportQRCodeType);
        if (Cache::has('dutyCheckTokenUser_'.$userDetail->user_id)) return "<h1 style='color: red;text-align:center'>请使用原有设备进行打卡,如无法使用原有设备请联系管理人员解绑设备!</h1>";
        if($importAndExportQRCodeType=='import') return redirect('personnel/checking-in/userDutyCheck/updateUserLaborCompanies/' . $userDetail->mobile_phone)->with("importAndExportQRCodeType", $importAndExportQRCodeType);
        $userDutyCheck=$this->importAndExportDutyCheck($userDetail->user_id, $importAndExportQRCodeType);
        $error=$this->hasError($userDutyCheck);
        if ($error) return $error;
        $laborReportService = app('LaborReportService');
        $errorMessage = $laborReportService->makeOrChangeLaborReportByUserDutyCheck($userDutyCheck, $importAndExportQRCodeType);
        if ($errorMessage) return $errorMessage;
        $laravelEchoPrefix = config('database.redis.options.prefix');
        return response()->view('personnel/checking-in/importAndExportSuccess', ['full_name' => $userDetail->full_name, 'checked_at' => $userDutyCheck->checked_at, 'type' => $userDutyCheck->type, 'laravelEchoPrefix' => $laravelEchoPrefix]);
    }

    //根据用户提交进出场打卡记录
    public function importAndExportDutyCheck($user_id,$importAndExportQRCodeType)
    {
        $dateNow = Carbon::now()->format('Y-m-d');
        $userDutyCheckOld = UserDutyCheck::query()->with('laborReport')->where('user_id', $user_id)->where('checked_at','like',$dateNow.'%')->orderBy('id','desc')->first();
        $date = date('Y-m-d H:i:s');
        app('LogService')->log(__METHOD__, "提交打卡记录__" . __FUNCTION__, json_encode([$user_id, $date]));
        $userDutyCheck = new UserDutyCheck([
            'user_id' => $user_id,
            'checked_at' => $date,
            'source' => '正常',
        ]);
        //跨天登出情况
        if (!$userDutyCheckOld) {
            //当前日期的前一天
            $yesterday = Carbon::yesterday()->format('Y-m-d');
            $userDutyCheckYesterday = UserDutyCheck::query()->with('laborReport')->where('user_id', $user_id)->where('checked_at','like', $yesterday.'%')->orderBy('id','desc')->first();
            if ($importAndExportQRCodeType && $importAndExportQRCodeType == 'export') {
                if ($userDutyCheckYesterday && $userDutyCheckYesterday->type == '登入') {
                    $userDutyCheck->verify_user_id = $userDutyCheckYesterday->verify_user_id;
                    $userDutyCheck->type = '登出';
                    $userDutyCheck->save();
                    return $userDutyCheck;
                }
            }
            if ($importAndExportQRCodeType && $importAndExportQRCodeType == 'import') {
                if ($userDutyCheckYesterday && $userDutyCheckYesterday->type == '登入'&&$userDutyCheckYesterday->laborReport) {
                    $userDutyCheck->import = true;//已入场的不能再入场
                    return $userDutyCheck;
                }
            }
            if ($importAndExportQRCodeType == 'export') {
                $userDutyCheck->isNotImport = true;//还未进场，不可出场
                return $userDutyCheck;
            }
            $userDutyCheck->type = "登入";
            $userDutyCheck->save();
            app('LogService')->log(__METHOD__, "创建打卡记录" . __FUNCTION__, json_encode($userDutyCheck));
            return $userDutyCheck;
        }else{
            if ($importAndExportQRCodeType && $importAndExportQRCodeType == 'import') {
                if ($userDutyCheckOld->type == '登入'&&$userDutyCheckOld->laborReport) {
                    $userDutyCheck->import = true;//已入场的不能再入场
                    return $userDutyCheck;
                }
                $userDutyCheck->type = '登入';
            }
            if ($importAndExportQRCodeType && $importAndExportQRCodeType == 'export') {
                if ($userDutyCheckOld->type == '登出') {
                    $userDutyCheck->export = true;//已出场的不能再出场
                    return $userDutyCheck;
                }
                $userDutyCheck->verify_user_id = $userDutyCheckOld->verify_user_id;
                $userDutyCheck->type = '登出';
            }
            $userDutyCheck->save();
            app('LogService')->log(__METHOD__, "创建打卡记录" . __FUNCTION__, json_encode($userDutyCheck));
            return $userDutyCheck;
        }
    }
    //去往登记资料页面
    public function createUserDetail($mobile_phone)
    {
        $importAndExportQRCodeType = session("importAndExportQRCodeType");
        $laborCompanies = LaborCompany::select('id', 'name')->get();
        return view('personnel/checking-in/createUserDetail', ['mobile_phone' => $mobile_phone, 'importAndExportQRCodeType' => $importAndExportQRCodeType, 'laborCompanies' => $laborCompanies]);
    }
    //未打卡去往选择劳务所页面
    public function updateUserLaborCompanies($mobile_phone)
    {
        $importAndExportQRCodeType = session("importAndExportQRCodeType");
        $laborCompanies = LaborCompany::select('id', 'name')->get();
        return view('personnel/checking-in/updateUserLaborCompanies', ['mobile_phone' => $mobile_phone, 'importAndExportQRCodeType' => $importAndExportQRCodeType, 'laborCompanies' => $laborCompanies]);
    }

    //打卡修改临时工劳务所信息并生成进场记录 AndMakeEnterRecord
    public function storeUpdateUserLaborCompanies(Request $request)
    {
        $this->updateValidator($request)->validate();
        $importAndExportQRCodeType = $request->input('importAndExportQRCodeType');
        $mobile_phone = $request->input('mobile_phone');
        $userDetail = UserDetail::query()->where('mobile_phone', $mobile_phone)->first();
        if (!$userDetail) return view('exception.404', ['error' => '临时工信息不存在！']);
        $labor_company_id = $request->input('labor_company_id');
        $userLabor = UserLabor::query()->where('user_id', $userDetail->user_id)->first();
        $userLabor->update([
            'labor_company_id' => $labor_company_id,
        ]);
        app('LogService')->log(__METHOD__, "更改临时工劳务所信息" . __FUNCTION__, json_encode($userLabor), Auth::user()['id']);
        $userDutyCheck=$this->importAndExportDutyCheck($userDetail->user_id,$importAndExportQRCodeType);
        $error=$this->hasError($userDutyCheck);
        if ($error) return $error;
        $userLaborToken = $userDetail->getDutyCheckToken(config('users.token_check_in_expire_minutes'));
        $laborReportService = app('LaborReportService');
        $errorMessage = $laborReportService->makeOrChangeLaborReportByUserDutyCheck($userDutyCheck, $importAndExportQRCodeType);
        if ($errorMessage) return $errorMessage;
        $laravelEchoPrefix = config('database.redis.options.prefix');
        return response()->view('personnel/checking-in/importAndExportSuccess',['full_name'=>$userDetail->full_name,'checked_at'=>$userDutyCheck->checked_at,'type'=>$userDutyCheck->type,'laravelEchoPrefix'=>$laravelEchoPrefix])
            ->cookie('userLaborToken', $userLaborToken, config('users.token_check_in_expire_minutes'), '/');
    }

    public function updateValidator(Request $request)
    {
        $updateValidator = Validator::make($request->input(), [
            'mobile_phone' => ['required', 'integer', 'digits:11'],
            'labor_company_id' => ['filled'],
        ], [
            'filled' => ':attribute 不能为空',
            'required' => ':attribute 为必填项',
            'integer' => ':attribute 数字类型',
            'digits' => ':attribute 必须是11位',
        ], [
            'mobile_phone' => '手机号',
            'labor_company_id' => '劳务所',
        ]);
        return $updateValidator;
    }

    //打卡创建临时工资料并生成进场记录
    public function storeUserDetail(Request $request)
    {$this->validator($request)->validate();
        $importAndExportQRCodeType = $request->input('importAndExportQRCodeType');
        $mobile_phone = $request->input('mobile_phone');
        $full_name = $request->input('full_name');
        $identity_number = $request->input('identity_number');
        $gender = $request->input('gender');
        $labor_company_id = $request->input('labor_company_id');
        $user = new User([
            'name' => $mobile_phone,
            'password' => Uuid::uuid1(),
        ]);
        $user->save();
        $userDetail = new UserDetail([
            'user_id' => $user->id,
            'full_name' => $full_name,
            'identity_number' => $identity_number,
            'gender' => $gender,
            'mobile_phone' => $mobile_phone,
            'type' => '临时工',
        ]);
        $userDetail->save();
        $userDetail->updateUserName();
        $userLabor = new UserLabor([
            'user_id' => $user->id,
            'labor_company_id' => $labor_company_id,
        ]);
        $userLabor->save();
        $laborReportService = app('LaborReportService');
        $userDutyCheck=$this->importAndExportDutyCheck($userDetail->user_id,$importAndExportQRCodeType);
        $error=$this->hasError($userDutyCheck);
        if ($error) return $error;
        $laborReportService->makeLaborReportByUserDutyCheck($userDutyCheck);
        $userLaborToken=$userDetail->getDutyCheckToken(config('users.token_check_in_expire_minutes'));
        Controller::logS(__METHOD__,"录入临时工,用户,对应工作组,打卡记录".__FUNCTION__,json_encode($userDetail));
        $laravelEchoPrefix = config('database.redis.options.prefix');
        return response()->view('personnel/checking-in/importAndExportSuccess',['full_name'=>$userDetail->full_name,'checked_at'=>$userDutyCheck->checked_at,'type'=>$userDutyCheck->type,'laravelEchoPrefix'=>$laravelEchoPrefix])
            ->cookie('userLaborToken',$userLaborToken,config('users.token_check_in_expire_minutes'),'/');

    }

    public function validator(Request $request)
    {
        $validator = Validator::make($request->input(), [
            'full_name' => ['filled'],
            'gender' => ['filled'],
            'mobile_phone' => ['required', 'integer', 'digits:11','unique:user_details,mobile_phone'],
            'identity_number' => ['filled', 'identity_cards', 'unique:user_details,identity_number'],
            'labor_company_id' => ['filled'],
        ], [
            'unique' => ':attribute 已经存在，不能重复！',
            'filled' => ':attribute 不能为空',
            'required' => ':attribute 为必填项',
            'integer' => ':attribute 数字类型',
            'digits' => ':attribute 必须是11位',
        ], [
            'full_name' => '姓名',
            'gender' => '性别',
            'mobile_phone' => '手机号',
            'identity_number' => '身份证号',
            'labor_company_id' => '劳务所',
        ]);
        return $validator;
    }
    public function validatorPhone(Request $request)
    {
        $validator = Validator::make($request->input(), [
            'mobile_phone' => ['required', 'integer', 'digits:11'],
        ], [
            'required' => ':attribute 为必填项',
            'integer' => ':attribute 数字类型',
            'digits' => ':attribute 必须是11位',
        ], [
            'mobile_phone' => '手机号',
        ]);
        return $validator;
    }

    //扫工作组二维码
    public function clock(Request $request)
    {
        $userWorkgroupID = $request->input('userWorkgroupID');
        $userLaborToken = $request->cookie('userLaborToken');
        $user_id = Cache::get('dutyCheckTokenStr_'.$userLaborToken);
        if (!$user_id)app('LogService')->log(__METHOD__, "进组扫码(未绑定设备)__" . __FUNCTION__, json_encode($userWorkgroupID));
        if ($userLaborToken && $user_id) {
            $dateNow = Carbon::now()->format('Y-m-d');
            $userDutyCheck = UserDutyCheck::where('user_id', $user_id)->where('checked_at', 'like', $dateNow. '%')->orderBy('id', 'desc')->first();
            if (!$userDutyCheck['verify_user_id']) return "<h1 style='color: red;text-align:center'>进场门卫还未审核，暂无法进组！</h1>";
            if ($userDutyCheck->type == '登出') return "<h1 style='color: red;text-align:center'>进场是否未打卡？如若未打，请先返回打进场卡！</h1>";
            $html=$this->updateLaborReport($user_id,$userWorkgroupID);
            if ($html)return $html;
            $log=[
                'userWorkgroupID'=>$userWorkgroupID,
                'user_id'=>$user_id,
            ];
            app('LogService')->log(__METHOD__, "进组扫码__" . __FUNCTION__, json_encode($log));
        }else{
            return view("personnel/checking-in/enterGroupClock", compact('userWorkgroupID'));
        }
    }

    public function updateLaborReport($user_id,$userWorkgroupID,$userLaborToken=null)
    {
        $userDetail = UserDetail::find($user_id);
        $group_name = UserWorkgroup::where('id', $userWorkgroupID)->value('name');
        $laravelEchoPrefix = config('database.redis.options.prefix');
        $laborReportService = app('LaborReportService');
        //判断是否是第一次进组
        $laborReport = LaborReport::where('user_id', $user_id)->where('user_workgroup_id', null)->where('created_at', 'like', Carbon::now()->format('Y-m-d') . '%')->orderBy('id', 'desc')->first();
        if ($laborReport) {
            $newLaborReport = $laborReportService->enterGroupAndUpdateLaborReport($laborReport, $userWorkgroupID);
            app('LogService')->log(__METHOD__, "当日首次进组更新临时工报表记录__" . __FUNCTION__, json_encode($userWorkgroupID));
            if (!$newLaborReport) return "<h1 style='color: red;text-align:center'>打卡异常，请联系相关人员!</h1>";
            event(new ClockinEvent($newLaborReport));
        } else {
            //换组判断上一条临时工报表信息是否退组
            $laborReportNow = LaborReport::where('user_id', $user_id)->orderBy('id', 'desc')->first();
            if ($laborReportNow['group_user_id'] && !$laborReportNow['check_out_at']) return "<h1 style='color: darkred;text-align:center'>您还未退组，暂不可换组，请联系之前组长!</h1>";
            if (!$laborReportNow['group_user_id'] && $laborReportNow['user_workgroup_id']==$userWorkgroupID) return "<h1 style='color: darkred;text-align:center'>当前已进组，请等待组长审核！</h1>";
            //此处表示临时工换组操作
            $newLaborReport = $laborReportService->changeGroupAndMakeLaborReport($user_id, $userWorkgroupID);
            app('LogService')->log(__METHOD__, "当日临时工换组新建临时工报表记录__" . __FUNCTION__, json_encode([$user_id, $userWorkgroupID]));
            if (!$newLaborReport) return "<h1 style='color: red;text-align:center'>打卡异常，请联系相关人员!</h1>";
            event(new ClockinEvent($newLaborReport));
        }
        if ($userLaborToken){
            return response()->view('personnel/checking-in/success', ['group_name' => $group_name ?? '', 'full_name' => $userDetail->full_name, 'check_in_at' => $newLaborReport->check_in_at, 'laravelEchoPrefix' => $laravelEchoPrefix])
                ->cookie('userLaborToken',$userLaborToken,config('users.token_check_in_expire_minutes'),'/');
        }else{
            return response()->view('personnel/checking-in/success', ['group_name' => $group_name ?? '', 'full_name' => $userDetail->full_name, 'check_in_at' => $newLaborReport->check_in_at, 'laravelEchoPrefix' => $laravelEchoPrefix]);
        }
    }
    public function 绑定临时工并进组(Request $request){
        $userWorkgroupID = $request->input('userWorkgroupID');
        $mobile_phone = $request->input('mobile_phone');
        $userDetail = UserDetail::query()->where('mobile_phone', $mobile_phone)->first();
        if (!$userDetail) return "<h1 style='color: red;text-align:center'>系统未识别当前手机号，请验证输入是否正确！</h1>";
        $userLaborToken=$userDetail->getDutyCheckToken(config('users.token_check_in_expire_minutes'));
        $dateNow = Carbon::now()->format('Y-m-d');
        $userDutyCheck = UserDutyCheck::where('user_id', $userDetail->user_id)->where('checked_at', 'like', $dateNow. '%')->orderBy('id', 'desc')->first();
        if (!$userDutyCheck['verify_user_id']) return "<h1 style='color: red;text-align:center'>进场门卫还未审核，暂无法进组！</h1>";
        if ($userDutyCheck->type == '登出') return "<h1 style='color: red;text-align:center'>进场是否未打卡？如若未打，请先返回打进场卡！</h1>";
        app('LogService')->log(__METHOD__, "进组扫码未绑定设备重新绑定__" . __FUNCTION__, json_encode([$userWorkgroupID,$userDetail]));
        $html=$this->updateLaborReport($userDetail->user_id,$userWorkgroupID,$userLaborToken);
        if ($html)return $html;
    }
    private function hasError($userDutyCheck)
    {
        if ($userDutyCheck && $userDutyCheck->isNotImport == true) return "<h1 style='color: darkred;text-align:center'>当前还未入场，不可出场!</h1>";
        if ($userDutyCheck && $userDutyCheck->import == true) return "<h1 style='color: darkred;text-align:center'>您已入场，不可再次入场!</h1>";
        if ($userDutyCheck && $userDutyCheck->export == true) return "<h1 style='color: darkred;text-align:center'>您已出场，不可再次出场!!</h1>";
        if ($userDutyCheck&& !$userDutyCheck->id) return "<h1 style='color: red;text-align:center'>打卡异常，请联系相关人员!</h1>";
    }

}
