<?php

namespace App\Http\Controllers\H5;

use App\Facades\CommonService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\SendTemplateNotice;
use App\Models\ActivityOrder;
use App\Models\AgentOrder;
use App\Models\ChefPlan;
use App\Models\ChefUser;
use App\Models\Collaborator;
use App\Models\Office;
use App\Models\Partner;
use App\Models\Restaurant;
use App\Models\RestaurantDate;
use App\Models\RestaurantOrder;
use App\Models\RestaurantOrderRefund;
use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class RestaurantController 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 getRestaurantLog(Request $request)
    {
        try {
            $date = $request->input('date');
            if (empty($date)) {
                return $this->failure('时间不为空');
            }

            $user = auth()->user();
//            $partner = Partner::where('user_id',$user->id)->first();
            $partner = Collaborator::where('user_id',$user->id)
                ->where('status',Collaborator::STATUS_PASS)
                ->first();
            $flag = false;
            if(!$partner){
                $flag = true;
            }

            //查询餐饮日期
            $start_date = date('Y-m-01', strtotime($date));
            $end_date = date('Y-m-d', strtotime("$start_date + 1 month -1 day"));
            $month = date('Y-m', strtotime($date));
            $restaurant_date = RestaurantDate::where('date','like',$month.'%')->get();
            $date_arr = [];
            if(!$restaurant_date->isEmpty()){
                foreach ($restaurant_date as $val){
                    $status = $val->status;
                    $exists = Restaurant::where('user_id', $user->id)->where('date', $val->date)
                        ->where('status','<>',Restaurant::STATUS_RESERVE)->exists();
                    if ($exists) {
                        $status = 1;
                    }
                    $date_arr[] = $status;
                }
            }else{
                $dailies = CommonService::daliy($start_date, $end_date);
                foreach ($dailies as $daily) {
                    $exists = Restaurant::where('user_id', $user->id)->where('date', $daily)->where('status','<>',Restaurant::STATUS_RESERVE)->exists();
                    $status = 2;
                    if ($exists) {
                        $status = 1;
                    }
                    $date_arr[] = $status;
                }
            }
            $restaurant = Restaurant::where('user_id', $user->id)
                ->where('status','<>',Restaurant::STATUS_RESERVE)
                ->whereBetween('date', [$start_date, $end_date])
                ->select('id','date','diet_type','food_type','num','status','office_id','amount')
                ->orderBy('date', 'asc')
                ->orderBy('diet_type','asc')
                ->orderByDesc('id')
                ->get()
                ->toArray();
            $log = [];
            foreach ($restaurant as $item){
                $item['office_name'] = '';
                if($item['office_id']){
                    $item['office_name'] = Office::where('id',$item['office_id'])->value('office_name');
                }
                $date = $item['date'];
                //查看午餐是否购买过
                $lunch = Restaurant::where('user_id',$user->id)->where('date',$date)->where('diet_type',Restaurant::DIET_TYPE_LUNCH)
                    ->whereIn('status',Restaurant::STATUS_ARR)
                    ->exists();
                //查看晚餐是否购买过
                $dinner = Restaurant::where('user_id',$user->id)->where('date',$date)->where('diet_type',Restaurant::DIET_TYPE_DINNER)
                    ->whereIn('status',Restaurant::STATUS_ARR)
                    ->exists();

                $log[$item['date']]['list'][] = $item;
                $log[$item['date']]['date'] = $date;

                $log[$item['date']]['have_lunch'] = $lunch;
                $log[$item['date']]['have_dinner'] = $dinner;
            }
            $logs = array_values($log);

            //获取开关状态,如果没设置，则查看数据库，有订餐，默认开启
            $switch_status = Redis::hget(Restaurant::REDIS_SEND_SWITCH,$user->id);
            if($switch_status === false){
                $exists = Restaurant::where('status','>',0)->where('user_id',$user->id)->exists();
                $switch_status = 0;
                if($exists){
                    $switch_status = 1;
                }
            }
            $switch_status = intval($switch_status);

            $lunch_reserve_time = Restaurant::LUNCH_RESERVE_TIME;
            $dinner_reserve_time = Restaurant::DINNER_RESERVE_TIME;

            return $this->success('ok', compact('date_arr', 'logs','flag','switch_status','lunch_reserve_time','dinner_reserve_time'));
        } catch (\Exception $e) {
            Log::error('getRestaurantLog:' . $e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     *按日期获取某一天订餐情况
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getRestaurantDetail(Request $request)
    {
        try {
            $id = $request->get('id');
            if (empty($id)) return $this->failure('日期不为空');
            $restaurant = Restaurant::where('id', $id)->first();
            $restaurant->images = json_decode($restaurant->images,true);
            return $this->success('ok', $restaurant);
        } catch (\Exception $e) {
            Log::error('getRestaurantDetail:' . $e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 申请订餐
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function addRestaurant(Request $request)
    {
        DB::beginTransaction();
        try {
            $user = auth()->user();
            $diet_type = $request->get('diet_type');
            if (empty($diet_type)) return $this->failure('请选择晚餐或午餐');
//            $diet_type = json_decode($diet_type,true);

            $office_id = $request->get('office_id');
            if (empty($office_id)) return $this->failure('请选择办公室');

            $office_name = Office::where('id',$office_id)->value('office_name');

            $date = $request->get('date');
            if(empty($date)) return $this->failure('请选择日期');
            $day_of_week = date('w', strtotime($date));
//            if($day_of_week == 0){
//                return $this->failure('周日不可订餐');
//            }
            $day = date('Y-m-d');
            //如果时间是当天
            $flag = false;
            if($date == $day){
                $minute = date('H:i');
                foreach ($diet_type as $diet){
                    if($diet == Restaurant::DIET_TYPE_LUNCH && $minute > Restaurant::LUNCH_RESERVE_TIME){
                        $flag = true;
                    }
                    if($diet == Restaurant::DIET_TYPE_DINNER && $minute > Restaurant::DINNER_RESERVE_TIME){
                        $flag = true;
                    }
                }
            }
            //如果时间过了,弹出提示
            if($flag){
                return $this->failure('已超过约定时间');
            }

            if($date < $day){
                return $this->failure('日期不能小于今天');
            }

            $food_type = $request->get('food_type');
            if (strlen($food_type) == 0) return $this->failure('请选择订餐类型');

            $lunch_num = $request->input('lunch_num',0);
            $dinner_num = $request->input('dinner_num',0);
            if (empty($lunch_num) && empty($dinner_num)) {
                return $this->failure('请至少订一份');
            }

            //一天某一餐 免费一份
            $pay_lunch_num = $lunch_num;
            $pay_dinner_num = $dinner_num;
            //查看午餐是否购买过
            $lunch = Restaurant::where('user_id',$user->id)->where('date',$date)->where('diet_type',Restaurant::DIET_TYPE_LUNCH)
                ->whereIn('status',Restaurant::STATUS_ARR)
                ->exists();

            if ($lunch_num && !$lunch) {
                $pay_lunch_num = $lunch_num - 1;
            }
            //查看晚餐是否有记录，有记录继续购买需要付费
            $dinner = Restaurant::where('user_id',$user->id)->where('date',$date)->where('diet_type',Restaurant::DIET_TYPE_DINNER)
                ->whereIn('status',Restaurant::STATUS_ARR)
                ->exists();
            if ($dinner_num && !$dinner) {
                $pay_dinner_num = $dinner_num - 1;
            }

            $num = $pay_lunch_num + $pay_dinner_num;

            $pay_map = [
                'user_id' => $user->id,
                'trade_no' => CommonService::getTradeNO(),
                'status'=> Restaurant::STATUS_RESERVE,
                'num' => $num,
                'price' => $num * RestaurantOrder::PRICE,
                'amount' => $num * RestaurantOrder::PRICE,
            ];
            $model = RestaurantOrder::create($pay_map);

            $map = $list= [];
            $map['user_id'] = $user->id;
            $map['order_id'] = $model->id;
            $map['date'] = $date;

            $map['office_id'] = $office_id;
            //每一餐,每一份都生成一条记录,别问为什么,问就是产品要求
            $diet_type_name = "午餐";
            $food_type_name = '装修日';
            if($food_type == Restaurant::FOOD_TYPE_CLEAN){
                $food_type_name = "清洁日";
            }
            foreach ($diet_type as $val) {
                $map['diet_type'] = $val;
                $map['food_type'] = $food_type;
                if ($val == RestaurantOrder::DIET_TYPE_LUNCH) {
                    //如果提交数量大于实际数量,说明有一份免费,插入一条记录
                    if($lunch_num > $pay_lunch_num){
                        $map['amount'] = 0;
                        $map['num'] = 1;
                        $map['status'] = 1;
                        $model = Restaurant::create($map);
                        $model->office_name = $office_name;
                        //返回给前端
                        $list[] = $model;
                    }
                    //遍历需要付费订单,每次都插入
                    for ($i = 1;$i<=$pay_lunch_num;$i++){
                        $map['amount'] = RestaurantOrder::PRICE;;
                        $map['num'] = 1;
                        $map['status'] = 0;
                        $model = Restaurant::create($map);
                        $model->office_name = $office_name;
                        //返回给前端
                        $list[] = $model;
                    }
                } elseif ($val == RestaurantOrder::DIET_TYPE_DINNER) {
                    $diet_type_name = "晚餐";
                    //如果提交数量大于实际数量,说明有一份免费,插入一条记录
                    if($dinner_num > $pay_dinner_num){
                        $map['amount'] = 0;
                        $map['num'] = 1;
                        $map['status'] = 1;
                        $model = Restaurant::create($map);
                        $model->office_name = $office_name;
                        //返回给前端
                        $list[] = $model;
                    }
                    //遍历需要付费订单,每次都插入
                    for ($i = 1;$i<=$pay_dinner_num;$i++){
                        $map['amount'] = RestaurantOrder::PRICE;;
                        $map['num'] = 1;
                        $map['status'] = 0;
                        $model = Restaurant::create($map);
                        $model->office_name = $office_name;
                        //返回给前端
                        $list[] = $model;
                    }
                }

            }

            $config = [];
            if($pay_map['amount']){
                $callback = config('app.url') . '/api/h5/notify/restaurant/orders/' . $pay_map['trade_no'];
                $appId = config('wechat.payment.sub_official_app_id');
//                $config = WechatService::mpPay($pay_map['trade_no'], 'oHGap6F1HR-5q-JdRKrgb6DwztWQ', $pay_map['amount'], $pay_map['desc'], $callback, $appId);
                $config = WechatService::mpPay($pay_map['trade_no'], $user->officialWechat->openid, $pay_map['amount'], $pay_map['desc']??'用户订餐', $callback, $appId);
            }

            DB::commit();

            //查看午餐是否购买过
            $have_lunch = Restaurant::where('user_id',$user->id)->where('date',$date)->where('diet_type',Restaurant::DIET_TYPE_LUNCH)
                ->whereIn('status',Restaurant::STATUS_ARR)
                ->exists();
            //查看晚餐是否有记录，有记录继续购买需要付费
            $have_dinner = Restaurant::where('user_id',$user->id)->where('date',$date)->where('diet_type',Restaurant::DIET_TYPE_DINNER)
                ->whereIn('status',Restaurant::STATUS_ARR)
                ->exists();

            $params = [
                'touser'=>$user->officialWechat->openid,
                'template_id'=>config('wechat.tpls.success_restaurant'),
                'url'=>config('app.url').'/order/#/cateringApplyFor',
                'data'=>[
                    'time28' => ['value'=>$date],
                    'thing16' => ['value'=>$diet_type_name."/".$food_type_name],
                    'number10' => ['value'=>$lunch_num+$dinner_num],
                    'thing29' => ['value'=>$office_name],
                    'time4' => ['value'=>date('Y-m-d H:i:s')],
                ]
            ];
            Log::info('addRestaurant:'.json_encode($params));
            SendTemplateNotice::dispatch($params)->onQueue('health');

            return $this->success('ok', compact( 'list', 'config','pay_map','have_dinner','have_lunch'));
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('addRestaurant:' . $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 addOtherRestaurant(Request $request){
        DB::beginTransaction();
        try {
            $user = auth()->user();
            $diet_type = $request->get('diet_type');
            if (strlen($diet_type) == 0) return $this->failure('请选择晚餐或午餐');

            $desc = $request->get('desc');
            $office_id = $request->get('office_id');
            if (empty($office_id)) return $this->failure('请选择办公室');

            $office_name = Office::where('id',$office_id)->value('office_name');

            $date = $request->get('date');
            if(empty($date)) return $this->failure('请选择日期');
            $day_of_week = date('w', strtotime($date));
//            if($day_of_week == 0){
//                return $this->failure('周日不可订餐');
//            }
            $day = date('Y-m-d');

            if($date < $day){
                return $this->failure('日期不能小于今天');
            }

            $food_type = $request->get('food_type');
            if (strlen($food_type) == 0) return $this->failure('请选择订餐类型');

            $free_num = $request->input('free_num',0);
            $pay_num = $request->input('pay_num',0);
            if (empty($free_num) && empty($pay_num)) {
                return $this->failure('请至少订一份');
            }

            $pay_map = [
                'user_id' => $user->id,
                'trade_no' => CommonService::getTradeNO(),
                'status'=> Restaurant::STATUS_RESERVE,
                'num' => $pay_num,
                'price' => $pay_num * RestaurantOrder::PRICE,
                'amount' => $pay_num * RestaurantOrder::PRICE,
                'desc' => '用户:' . $user->name . '订餐',
            ];
            $model = RestaurantOrder::create($pay_map);

            $map = $list= [];
            $map['user_id'] = $user->id;
            $map['order_id'] = $model->id;
            $map['date'] = $date;
            $map['office_id'] = $office_id;
            $map['diet_type'] = $diet_type;
            $map['food_type'] = $food_type;
            $map['desc'] = $desc;

            //每一餐,每一份都生成一条记录,别问为什么,问就是产品要求
            //遍历免费订单,每次都插入
            for ($i = 1;$i<=$free_num;$i++){
                $map['amount'] = 0;
                $map['num'] = 1;
                $map['status'] = Restaurant::STATUS_PAY;
                $map['type'] = Restaurant::TYPE_HELP_OTHER;
                $model = Restaurant::create($map);
                $model->office_name = $office_name;
                //返回给前端
                $list[] = $model;
            }
            //遍历需要付费订单,每次都插入
            for ($i = 1;$i<=$pay_num;$i++){
                $map['amount'] = RestaurantOrder::PRICE;;
                $map['num'] = 1;
                $map['status'] = Restaurant::STATUS_RESERVE;
                $map['type'] = Restaurant::TYPE_HELP_OTHER;
                $model = Restaurant::create($map);
                $model->office_name = $office_name;
                //返回给前端
                $list[] = $model;
            }

            $config = [];
            if($pay_map['amount']){
                $callback = config('app.url') . '/api/h5/notify/restaurant/orders/' . $pay_map['trade_no'];
                $appId = config('wechat.payment.sub_official_app_id');
//                $config = WechatService::mpPay($pay_map['trade_no'], 'oHGap6F1HR-5q-JdRKrgb6DwztWQ', $pay_map['amount'], $pay_map['desc'], $callback, $appId);
                $config = WechatService::mpPay($pay_map['trade_no'], $user->officialWechat->openid, $pay_map['amount'], $pay_map['desc'], $callback, $appId);
            }

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

    /**
     * 订单回调
     * @param $trade_no
     * @return bool
     * @throws \Exception
     */
    public function notifyOrder($trade_no)
    {
        try {
            $order = RestaurantOrder::where('trade_no', $trade_no)->first();
            if (empty($order)) throw new \Exception("订单不存在");
            $result = WechatService::mpPaid($trade_no);
            if (empty($result)) {//成功
                DB::beginTransaction();
                RestaurantOrder::where("id", $order->id)->update(['status' => 1]);
                Restaurant::where('order_id', $order->id)->update(['status' => 1]);
                DB::commit();
                return $this->success('ok');
            } else {//失败
                Log::debug($trade_no . '订单查询异常: 支付回调失败' . $result);
                return $this->failure('支付失败');
            }
        } catch (\Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 通过订单号
     */
    public function getOrderDetail(Request $request){
            $trade_no = $request->get('trade_no');
            if(empty($trade_no)){
                return $this->failure('订单号不为空');
            }
            //判断订单号
            $res = explode('_', $trade_no);
            switch ($res[0]) {
                case "saas": //福恋saas
                    $list = $this->getSaasOrderList($trade_no);
                    Log::info($list);
                    break;
                case "activity":
                    $list = $this->getActivityOrderList($trade_no);
                    break;
                case "AA":
                    $list = $this->getOAActivityOrderList($trade_no);
                    break;
                case "agent":
                    $list = $this->getAgentOrderList($trade_no);
                    break;
                default :
                    $list = $this->getOrderList($trade_no);
            }
            return $this->success('ok',$list);

    }

    public function getAgentOrderList($trade_no)
    {
        $order = AgentOrder::where('trade_no', $trade_no)->first();
        if (empty($order)) throw new \Exception("订单不存在");
        $shop_info = $order->shop_info;
        $list = [
            'name'=>$shop_info['title'],
            'sku'=>$shop_info['sku']['name']??"",
            'id'=>$order->id,
            'num'=>$order->num,
            'price'=>$order->price,
            'order_type'=>'agent_shop',
            'date'=>$order->created_at->toDateTimeString(),
        ];
        return $list;
    }

    public function getOAActivityOrderList($trade_no)
    {
        config(['database.connections.mysql.prefix' => '']);
        $order = DB::table('oa_agent_activity_order')->where('trade_no', $trade_no)->first();
        $sku = json_decode($order->sku);
        $activity = json_decode($order->activity_info);
        $list = [
            'name'=>$activity?$activity->title:'',
            'sku'=>$sku?$sku->name:'',
            'id'=>$order->id,
            'num'=>1,
            'price'=>$order->price,
            'order_type'=>'oa_activity',
            'date'=>date("Y-m-d H:i:s", $order->created_at),
        ];
        return $list;
    }


    public function getActivityOrderList($trade_no)
    {
        $order = ActivityOrder::with('activity')->where('trade_no', $trade_no)->first();
        $list = [
            'name'=>$order->activity->title,
            'sku'=>$order->sku,
            'id'=>$order->id,
            'num'=>$order->num,
            'price'=>$order->amount,
            'order_type'=>'activity',
            'date'=>$order->created_at->toDateTimeString(),
        ];
        return $list;
    }

    public function getSaasOrderList($trade_no)
    {
        $url = config('app.shop_url')."orders/{$trade_no}/receipt";
        $res = $this->getData($url);
        if ($res['code'] == 1) return $this->failure($res['message']);
        $data = $res['data'];
        return $data;
    }
    public function getData($url){
        $headers = [
            'Key' => config('app.shop_key'), // 自定义头部参数（示例）
        ];
        $client = new Client();
        $response = $client->get($url, [
            'headers' => $headers,
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }

    public function getOrderList($trade_no)
    {
        $order = RestaurantOrder::where('trade_no', $trade_no)->first();
        if (empty($order)) throw new \Exception("订单不存在");
        //查看当前订单号相关数据
        $restaurant = Restaurant::where('order_id',$order->id)->get();
        $diet = '';
        $num = 0;
        $date = '';
        foreach ($restaurant as $item){
            if($item->diet_type == Restaurant::DIET_TYPE_LUNCH){
                $diet = $diet.'午餐';
            }
            if($item->diet_type == Restaurant::DIET_TYPE_DINNER){
                $diet = $diet.'+晚餐';
            }
            $num += $item->num;
            $date = $item->date;
        }
        $list = [
            'diet' => $diet,
            'num' => $num,
            'amount' => $order->amount,
            'date' => $date,
            'order_type' => 'repast',
        ];
        $list['flag'] = 0;
        if($order->desc){
            $list['flag'] = 1;
        }
        return $list;
    }

    /**
     * 取消订餐
     * @param Request $request
     */
    public function cancelRestaurant(Request $request){
        DB::beginTransaction();
        try {
            $user = auth()->user();
            $id = $request->get('id');
            $restaurant = Restaurant::where('id',$id)->whereIn('status',[0,1])->first();
            if(!$restaurant){
                return $this->failure('该订单不存在或订单状态不正确');
            }
            $restaurant_order = RestaurantOrder::where('id',$restaurant->order_id)->first();
            if(!$restaurant_order){
                return $this->failure('订单查询失败');
            }

            $map = [];
            //已支付则退款,为支付则直接取消
            if($restaurant_order->status == 1 && $restaurant->amount > 0){
                $map = [
                    'user_id' => $user->id,
                    'restaurant_id' => $restaurant->id,
                    'trade_no' => $restaurant_order->trade_no,
                    'refund_trade_no' => get_refund_trade_no(),
                    'total_amount' => $restaurant_order->amount,
                    'refund_amount' => $restaurant->amount,
                ];

                //发起退款
                $callback = config('app.url') . '/api/h5/notify/restaurant/orders/refund/'.$map['refund_trade_no'];
                $result = WechatService::refund($map['trade_no'],$map['refund_trade_no'],$map['total_amount'],$map['refund_amount'],$callback);
                if (!$result['status']) return $this->failure($result['msg']);
                if($result['status']){
                    RestaurantOrderRefund::create($map);
                }
            }
            $restaurant->status = Restaurant::STATUS_CANCEL;
            $restaurant->save();

            DB::commit();

            $date = $restaurant->date;
            //查看午餐是否购买过
            $have_lunch = Restaurant::where('user_id',$user->id)->where('date',$date)->where('diet_type',Restaurant::DIET_TYPE_LUNCH)
                ->whereIn('status',Restaurant::STATUS_ARR)
                ->exists();
            //查看晚餐是否有记录，有记录继续购买需要付费
            $have_dinner = Restaurant::where('user_id',$user->id)->where('date',$date)->where('diet_type',Restaurant::DIET_TYPE_DINNER)
                ->whereIn('status',Restaurant::STATUS_ARR)
                ->exists();

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

    /**
     * 退款回调
     * @param Request $request
     */
    public function notifyRefund($refund_trade_no){
        DB::beginTransaction();
        try {
            if(!$refund_trade_no){
                return $this->failure('退款订单号不能为空');
            }
            $refund_order = RestaurantOrderRefund::where('refund_trade_no',$refund_trade_no)->first();
            if(!$refund_order){
                return $this->failure('退款订单不存在');
            }
            //避免多次回调
            if($refund_order->status == 1){
                return $this->success('ok');
            }
            $result = WechatService::orderRefunded($refund_trade_no);

            $restaurant = Restaurant::where('id',$refund_order->restaurant_id)->first();
            $restaurant->status = Restaurant::STATUS_CANCEL;

            if(!$result['status']){
                $restaurant->status = Restaurant::STATUS_PAY;
                return $this->failure('支付失败');
            }


            $restaurant->save();

            $refund_order->status = 1;
            $refund_order->save();

            DB::commit();
            return $this->success('ok');
        }catch (\Exception $e){
            DB::rollBack();
            Log::error('refundCallback:' . $e->getMessage());
            return $this->failure('支付失败');
        }
    }

    /**
     * 订单评价
     * @param Request $request
     */
    public function evaluate(Request $request){
        try {
            $id = $request->get('id');
            if(empty($id)) return $this->failure('id不为空');

            $restaurant = Restaurant::where('id',$id)->first();

            if($restaurant->status != Restaurant::STATUS_TAKE){
                return $this->failure('请先取餐');
            }

            $remark = $request->get('remark');
            if(!$remark) return $this->failure('请输入评价');
            $restaurant->remark = $remark;

            $star = $request->get('star');
            if($star) $restaurant->star = $star;

            $images = $request->get('images');
            if($images) $restaurant->images = json_encode($images);

            $restaurant->status = Restaurant::STATUS_EVALUATE;

            $restaurant->save();
            return $this->success('ok');
        }catch (\Exception $e){
            Log::error('evaluate:' . $e->getMessage());
            return $this->failure('评价失败');
        }
    }

    /**
     * 获取厨师做饭安排,看不懂,根本看不懂,有缘人祝你好运
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getChefCookPlan(Request $request){
        try {
            $date = $request->get('date');
            if (empty($date)) {
                return $this->failure('时间不为空');
            }

            $user = auth()->user();
            $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('user_id', $user->id)->where('date', $daily)->exists();
                $status = 0;
                if ($exists) {
                    $status = 1;
                    $chef_date[] = $daily;
                }
                $date_arr[] = $status;
            }
            //获取整月的订餐数据
            $restaurant = Restaurant::whereIn('date', $chef_date)
                ->whereIn('status',Restaurant::STATUS_ARR)
                ->orderBy('date', 'asc')
                ->select('id','user_id','date','diet_type','food_type','num','status','office_id')
                ->orderByDesc('id')
                ->get();

            $log = [];
            foreach ($restaurant as $value){
                $user_info = User::where('id',$value->user_id)->first();
                $value->office_name = Office::where('id',$value->office_id)->value('office_name');
                $value->name = $user_info->name??'';
                $value->mobile = $user_info->mobile??'';
                $value->avatar = $user_info->avatar??'';
                $log[$value['date']]['date'] = $value['date'];
                //初始化数组值
                if(!isset($log[$value['date']]['lunch_food_clean_num'])){
                    $log[$value['date']]['lunch_food_clean_num'] = 0;
                }
                if(!isset($log[$value['date']]['lunch_food_trim_num'])){
                    $log[$value['date']]['lunch_food_trim_num'] = 0;
                }
                if(!isset($log[$value['date']]['dinner_food_clean_num'])){
                    $log[$value['date']]['dinner_food_clean_num'] = 0;
                }
                if(!isset($log[$value['date']]['dinner_food_trim_num'])){
                    $log[$value['date']]['dinner_food_trim_num'] = 0;
                }

                //初始化订餐人员数组
//                if(!isset($log[$value['date']]['dinner_user_list'])){
//                    $log[$value['date']]['dinner_user_list'] = [];
//                }
//                if(!isset($log[$value['date']]['lunch_user_list'])){
//                    $log[$value['date']]['lunch_user_list'] = [];
//                }

                //初始化厨师数组
                if(!isset($log[$value['date']]['lunch_chef_list'])){
                    $log[$value['date']]['lunch_chef_list'] = [];
                }

                if(!isset($log[$value['date']]['dinner_chef_list'])){
                    $log[$value['date']]['dinner_chef_list'] = [];
                }

                if(!isset($log[$value['date']]['dinner_detail_count'][$value->office_id])){
                    $log[$value['date']]['dinner_detail_count'][$value->office_id] = [];
                    $log[$value['date']]['dinner_detail_count'][$value->office_id]['office_id'] = $value->office_id;
                    $log[$value['date']]['dinner_detail_count'][$value->office_id]['office_name'] = $value->office_name;
                    $log[$value['date']]['dinner_detail_count'][$value->office_id]['food_trim_num'] = 0;
                    $log[$value['date']]['dinner_detail_count'][$value->office_id]['food_clean_num'] = 0;
                }

                if(!isset($log[$value['date']]['lunch_detail_count'][$value->office_id])){
                    $log[$value['date']]['lunch_detail_count'][$value->office_id] = [];
                    $log[$value['date']]['lunch_detail_count'][$value->office_id]['office_id'] = $value->office_id;
                    $log[$value['date']]['lunch_detail_count'][$value->office_id]['office_name'] = $value->office_name;
                    $log[$value['date']]['lunch_detail_count'][$value->office_id]['food_trim_num'] = 0;
                    $log[$value['date']]['lunch_detail_count'][$value->office_id]['food_clean_num'] = 0;
                }

                if($value->diet_type == Restaurant::DIET_TYPE_DINNER){
                    //晚餐装修日,清洁日总数分别是多少
                    if($value->food_type == Restaurant::FOOD_TYPE_TRIM){
                        $log[$value['date']]['dinner_food_trim_num'] += $value->num;
                        $log[$value['date']]['dinner_detail_count'][$value->office_id]['food_trim_num'] += $value->num;
                    }else{
                        $log[$value['date']]['dinner_food_clean_num'] += $value->num;
                        $log[$value['date']]['dinner_detail_count'][$value->office_id]['food_clean_num'] += $value->num;
                    }
//                    $log[$value['date']]['dinner_user_list'][] = $value;
                }else{
                    //午餐装修日,清洁日总数分别是多少
                    if($value->food_type == Restaurant::FOOD_TYPE_TRIM){
                        $log[$value['date']]['lunch_food_trim_num'] += $value->num;
                        $log[$value['date']]['lunch_detail_count'][$value->office_id]['food_trim_num'] += $value->num;
                    }else{
                        $log[$value['date']]['lunch_food_clean_num'] += $value->num;
                        $log[$value['date']]['lunch_detail_count'][$value->office_id]['food_clean_num'] += $value->num;
                    }
//                    $log[$value['date']]['lunch_user_list'][] = $value;
                }

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

            foreach ($chef_plan as $chef){
                $chef_info = Partner::where('user_id',$chef->user_id)->first();
                $chef->name = $chef_info->name??'';
                $chef->mobile = $chef_info->mobile??'';
                $chef->avatar = $chef_info->pic??'';
                //处理厨师数组
                $date_time = $chef['date'];

                //如果没有订餐,先设置厨师,初始化字段
                if(!isset($log[$date_time])){
                    $log[$date_time]['date'] = $date_time;
                    $log[$date_time]['lunch_food_clean_num'] = 0;
                    $log[$date_time]['lunch_food_trim_num'] = 0;
                    $log[$date_time]['dinner_food_clean_num'] = 0;
                    $log[$date_time]['dinner_food_trim_num'] = 0;
                    $log[$date_time]['dinner_user_list'] = [];
                    $log[$date_time]['lunch_user_list'] = [];
                    $log[$date_time]['lunch_detail_count'] = [];
                    $log[$date_time]['dinner_detail_count'] = [];
                }
                $log[$date_time]['lunch_detail_count'] = array_values($log[$date_time]['lunch_detail_count']);
                $log[$date_time]['dinner_detail_count'] = array_values($log[$date_time]['dinner_detail_count']);

                $diet_type = $chef['diet_type'];
                $chef_diet_type = ChefPlan::where('date',$chef->date)->where('user_id',$user->id)->distinct()->pluck('diet_type')->toArray();
                // 将chef信息添加到对应的数组中
                if ($diet_type == Restaurant::DIET_TYPE_LUNCH) {
                    $log[$date_time]['lunch_chef_list'][] = $chef;
                } elseif ($diet_type == Restaurant::DIET_TYPE_DINNER) {
                    $log[$date_time]['dinner_chef_list'][] = $chef;
                }

                //如果当前用户不是这一餐的工作人员,信息不可查看
                if(!in_array(Restaurant::DIET_TYPE_LUNCH,$chef_diet_type)){
                    $log[$date_time]['lunch_chef_list'] = [];
                    $log[$date_time]['lunch_user_list'] = [];
                    $log[$date_time]['lunch_detail_count'] = [];
                    $log[$date_time]['lunch_food_clean_num'] = 0;
                    $log[$date_time]['lunch_food_trim_num'] = 0;
                }elseif(!in_array(Restaurant::DIET_TYPE_DINNER,$chef_diet_type)){
                    $log[$date_time]['dinner_chef_list'] = [];
                    $log[$date_time]['dinner_user_list'] = [];
                    $log[$date_time]['dinner_detail_count'] = [];
                    $log[$date_time]['dinner_food_clean_num'] = 0;
                    $log[$date_time]['dinner_food_trim_num'] = 0;
                }

            }
            $logs = array_values($log);

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

    /**
     * 获取餐饮厨师做饭计划
     */
    public function getChefPlan(Request $request){
        try {
            $date = $request->get('date');
            if (empty($date)) {
                return $this->failure('时间不为空');
            }

            $user = auth()->user();
            $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) {
                //判断某些用户固定展示
                if(in_array($user->id,[197,304,157])){
                    $exists = Restaurant::where('date', $daily)->exists();
                    $status = 0;
                    if ($exists) {
                        $status = 2;
                        $chef_date[] = $daily;
                    }
                }else{
                    $exists = ChefPlan::where('user_id', $user->id)->where('date', $daily)->exists();
                    $status = 0;
                    if ($exists) {
                        $status = 1;
                        $chef_date[] = $daily;
                    }
                }
                $date_arr[] = $status;
            }
            $log = [];
            //获取整月的订餐数据
//            $restaurant = Restaurant::whereIn('date', $chef_date)
//                ->whereIn('status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED,Restaurant::STATUS_EVALUATE])
//                ->orderBy('date', 'asc')
//                ->select('id','user_id','date','diet_type','food_type','num','status','office_id')
//                ->orderByDesc('id')
//                ->get();
//
//            foreach ($restaurant as $value){
//                $user_info = User::where('id',$value->user_id)->first();
//                $value->office_name = Office::where('id',$value->office_id)->value('office_name');
//                $value->name = $user_info->name??'';
//                $value->mobile = $user_info->mobile??'';
//                $value->avatar = $user_info->avatar??'';
//                $log[$value['date']]['date'] = $value['date'];
//
//                //初始化厨师数组
//                if(!isset($log[$value['date']]['lunch_chef_list'])){
//                    $log[$value['date']]['lunch_chef_list'] = [];
//                }
//
//                if(!isset($log[$value['date']]['dinner_chef_list'])){
//                    $log[$value['date']]['dinner_chef_list'] = [];
//                }
//
//            }
            //获取厨师人员安排
            $chef_plan = ChefPlan::whereIn('date', $chef_date)
                ->orderBy('date','asc')
                ->orderBy('id','desc')
                ->select('user_id','type','date','diet_type')
                ->get();

            foreach ($chef_plan as $chef){
                $chef_info = Partner::where('user_id',$chef->user_id)->first();
                $chef->name = $chef_info->name??'';
                $chef->mobile = $chef_info->mobile??'';
                $chef->avatar = $chef_info->pic??'';
                //处理厨师数组
                $date_time = $chef['date'];

                //如果没有订餐,先设置厨师,初始化字段
                if(!isset($log[$date_time])){
                    $log[$date_time]['date'] = $date_time;
                    $log[$date_time]['dinner_chef_list'] = [];
                    $log[$date_time]['lunch_chef_list'] = [];
                }

                $diet_type = $chef['diet_type'];
                // 将chef信息添加到对应的数组中
                if ($diet_type == Restaurant::DIET_TYPE_LUNCH) {
                    $log[$date_time]['lunch_chef_list'][] = $chef;
                } elseif ($diet_type == Restaurant::DIET_TYPE_DINNER) {
                    $log[$date_time]['dinner_chef_list'][] = $chef;
                }
            }
            $logs = array_values($log);

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

    /**
     * 获取订餐人员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getDayRestaurantList(Request $request)
    {
        try {
            $date = $request->get('date');
            $keyword = $request->get('keyword');
            $diet_type = $request->get('diet_type');
            $food_type = $request->get('food_type');
            $office_id = $request->get('office_id');
            $query = Restaurant::query();
            if($date){
                $query->when($date, function ($query) use ($date) {
                    $query->where(function ($query) use ($date) {
                        $query->where('date', $date);
                    });
                });
            }

            if($keyword){
                $query->where(function($sql) use($keyword) {
                    $sql->where('collaborator.name', 'like', '%'.$keyword.'%')
                        ->orWhere('collaborator.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');

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

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

            return $this->success('ok', compact('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',date('Y-m-d'));
            $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,6),1,null)) as lunch_num'),
                DB::raw('count(if(diet_type =1 and status in (1,2,3,4,6),1,null)) as dinner_num'),
                DB::raw('sum(if(food_type =0 and status in (1,2,3,4,6),num,0)) as trim_num'),
                DB::raw('sum(if(food_type =1 and status in (1,2,3,4,6),num,0)) as clean_num'),
                DB::raw('count(if(food_type =0 and status in (1,2,3),1,null)) as trim_not_take_num'),
                DB::raw('count(if(food_type =1 and status in (1,2,3),1,null)) as clean_not_take_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,6),1,null)) as lunch_num'),
                DB::raw('count(if(diet_type =1 and status in (1,2,3,4,6),1,null)) as dinner_num'),
                DB::raw('sum(if(food_type =0 and status in (1,2,3,4,6),num,0)) as trim_num'),
                DB::raw('sum(if(food_type =1 and status in (1,2,3,4,6),num,0)) as clean_num'),
                DB::raw('count(if(food_type =0 and status in (1,2,3),1,null)) as trim_not_take_num'),
                DB::raw('count(if(food_type =1 and status in (1,2,3),1,null)) as clean_not_take_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 setRestaurantSwitch(Request $request){
        try {
            $user = auth()->user();
            $status = $request->input('status',0);
            Redis::hset(Restaurant::REDIS_SEND_SWITCH,$user->id,$status);
            return $this->success('ok');
        }catch (\Exception $e){
            Log::error('restaurantSwitch:' . $e->getMessage());
            return $this->failure('切换失败');
        }
    }

    /**
     * 删除餐饮相关数据
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function deleteRestaurantData(){
        try {
            Db::table('chef_user')->delete();
            Db::table('chef_plan')->delete();
            Db::table('restaurant')->delete();
            Db::table('restaurant_order')->delete();
            Db::table('restaurant_order_refund')->delete();
            return $this->success('ok');
        }catch (\Exception $e){
            return $this->failure('删除失败');
        }
    }


    /**
     *更新订餐状态
     */
    public function updateRestaurantStatus(){
        $date = '2023-09-15';
        $ids = [304,157,152,7,449];
        Restaurant::where('date','>',$date)->whereIn('user_id',$ids)->update(['status'=>0]);
        return $this->success('ok');
    }

    /**
     * 扫码取餐 status 0:未订餐  1:订餐了,但是还没到取餐时间  2:已过取餐时间 3:取餐成功 4:已取餐,无需重复取餐
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function takeRestaurant(Request $request){
        try {
            $user = auth()->user();
            $date = date('Y-m-d');

            //如果时间小于下午2点,则查询午餐订餐
            $minute = date('H:i');
            if($minute <= Restaurant::LUNCH_TAKE_FINAL_TIME){
                $restaurant = Restaurant::where('user_id',$user->id)
                    ->where('date',$date)
                    ->where('diet_type',Restaurant::DIET_TYPE_LUNCH)
                    ->whereIn('status',Restaurant::STATUS_ARR)
                    ->first();
            }else{
                $restaurant = Restaurant::where('user_id',$user->id)
                    ->where('date',$date)
                    ->where('diet_type',Restaurant::DIET_TYPE_DINNER)
                    ->whereIn('status',Restaurant::STATUS_ARR)
                    ->first();
            }

            if(empty($restaurant)){
                return $this->success('ok',['status'=>0]);
            }

            if($restaurant->status == Restaurant::STATUS_TAKE){
                return $this->success('ok',['status'=>4]);
            }

            if($restaurant->diet_type == Restaurant::DIET_TYPE_LUNCH && $minute <= Restaurant::LUNCH_TAKE_FINAL_TIME){
                if($minute < Restaurant::LUNCH_TAKE_START_TIME){
                    return $this->success('ok',['status'=>1]);
                }elseif($minute > Restaurant::LUNCH_TAKE_END_TIME){
                    return $this->success('ok',['status'=>2]);
                }
            }else{
                if($minute < Restaurant::DINNER_TAKE_START_TIME){
                    return $this->success('ok',['status'=>1]);
                }elseif ($minute > Restaurant::DINNER_TAKE_END_TIME){
                    return $this->success('ok',['status'=>2]);
                }
            }
            Restaurant::where('user_id',$user->id)
                ->where('date',$date)
                ->where('diet_type',$restaurant->diet_type)
                ->whereIn('status',[Restaurant::STATUS_PAY,Restaurant::STATUS_WAIT,Restaurant::STATUS_FINISHED])
                ->update(['status'=>Restaurant::STATUS_TAKE]);

            return $this->success('ok',['status'=>3]);
        }catch (\Exception $e){
            return $this->failure('删除失败');
        }
    }
}
