<?php

namespace App\Http\Controllers\H5;

use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\SendTemplateNotice;
use App\Models\MeetRoom;
use App\Models\MeetRoomOwner;
use App\Models\MeetRoomReserve;
use App\Models\Office;
use App\Models\ServiceUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use function Symfony\Component\Translation\t;

class OfficeController extends Controller
{
    use ResponseJson;


    /**
     * 预定会议室
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function reserveMeetRoom(Request $request){
        DB::beginTransaction();
        try {
            $user = Auth()->user();
            $date_time = date('Y-m-d H:i:s');
            $title = $request->input('title');
            if(empty($title)) return $this->failure('请输入会议标题');
            $room_id = $request->input('room_id');
            if(empty($room_id)) return $this->failure('请选择会议室');

            $start_time = $request->input('start_time');
            if(empty($start_time)) return $this->failure('请选择开始时间');

            $end_time = $request->input('end_time');
            if(empty($end_time)) return $this->failure('请选择结束时间');

            if($end_time <= $start_time){
                return $this->failure('结束时间小于开始时间');
            }
            //与当前时间对比 TODO
            if($end_time < $date_time){
                return $this->failure('结束时间不得小于当前时间');
            }

            //时间间隔不得大于8小时 TODO
            $datetime1 = new \DateTime($start_time);
            $datetime2 = new \DateTime($end_time);
            $interval = $datetime1->diff($datetime2);
            $hours = ($interval->days * 24) + $interval->h;
            if($hours > 8){
                return $this->failure('时间间隔不得大于8小时');
            }
            $number = $request->input('number');

            //查看房间在这个时间段是否被预定
            $meet_room = MeetRoom::where('id',$room_id)->first();
            $day = date('Y-m-d');
            $reserve_list = MeetRoomReserve::where('room_id',$room_id)->where('created_at','like',$day.'%')->whereIn('status',[1,2,3])->get();
            $flag = false;
            foreach ($reserve_list as $value){
                $s_time = $value->start_time;
                $e_time = $value->end_time;
                //结束时间在别的预定之间
                if($value->start_time < $end_time && $value->end_time > $end_time){
                    $flag = true;
                    break;
                }
                //开始时间在别的预定之间
                if($value->start_time < $start_time && $value->end_time > $start_time){
                    $flag = true;
                    break;
                }
                //预定时间包含别人整个时间
                if($value->start_time > $start_time && $value->end_time < $end_time){
                    $flag = true;
                    break;
                }
            }
            //提示哪个时间段被预约 TODO
            if($flag){
                return $this->failure('时间段'.$s_time.'-'.$e_time.'被预定,请选择合适时间');
            }
            $service_user = ServiceUser::where('user_id',$user->id)->first();
            $map = [];
            $map['room_id'] = $room_id;
            $map['title'] = $title;
            $map['user_id'] = $user->id;
            $map['user_name'] = $service_user->name??'';
            $map['user_mobile'] = $service_user->mobile??'';
            $map['number'] = $number;
            $map['start_time'] = $start_time;
            $map['end_time'] = $end_time;
            //无需审核,直接预定
            if($meet_room->type == 1){
                $map['status'] = 1;
                MeetRoom::where('id',$room_id)->update(['status'=>1]);
                //给所有者发送消息通知
                $owner_user = MeetRoomOwner::where('room_id',$room_id)->get();

                foreach ($owner_user as $item){
                    $params = [
                        'touser'=>$item->open_id,
                        'template_id'=>config('wechat.tpls.reserve_meeting_room'),
                        'data'=>[
                            'thing2' => ['value'=>$meet_room->room_name],
                            'phrase13' => ['value'=>$service_user->name],
                            'time26' => ['value'=>$start_time.'~'.$end_time],
                            'time20' => ['value'=>$date_time],
                        ]
                    ];
                    SendTemplateNotice::dispatch($params)->onQueue('health');
                }
            }

            MeetRoomReserve::create($map);

            DB::commit();
            return $this->success('ok',$map);
        }catch (\Exception $e){
            DB::rollBack();
            Log::error('reserveMeetRoom:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 获取预定记录
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getReserveLog(){
        try {
            $user = Auth()->user();
            $list = MeetRoomReserve::orderByDesc('id')->paginate();
            foreach ($list as $item){
                $item->room_name = MeetRoom::where('id',$item->room_id)->value('room_name');
                $item->is_my_self = false;
                if($item->user_id == $user->id){
                    $item->is_my_self = true;
                }
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getReserveLog:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 获取会议室
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getMeetRoom(){
        try {
            $list = MeetRoom::get();
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getMeetRoom:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 取消预定
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function cancelReserve(Request $request){
        DB::beginTransaction();
        try {
            $id = $request->get('id');
            $user = Auth()->user();
            if(empty($id)) return $this->failure('id不为空');

            $reserve = MeetRoomReserve::where('id',$id)->first();
            if(in_array($reserve->status,[2,3,4])){
                return $this->failure('会议已开始或已取消');
            }

            if($user->id != $reserve->user_id){
                return $this->failure('不能取消非自己预定记录');
            }
            $reserve->status = 4;
            $reserve->save();

            $meet_room = MeetRoom::where('id',$reserve->room_id)->first();
            $meet_room->status = 0;
            $meet_room->save();

            DB::commit();
            return $this->success('ok');
        }catch (\Exception $e){
            DB::rollBack();
            Log::error('cancelReserve:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 获取办公室列表
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getOffice(){
        try {
            $list = Office::get();
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getOffice:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }
}
