<?php

namespace App\Http\Controllers\Admin;

use App\Exports\ChefUserExport;
use App\Exports\MeetRoomExport;
use App\Exports\OfficeExport;
use App\Exports\StationExport;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\MeetRoom;
use App\Models\MeetRoomOwner;
use App\Models\MeetRoomReserve;
use App\Models\Office;
use App\Models\Partner;
use App\Models\ServiceUser;
use App\Models\Station;
use App\Models\StationLog;
use App\Models\Wechat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class OfficeController extends Controller
{
    use ResponseJson;

    /**
     * 创建办公室
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function addOffice(Request $request)
    {
        try {
            $office_name = $request->input('office_name');
            if(empty($office_name)){
                return $this->failure('办公室名不为空');
            }
            $exists = Office::where('office_name',$office_name)->exists();
            if($exists){
                return $this->failure('办公室已存在');
            }
            $images = $request->input('images');
            $detail_images = $request->input('detail_images');
            $map = [];
            $map['office_name'] = $office_name;
            $map['images'] = $images;
            $map['detail_images'] = $detail_images;
            $res = Office::create($map);
            return $this->success('ok',$res);
        }catch (\Exception $e){
            Log::error('addOffice:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 获取办公室列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getOfficeList(Request $request){
        try {
            $keyword = $request->get('keyword');
            $no_page = $request->get('no_page');
            $office = Office::query()->when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('office_name', 'like', "%{$keyword}%");
                });
            })
                ->orderByDesc('id');

            if($no_page){
                $list = $office->get();
            }else{
                $list = $office->paginate();
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getOfficeList:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 更新办公室信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function updateOffice(Request $request){
        try{
            $id = $request->get('id');
            if(empty($id)) return $this->failure('id不为空');
            $office = Office::where('id',$id)->first();

            $office_name = $request->get('office_name');
            if(!empty($office_name)) $office->office_name = $office_name;

            $exists = Office::where('office_name',$office_name)->exists();
            if($exists){
                return $this->failure('办公室已存在');
            }

            $images = $request->input('images');
            if(!empty($images)) $office->images = $images;

            $detail_images = $request->input('detail_images');
            if(!empty($detail_images)) $office->detail_images = $detail_images;

            $office->save();
            return $this->success('ok');

        }catch (\Exception $e){
            Log::error('updateOffice:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 删除办公室
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function deleteOffice(Request $request){
        try {
            $id = $request->get('id');
            if(empty($id)) return $this->failure('id不为空');
            $meetRoom = MeetRoom::where('office_id',$id)->exists();
            if($meetRoom){
                return $this->failure('请先删除办公室下会议室');
            }
            $station = Station::where('office_id',$id)->exists();
            if($station){
                return $this->failure('请先删除办公室下工位');
            }
            $res = Office::where('id',$id)->delete();
            return $this->success('ok',$res);
        }catch (\Exception $e){
            Log::error('deleteOffice:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 添加会议室
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function addMeetingRoom(Request $request){
        DB::beginTransaction();
        try {
            $office_id = $request->input('office_id');
            if(empty($office_id)) return $this->failure('请选择所属办公室');
            $room_name = $request->input('room_name');
            if(empty($room_name)) return $this->failure('会议室名称不为空');

            $user_ids = $request->input('user_ids');
            if(empty($user_ids)) return $this->failure('拥有者id不为空');

            $type = $request->input('type',0);

            $desc = $request->input('desc');
            $images = $request->input('images');

            $room_map = [];
            $room_map['office_id'] = $office_id;
            $room_map['room_name'] = $room_name;
            $room_map['type'] = $type;
            $room_map['desc'] = $desc;
            $room_map['images'] = $images;
            $model = MeetRoom::create($room_map);
            //获取会议室id并添加拥有者
            $room_id = $model->id;
            foreach ($user_ids as $user_id){
                $owner_map = [];
                $user = ServiceUser::where('user_id',$user_id)->first();
                $open_id = Wechat::where('user_id',$user_id)->where('type','official')->value('openid');
                $owner_map['room_id'] = $room_id;
                $owner_map['user_id'] = $user_id;
                $owner_map['name'] = $user->name??'';
                $owner_map['mobile'] = $user->mobile??'';
                $owner_map['open_id'] = $open_id??0;
                MeetRoomOwner::create($owner_map);
            }
            DB::commit();
            return $this->success('ok');
        }catch (\Exception $e){
            DB::rollBack();
            Log::error('addMeetingRoom:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 获取会议室列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getMeetRoomList(Request $request){
        try {
            $keyword = $request->get('keyword');
            $list = MeetRoom::when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('room_name', 'like', "%{$keyword}%");
                });
            })
                ->orderByDesc('id')
                ->paginate();

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

    /**
     * 获取拥有者数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getOwnerUser(Request $request){
        try {
            $room_id = $request->get('room_id');
            if(empty($room_id)) return $this->failure('会议室id不能为空');
            $list = MeetRoomOwner::where('room_id',$room_id)
                ->orderByDesc('id')
                ->get();
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getOwnerUser:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     *获取预约记录
     * @param Request $request
     */
    public function getMeetRoomReserve(Request $request){
        try {
            $room_id = $request->get('room_id');
            if(empty($room_id)) return $this->failure('会议室id不能为空');
            $list = MeetRoomReserve::where('room_id',$room_id)
                ->orderByDesc('id')
                ->paginate();
            foreach ($list as $item){
                $item->room_name = MeetRoom::where('id',$item->room_id)->value('room_name');
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getMeetRoomReserve:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 删除会议室
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function deleteMeetRoom(Request $request){
        DB::beginTransaction();
        try {
            $room_id = $request->get('room_id');
            MeetRoom::where('id',$room_id)->delete();
            MeetRoomOwner::where('room_id',$room_id)->delete();
            DB::commit();
            return $this->success('ok');
        }catch (\Exception $e){
            DB::rollBack();
            Log::error('deleteMeetRoom:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 更新会议室信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function updateMeetRoom(Request $request){
        DB::beginTransaction();
        try {
            $room_id = $request->get('room_id');
            if(empty($room_id)) return $this->failure('会议室id不能为空');
            $room_info = MeetRoom::where('id',$room_id)->first();

            $office_id = $request->get('office_id');
            if(!empty($office_id)) $room_info->office_id = $office_id;

            $room_name = $request->get('room_name');
            if(!empty($room_name)) $room_info->room_name = $room_name;

            $desc = $request->get('desc');
            if(!empty($desc)) $room_info->desc = $desc;

            $images = $request->get('images');
            if(!empty($images)) $room_info->images = json_encode($images);

            //删除旧拥有者,重新插入
            MeetRoomOwner::where('room_id',$room_id)->delete();

            $user_ids = $request->input('user_ids');
            if(empty($user_ids)) return $this->failure('拥有者id不为空');

            foreach ($user_ids as $user_id){
                $owner_map = [];
                $user = ServiceUser::where('user_id',$user_id)->first();
                $open_id = Wechat::where('user_id',$user_id)->where('type','official')->value('openid');
                $owner_map['room_id'] = $room_id;
                $owner_map['user_id'] = $user_id;
                $owner_map['name'] = $user->name??'';
                $owner_map['mobile'] = $user->mobile??'';
                $owner_map['open_id'] = $open_id??0;
                MeetRoomOwner::create($owner_map);
            }

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

    /**
     * 获取服务人员
     * @param Request $request
     */
    public function getServiceUser(Request $request){
        try {
            $keyword = $request->get('keyword');
            $list = ServiceUser::when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%")->orWhere('mobile','like',"%{$keyword}%");
                });
            })
                ->orderByDesc('id')
                ->paginate();
            foreach ($list as $item){
                $partner = Partner::where('user_id',$item->user_id)->first();
                $item->avatar = $partner->pic??'';
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getServiceUser:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 添加工位
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function addStation(Request $request){
        DB::beginTransaction();
        try {
            $office_id = $request->input('office_id');
            if(empty($office_id)) return $this->failure('请选择所属办公室');

            $number = $request->input('number');
            if(empty($number)) return $this->failure('编号不为空');

            $exists = Station::where('office_id',$office_id)->where('number',$number)->exists();
            if($exists){
                return $this->failure('工位已存在');
            }
            $user_id = $request->input('user_id');

            $map = [];
            $map['office_id'] = $office_id;
            $map['number'] = $number;
            $map['user_id'] = $user_id;
            $model = Station::create($map);

            //增加绑定记录
            if($user_id){
                $log_map = [];
                $log_map['station_id'] = $model->id;
                $log_map['user_id'] = $user_id;
                $log_map['type'] = StationLog::TYPE_BIND;
                $log_map['remark'] = '用户id:'.$user_id.'绑定了工位';
                StationLog::create($log_map);
            }

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

    /**
     * 获取工位列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getStationList(Request $request){
        try{
            $keyword = $request->get('keyword');
            $type = $request->get('type');
            $office_id = $request->get('office_id');
            $query = Station::query()->when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('number', 'like', "%{$keyword}%");
                });
            });

            if(!empty($office_id)){
                $query->where('office_id',$office_id);
            }
            //查询没有绑定用户的工位
            if($type){
                $query->where('user_id',null);
            }
            $query->orderByDesc('id');
            $no_page = $request->input('no_page');

            if($no_page){
                $list = $query->get();
            }else{
                $list = $query->paginate();
            }
            foreach ($list as $item){
                $item->office_name = Office::where('id',$item->office_id)->value('office_name');
                if($item->user_id){
                    $item->user_name = ServiceUser::where('user_id',$item->user_id)->value('name');
                }
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getStationList:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 删除工位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function deleteStation(Request $request){
        try{
            $id = $request->get('id');
            if(empty($id)) return $this->failure('id不为空');
            Station::where('id',$id)->delete();
            return $this->success('ok');
        }catch (\Exception $e){
            Log::error('deleteStation:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 修改工位
     * @param Request $request
     */
    public function updateStation(Request $request){
        DB::beginTransaction();
        try {
            $id = $request->get('id');
            if(empty($id)) return $this->failure('id不为空');

            $station = Station::where('id',$id)->first();

            $office_id = $request->get('office_id');
            if(!empty($office_id)) $station->office_id = $office_id;

            $number = $request->get('number');
            if($number != $station->number){
                $exists = Station::where('office_id',$office_id)->where('number',$number)->exits();
                if($exists){
                    return $this->failure('工位已存在');
                }
            }
            if(!empty($number)) $station->number = $number;


            $user_id = $request->get('user_id');
            if($user_id && $station->user_id && $station->user_id != $user_id){
                return $this->failure('已绑定用户');
            }

            //增加绑定记录
            $log_map = [];
            $log_map['station_id'] = $id;
            if($user_id){
                $log_map['user_id'] = $user_id;
                $log_map['type'] = StationLog::TYPE_BIND;
                $log_map['remark'] = '用户id:'.$user_id.'绑定了工位';
                StationLog::create($log_map);
            }else{
                $log_map['user_id'] = $station->user_id;
                $log_map['type'] = StationLog::TYPE_UNBIND;
                $log_map['remark'] = '用户id:'.$user_id.'解绑了工位';
                StationLog::create($log_map);
            }

            $station->user_id = $user_id;

            $station->save();

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

    /**
     *h获取解绑记录
     */
    public function getBindLog(Request $request){
        try {
            $keyword = $request->get('keyword');
            $list = StationLog::join('station','station.id','=','station_log.station_id')
                ->when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('station.number', 'like', "%{$keyword}%");
                });
            })
                ->select('station.number','station_log.*')
                ->orderByDesc('id')
                ->paginate();
            foreach ($list as $item){
                $item->user_name = ServiceUser::where('user_id',$item->user_id)->value('name');
                $office_id = Station::where('id',$item->station_id)->value('office_id');
                $item->office_name = Office::where('id',$office_id)->value('office_name');
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::error('getBindLog:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 导出办公室
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function exportOffice(Request $request){
        try {
            $keyword = $request->get('keyword');
            $office = Office::query()->when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('office_name', 'like', "%{$keyword}%");
                });
            })
                ->orderByDesc('id');

            $list = $office->get();
            if($list->isEmpty()){
                return $this->failure('暂无数据');
            }
            return Excel::download(new OfficeExport($list), 'office.xlsx');
        }catch (\Exception $e){
            Log::error('exportOffice:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 导出会议室
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function exportMeetRoom(Request $request){
        try {
            $keyword = $request->get('keyword');
            $list = MeetRoom::when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('room_name', 'like', "%{$keyword}%");
                });
            })
                ->orderByDesc('id')
                ->get();

            if($list->isEmpty()){
                return $this->failure('暂无数据');
            }
            return Excel::download(new MeetRoomExport($list), 'meet_room.xlsx');
        }catch (\Exception $e){
            Log::error('exportOffice:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 导出工位
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function exportStation(Request $request){
        try{
            $keyword = $request->get('keyword');
            $type = $request->get('type');
            $office_id = $request->get('office_id');
            $query = Station::query()->when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('number', 'like', "%{$keyword}%");
                });
            });

            if(!empty($office_id)){
                $query->where('office_id',$office_id);
            }
            //查询没有绑定用户的工位
            if($type){
                $query->where('user_id',null);
            }
            $query->orderByDesc('id');

            $list = $query->get();

            foreach ($list as $item){
                $item->office_name = Office::where('id',$item->office_id)->value('office_name');
                if($item->user_id){
                    $item->user_name = ServiceUser::where('user_id',$item->user_id)->value('name');
                }
            }
            return Excel::download(new StationExport($list), 'station.xlsx');
        }catch (\Exception $e){
            Log::error('getStationList:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }
}
