<?php

namespace App\Http\Controllers\Admin;

use App\Exports\CanRestaurantExport;
use App\Exports\ChefPlanListExport;
use App\Exports\ChefUserExport;
use App\Exports\RestaurantEvaluateEXport;
use App\Exports\RestaurantExport;
use App\Facades\CommonService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\AgentUser;
use App\Models\ChefPlan;
use App\Models\ChefUser;
use App\Models\Office;
use App\Models\Partner;
use App\Models\Restaurant;
use App\Models\RestaurantDate;
use App\Models\Station;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class RestaurantController extends Controller
{
    use ResponseJson;

    /**
     * 获取订餐记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getRestaurantList(Request $request)
    {
        try {
            $date = $request->get('date');
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $is_pay = $request->get('is_pay', '');
            $keyword = $request->get('keyword');
            $diet_type = $request->get('diet_type');
            $food_type = $request->get('food_type');
            $office_id = $request->get('office_id');
            $type = $request->get('type');
            $query = Restaurant::query();
            if($date){
                $query->when($date, function ($query) use ($date) {
                    $query->where(function ($query) use ($date) {
                        $query->where('date', $date);
                    });
                });
            }

            if($start_time){
                $query->whereBetween('restaurant.created_at',[$start_time,date('Y-m-d', strtotime('+1 day', strtotime($end_time)))]);
            }

            if(strlen($type) > 0){
                $query->where('type',$type);
            }
            if(strlen($is_pay) > 0){
                if($is_pay > 0){
                    $query->where('amount','>',0)->whereIn('restaurant.status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE]);
                }elseif ($is_pay == 0){
                    $query->where('amount','=',0)->whereIn('restaurant.status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE]);
                }
            } else {
                $query->whereIn('restaurant.status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE]);
            }

            if($keyword){
                $query->where(function($sql) use($keyword) {
                    $sql->where('users.name', 'like', '%'.$keyword.'%')
                        ->orWhere('users.mobile', 'like', '%'.$keyword.'%');
                });
            }
            if($office_id){
                $query->where('office_id',$office_id);
            }

            if(strlen($diet_type) > 0){
                $query->where('diet_type',$diet_type);
            }
            if(strlen($food_type) > 0){
                $query->where('food_type',$food_type);
            }

            // $query->join('collaborator','collaborator.user_id','=','restaurant.user_id')->select('restaurant.*','collaborator.name','collaborator.mobile','collaborator.avatar');

            $query->join('users','users.id','=','restaurant.user_id')->select('restaurant.*','users.name','users.mobile','users.avatar');

            $list = $query->orderByDesc('id')
                ->paginate();

            foreach ($list as $item){
                $item->images = json_decode($item->images,true);
                $item->office_name = Office::where('id',$item->office_id)->value('office_name');
            }

            return $this->success('ok', $list);
        } catch (\Exception $e) {
            Log::error('getRestaurantList:' . $e->getMessage());
            return $this->failure('查询失败');
        }
    }

    /**
     * 获取统计数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getRestaurantDataStat(Request $request){
        try {
            $date = $request->get('date');
            $diet_type = $request->get('diet_type');
            $food_type = $request->get('food_type');
            $office_id = $request->get('office_id');
            //查询总数
            $count_query = Restaurant::query();
            //按详情数
            $detail_query = Restaurant::query();
            if($date){
                $count_query->when($date, function ($query) use ($date) {
                    $query->where(function ($query) use ($date) {
                        $query->where('date', $date);
                    });
                });
                $detail_query->when($date, function ($query) use ($date) {
                    $query->where(function ($query) use ($date) {
                        $query->where('date', $date);
                    });
                });
            }


            if($office_id){
                $count_query->where('office_id',$office_id);
                $detail_query->where('office_id',$office_id);
            }

            if(strlen($diet_type) > 0){
                $count_query->where('diet_type',$diet_type);
                $detail_query->where('diet_type',$diet_type);
            }
            if(strlen($food_type) > 0){
                $count_query->where('food_type',$food_type);
                $detail_query->where('food_type',$food_type);
            }


            $count = $count_query->select(
                DB::raw('count(if(diet_type =0 and status in (1,2,3,4),1,null)) as lunch_num'),
                DB::raw('count(if(diet_type =1 and status in (1,2,3,4),1,null)) as dinner_num'),
                DB::raw('sum(if(food_type =0 and status in (1,2,3,4),num,0)) as trim_num'),
                DB::raw('sum(if(food_type =1 and status in (1,2,3,4),num,0)) as clean_num'),
                DB::raw('FORMAT(AVG(star),2) as avg_star')
            )->get();

//            $count = Restaurant::when($date, function ($query) use ($date) {
//                $query->where(function ($query) use ($date) {
//                    $query->where('date', $date);
//                });
//            })->select(
//                DB::raw('count(if(diet_type =0 and status in (1,2,3,4),1,null)) as lunch_num'),
//                DB::raw('count(if(diet_type =1 and status in (1,2,3,4),1,null)) as dinner_num'),
//                DB::raw('sum(if(food_type =0 and status in (1,2,3,4),num,0)) as trim_num'),
//                DB::raw('sum(if(food_type =1 and status in (1,2,3,4),num,0)) as clean_num'),
//                DB::raw('FORMAT(AVG(star),2) as avg_star')
//            )->get();

            //按房间号统计数据
            $detail_count = $detail_query->select(
                DB::raw('office_id'),
                DB::raw('count(if(diet_type =0 and status in (1,2,3,4),1,null)) as lunch_num'),
                DB::raw('count(if(diet_type =1 and status in (1,2,3,4),1,null)) as dinner_num'),
                DB::raw('sum(if(food_type =0 and status in (1,2,3,4),num,0)) as trim_num'),
                DB::raw('sum(if(food_type =1 and status in (1,2,3,4),num,0)) as clean_num')
            )->groupBy('office_id')
                ->get();

//            $detail_count = Restaurant::when($date, function ($query) use ($date) {
//                $query->where(function ($query) use ($date) {
//                    $query->where('date', $date);
//                });
//            })->select(
//                DB::raw('office_id'),
//                DB::raw('count(if(diet_type =0 and status in (1,2,3,4),1,null)) as lunch_num'),
//                DB::raw('count(if(diet_type =1 and status in (1,2,3,4),1,null)) as dinner_num'),
//                DB::raw('sum(if(food_type =0 and status in (1,2,3,4),num,0)) as trim_num'),
//                DB::raw('sum(if(food_type =1 and status in (1,2,3,4),num,0)) as clean_num')
//            )->groupBy('office_id')
//                ->get();
            foreach ($detail_count as $detail){
                $detail->office_name = Office::where('id',$detail->office_id)->value('office_name');
            }
            $count = $count[0] ?? [];
            return $this->success('ok', compact('count','detail_count'));
        }catch (\Exception $e) {
            Log::error('getRestaurantDataStat:' . $e->getMessage());
            return $this->failure('查询失败');
        }
    }

    /**
     * 添加厨师
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function addChefUserPlan(Request $request)
    {
        try {
            $chef_data = $request->input('chef_data');
            $date = $request->input('date');
            if (empty($chef_data) || empty($date)) {
                return $this->failure('缺少参数');
            }
//            $chef_data = json_decode($chef_data,true);

            //按照日期把人删除,然后再添加前端传的数据
            ChefPlan::where('date', $date)->delete();
            $map = $list = [];
            $map['date'] = $date;
            foreach ($chef_data as $chef) {
                $map['diet_type'] = $chef['diet_type'];
                $map['user_id'] = $chef['user_id'];
                $map['type'] = $chef['type'];
                $model = ChefPlan::create($map);
                $list[] = $model;
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            Log::error('addChefUser:' . $e->getMessage());
            return $this->failure('添加失败');
        }
    }

    /**
     * 获取厨师月度安排
     */
    public function getChefPlan(Request $request){
        try {
            $date = $request->get('date');
            if (empty($date)) {
                return $this->failure('时间不为空');
            }

            $start_date = date('Y-m-01', strtotime($date));
            $end_date = date('Y-m-d', strtotime("$start_date + 1 month -1 day"));
            $dailies = CommonService::daliy($start_date, $end_date);
            $date_arr = $chef_date = [];
            foreach ($dailies as $daily) {
                $exists = ChefPlan::where('date', $daily)->exists();
                $status = 0;
                if ($exists) {
                    $status = 1;
                    $chef_date[] = $daily;
                }
                $date_arr[] = $status;
            }

            //获取厨师人员安排
            $chef_plan = ChefPlan::whereIn('date', $chef_date)
                ->orderBy('date','asc')
                ->orderBy('type','asc')
                ->select('user_id','type','date','diet_type')
                ->get();

            $chef_by_day = [];
            $lunch_chef = [];
            $dinner_chef = [];

            foreach ($chef_plan as $item) {
                $item['name'] = Partner::where('user_id',$item->user_id)->value('name');
                $date = $item['date'];
                if (!isset($chef_by_day[$date])) {
                    $chef_plan[$date] = [];
                }
                $chef_by_day[$date]['date'] =  $date;
                // 子数组命名
                $chef_type = $item['diet_type'] == Restaurant::DIET_TYPE_LUNCH ? 'lunch_chef' : 'dinner_chef';

                if (!isset($chef_by_day[$date][$chef_type])) {
                    $chef_by_day[$date][$chef_type] = [];
                }

                // 按type分组
                if ($item['type'] == ChefPlan::CHEF_MAIN) {
                    $chef_by_day[$date][$chef_type]['main_chef'][] = $item;
                } elseif ($item['type'] == ChefPlan::CHEF_SOUS) {
                    $chef_by_day[$date][$chef_type]['sous_chef'][] = $item;
                } else {
                    $chef_by_day[$date][$chef_type]['help_chef'][] = $item;
                }
            }

            $chef_by_day = array_values($chef_by_day);

            return $this->success('ok',compact('date_arr','chef_by_day'));
        }catch (\Exception $e) {
            Log::error('getChefPlan:' . $e->getMessage());
            return $this->failure('查询失败');
        }
    }

    /**
     * 导出订餐人员数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function exportRestaurantUser(Request $request){
        try {
            $date = $request->get('date');
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $keyword = $request->get('keyword');
            $is_pay = $request->get('is_pay', '');
            $diet_type = $request->get('diet_type');
            $food_type = $request->get('food_type');
            $office_id = $request->get('office_id');
            $type = $request->get('type');
            $query = Restaurant::query();
            if($date){
                $query->when($date, function ($query) use ($date) {
                    $query->where(function ($query) use ($date) {
                        $query->where('date', $date);
                    });
                });
            }

            if(strlen($type) > 0){
                $query->where('type',$type);
            }
            if($start_time){
                $query->whereBetween('restaurant.created_at',[$start_time,date('Y-m-d', strtotime('+1 day', strtotime($end_time)))]);
            }

            if(strlen($is_pay) > 0){
                if($is_pay > 0){
                    $query->where('amount','>',0)->whereIn('restaurant.status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE]);
                }elseif ($is_pay == 0){
                    $query->where('amount','=',0)->whereIn('restaurant.status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE]);
                }
            } else {
                $query->whereIn('restaurant.status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE]);
            }

            // if($is_pay){
            //     $query->where('amount','>',0)->whereIn('restaurant.status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE]);
            // }else{
            //     $query->whereIn('restaurant.status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE,Restaurant::STATUS_CANCEL]);
            // }

            if($keyword){
                $query->where(function($sql) use($keyword) {
                    $sql->where('users.name', 'like', '%'.$keyword.'%')
                        ->orWhere('users.mobile', 'like', '%'.$keyword.'%');
                });
            }

            if($office_id){
                $query->where('office_id',$office_id);
            }

            if(strlen($diet_type) > 0){
                $query->where('diet_type',$diet_type);
            }

            if(strlen($food_type) > 0){
                $query->where('food_type',$food_type);
            }

            // $query->join('collaborator','collaborator.user_id','=','restaurant.user_id')->select('restaurant.*','collaborator.name','collaborator.mobile','collaborator.avatar');

            $query->join('users','users.id','=','restaurant.user_id')->select('restaurant.*','users.name','users.mobile','users.avatar');

            $list = $query->orderByDesc('id')
                ->get();
            if($list->isEmpty()){
                return $this->failure('暂无数据');
            }
//            return $this->success('ok',$list);
            return Excel::download(new RestaurantExport($list), 'restaurant_user.xlsx');
        }catch (\Exception $e) {
            Log::error('exportRestaurant:' . $e->getMessage());
            return $this->failure('导出失败');
        }
    }

    /**
     * 获取评价数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getEvaluateList(Request $request){
        try {
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $keyword = $request->get('keyword');
            $diet_type = $request->get('diet_type');
            $food_type = $request->get('food_type');
            $query = Restaurant::query();
            $count_query = Restaurant::query();

            if($keyword){
                $query->where(function($sql) use($keyword) {
                    $sql->where('collaborator.name', 'like', '%'.$keyword.'%')
                        ->orWhere('collaborator.mobile', 'like', '%'.$keyword.'%');
                });
            }

            if(!empty($start_time)){
                $query->whereBetween('restaurant.date',[$start_time,$end_time]);
                $count_query->whereBetween('restaurant.date',[$start_time,$end_time]);
            }
            if(strlen($diet_type) > 0){
                $query->where('restaurant.diet_type',$diet_type);
                $count_query->where('restaurant.diet_type',$diet_type);
            }
            if(strlen($food_type) > 0){
                $query->where('restaurant.food_type',$food_type);
                $count_query->where('restaurant.food_type',$food_type);
            }
            $query->join('collaborator','collaborator.user_id','=','restaurant.user_id')->select('restaurant.*','collaborator.name','collaborator.mobile','collaborator.avatar');

            $list = $query->where('restaurant.status',Restaurant::STATUS_EVALUATE)
                ->orderByDesc('restaurant.id')
                ->paginate();

            foreach ($list as $item){
                $item->images = json_decode($item->images);
            }

            //获取
            $count = $count_query->where('restaurant.status',Restaurant::STATUS_EVALUATE)
                ->selectRaw('count(*) as count')
                ->selectRaw('star')
                ->groupBy('star')
                ->pluck('count','star')->toArray();

            for ($i = 0; $i <= 5; $i++) {
                if (!isset($count[$i])) {
                    $count[$i] = 0;
                }
            }

            ksort($count);

            //本来可以按照日期把数据拿出来再塞进去,追求时间,那就循环吧
            foreach ($list as $item){
                $item->chef_user = ChefPlan::where('chef_plan.date',$item->date)
                    ->where('chef_plan.diet_type',$item->diet_type)
                    ->join('collaborator','collaborator.user_id','=','chef_plan.user_id')
                    ->select('chef_plan.date','chef_plan.diet_type','chef_plan.type','collaborator.name','collaborator.mobile','collaborator.avatar as pic')
                    ->orderBy('chef_plan.type','asc')
                    ->get();
            }
//            //获取当天厨师
//            $chef_user = ChefPlan::where('chef_plan.date',$date)
//                ->join('collaborator','collaborator.user_id','=','chef_plan.user_id')
//                ->select('chef_plan.date','chef_plan.diet_type','chef_plan.type','collaborator.name','collaborator.mobile','collaborator.avatar as pic')
//                ->get();

            return $this->success('ok',compact('list','count'));
        }catch (\Exception $e) {
            Log::error('getEvaluateList:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }

    /**
     * 导出评价
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function exportEvaluate(Request $request){
        try {
            $start_time = $request->get('start_time');
            $end_time = $request->get('end_time');
            $keyword = $request->get('keyword');
            $diet_type = $request->get('diet_type');
            $food_type = $request->get('food_type');
            $query = Restaurant::query();

            if($keyword){
                $query->where(function($sql) use($keyword) {
                    $sql->where('collaborator.name', 'like', '%'.$keyword.'%')
                        ->orWhere('collaborator.mobile', 'like', '%'.$keyword.'%');
                });
            }
            if(!empty($start_time)){
                $query->whereBetween('restaurant.date',[$start_time,$end_time]);
            }
            if(strlen($diet_type) > 0){
                $query->where('restaurant.diet_type',$diet_type);
            }
            if(strlen($food_type) > 0){
                $query->where('restaurant.food_type',$food_type);
            }
            $query->join('collaborator','collaborator.user_id','=','restaurant.user_id')->select('restaurant.*','collaborator.name','collaborator.mobile','collaborator.avatar');

            $list = $query->where('restaurant.status',Restaurant::STATUS_EVALUATE)
                ->orderByDesc('restaurant.id')
                ->get();

            if($list->isEmpty()){
                return $this->failure('暂无数据');
            }
            //本来可以按照日期把数据拿出来再塞进去,追求时间,那就循环吧
            foreach ($list as $item){
                $item->chef_user = ChefPlan::where('chef_plan.date',$item->date)
                    ->where('chef_plan.diet_type',$item->diet_type)
                    ->join('collaborator','collaborator.user_id','=','chef_plan.user_id')
//                    ->select('chef_plan.date','chef_plan.diet_type','chef_plan.type','collaborator.name','collaborator.mobile','collaborator.avatar as pic')
                    ->orderBy('chef_plan.type','asc')
                    ->pluck('collaborator.name')->toArray();
            }

            return Excel::download(new RestaurantEvaluateEXport($list), 'restaurant_evaluate.xlsx');
        }catch (\Exception $e){
            Log::error('exportEvaluate:' . $e->getMessage());
            return $this->failure('导出失败');
        }
    }


    /**
     * 导出厨师人员数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function exportChefUser(Request $request){
        try {
            $keyword = $request->get('keyword');
            $status = $request->get('status');
            $list = ChefUser::query()->when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('partners.name', 'like', "%{$keyword}%");
                    $query->where('partners.mobile', 'like', "%{$keyword}%");
                });
            })->when($status !== null,function ($query) use ($status) {
                $query->where('partners.status',$status);
            })->join('partners','partners.id','=','chef_user.partner_id')
                ->select('partners.name','partners.mobile','partners.user_id','partners.created_at')
                ->get();

            if($list->isEmpty()){
                return $this->failure('暂无数据');
            }
            return Excel::download(new ChefUserExport($list), 'chef_user.xlsx');
        }catch (\Exception $e){
            Log::error('exportChefUser:' . $e->getMessage());
            return $this->failure('导出失败');
        }
    }

    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getChefPlanList(Request $request){
        try {
            $keyword = $request->get('keyword');
            $type = $request->get('type');
            $start_date = $request->get('start_date');
            $end_date = $request->get('end_date');
            $is_export = $request->get('is_export');
            $query = ChefPlan::query();

            if($start_date){
                $query->where('chef_plan.date','>=',$start_date)->where('chef_plan.date','<=',$end_date);
            }

            $query->when($keyword, function ($sql) use ($keyword) {
                $sql->where('collaborator.name', 'like', "%{$keyword}%")->orWhere('collaborator.mobile', 'like', "%{$keyword}%");
            });

            $query->when($type !== null,function ($sql) use ($type) {
                $sql->where('chef_plan.type',$type);
            });

            $query->join('collaborator','collaborator.user_id','=','chef_plan.user_id')
                ->select('collaborator.name','collaborator.avatar','collaborator.mobile','collaborator.user_id',
                    'chef_plan.date','chef_plan.diet_type','chef_plan.type','chef_plan.created_at')->orderByDesc('chef_plan.id');

            if($is_export){
                $list = $query->get();
                if($list->isEmpty()){
                    return $this->failure('暂无数据');
                }
                return Excel::download(new ChefPlanListExport($list), 'chef_plan.xlsx');
            }
            $list = $query->paginate();
            return $this->success('ok',$list);
        }catch (\Exception $e){
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 删除餐饮订餐记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function deleteRestaurantLog(Request $request){
        try {
            $id = $request->get('id');
            Restaurant::where('id',$id)->delete();
            return $this->success('ok');
        }catch (\Exception $e){
            return $this->failure($e->getMessage());
        }
    }

    public function getRestaurantDate(Request $request){
        try {
            $month = $request->get('month',date('Y-m'));
            $calendar = RestaurantDate::where('date','like',$month.'%')->pluck('status');
            return $this->success('ok',$calendar);
        }catch (\Exception $e){
            return $this->failure($e->getMessage());
        }
    }

    public function setRestaurantDate(Request $request){
        try {
            $date = $request->input("date");
            $status = $request->input('status');

            RestaurantDate::where('date',$date)->update(['status'=>$status]);
            return $this->success('ok');
        }catch (\Exception $e){
            return $this->failure($e->getMessage());
        }
    }

    public function getCanRestaurantUser(Request $request){
        try {
            $keyword = $request->get('keyword');
            $office_name = $request->input("office_name");
            $is_export = $request->get('is_export');
            $query = User::query()->whereHas("station");
            // $query = $query->when($keyword,function ($sql) use ($keyword){
            //     $sql->where('users.name','like','%'.$keyword.'%')->orWhere('users.mobile','like','%'.$keyword.'%');
            // });

            
            // $query =$query->join('agent_users','agent_users.user_id','=','users.id');
            // $query =$query->where('agent_users.can_restaurant',AgentUser::CanRestaurant);
            if ($keyword) {
                $query = $query->where(function($sql) use($keyword) {
                    $sql->where('users.name','like','%'.$keyword.'%')->orWhere('users.mobile','like','%'.$keyword.'%');
                });
            }

            if ($office_name) {
                $query = $query->whereHas("office", function($sql) use($office_name) {
                    $sql->where("office_name", $office_name);
                });
            }
            

            $query =$query/*->select('users.*','agent_users.can_restaurant')*/->orderByDesc("users.id");
            if($is_export){
                $list = $query->get();
            }else{
                $list = $query->paginate();
            }

            foreach ($list as $item){
                $item->office_name = '';
                $station = Station::where('user_id',$item->id)->first();
                if(!$station){
                    continue;
                }
                $item->office_name = Office::where('id',$station->office_id)->value('office_name');
                $item->office_id = $station->office_id;
            }

            if($is_export){
                return Excel::download(new CanRestaurantExport($list), 'can_restaurant.xlsx');
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            return $this->failure($e->getMessage());
        }
    }

    public function addCanRestaurantUser(Request $request){
        DB::beginTransaction();
        try {
            $user_id = $request->input('user_id');
            $office_id = $request->input('office_id');
            AgentUser::updateOrCreate(['user_id'=>$user_id],['can_restaurant'=>AgentUser::CanRestaurant]);
            Station::updateOrCreate(['user_id'=>$user_id],['office_id'=>$office_id,'number'=>Station::NO_FIXED_STATION]);
            DB::commit();
            return $this->success('ok');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 设置不可订餐
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function deleteCanRestaurantUser(Request $request){
        try {
            $user_id = $request->input('user_id');
            AgentUser::where('user_id',$user_id)->update(['can_restaurant'=>AgentUser::NotCanRestaurant]);
            Station::where("user_id", $user_id)->delete();
            return $this->success('ok');
        }catch (\Exception $e){
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 更新用户办公室
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function updateUserOffice(Request $request){
        try {
            $user_id = $request->input('user_id');
            $office_id = $request->input('office_id');
            $station = Station::where('user_id',$user_id)->first();
            if($station){
                $station->office_id = $office_id;
                $station->save();
            }else{
                Station::create(['office_id'=>$office_id,'user_id'=>$user_id,'number'=>Station::NO_FIXED_STATION]);
            }
            return $this->success('ok');
        }catch (\Exception $e){
            return $this->failure($e->getMessage());
        }
    }
}