<?php


namespace App\Handlers;


use App\Models\AreaSetting;
use App\Models\Bike;
use App\Models\LocationsLog;
use App\Models\OrderBikeOperate;
use App\Models\OrderRent;
use App\Models\OrderRentBikeOperate;
use App\Utils\Admin;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderRentHandler
{
    /**
     * 关锁还车
     * */
    public static function closeOrderRent($order_id)
    {
        $order = OrderRent::find($order_id);
        if (empty($order)) {
            Log::error('找不到订单信息');
            return false;
        }
        if ($order->status !== OrderRent::STATUS_RENT_BIKE) {
            Log::error('订单状态不为租车中,无法改为待结算');
            return false;
        }
        $bike = Bike::query()->find($order->bike_id);
        if (empty($bike)) {
            Log::error('找不到订单车辆信息');
            return false;
        }
        // 关车
        $closeLockBool = (new BaseBikeControl($bike->box_no))::closeLock();
        if (!$closeLockBool) {
            Log::error('关锁失败');
            return false;
        }

        try {
            $lastLocation = LocationsLog::getNewestLocationByBikeNo($bike->bike_no);
            $BikeHandler = new BikeHandler();


            $is_ban_stop_bike = $BikeHandler->byLocationCheckIsInBanStopParking($lastLocation['lat'], $lastLocation['lng'], $order->area_id);
            if ($is_ban_stop_bike) {
                Log::error('车辆在禁停区,无法关闭订单还车');
                return false;
            }

            DB::beginTransaction();
            // 更新车信息
            $bike->is_riding = Bike::RIDING_NO;
            $bike->is_lock = Bike::LOCK_YES;
            $bike->is_rent = Bike::RIDING_NO;
            $bike->last_location = json_encode($lastLocation);
            $bike->last_use_bike_end_time = date('Y-m-d H:i:s');
            $bike->save();

            // 记录关锁日志信息
            $orderRentOperateBike = new OrderRentBikeOperate();
            $orderRentOperateBike->type = OrderRentBikeOperate::TYPE_CLONE_BIKE;
            $orderRentOperateBike->name = OrderRentBikeOperate::$typeMaps[OrderBikeOperate::TYPE_CLONE_BIKE] . ',后台关锁';
            $orderRentOperateBike->bike_id = $bike->id;
            $orderRentOperateBike->latitude = $lastLocation['lat'];
            $orderRentOperateBike->longitude = $lastLocation['lng'];
            $orderRentOperateBike->order_id = $order_id;
            $orderRentOperateBike->user_id = Admin::user()->id;
            $orderRentOperateBike->is_admin = OrderRentBikeOperate::IS_ADMIN_YES;
            $orderRentOperateBike->save();
            // 删除redis订单
            (new BikeStatusInfoSyncHandler())->toBikeWaitRideStatus($bike->bike_no, $lastLocation['lng'], $lastLocation['lat'], $bike->put_status);


            $second = Carbon::now()->diffInSeconds(Carbon::parse($order->start_use_bike_time));

            // 判断是否经常这样操作(未做)
            // 30秒内关车,关闭订单
//            if ($second <= 30) {
//                // 关闭订单
//                $order->status = Order::STATUS_CLOSE_ORDER;
//                $order->end_use_bike_time = now();
//                $order->end_use_bike_location = [
//                    'latitude' => $lastLocation['lat'],
//                    'longitude' => $lastLocation['lng'],
//                ];
//                $order->is_admin_settle_order = Order::ADMIN_SETTLE_ORDER_ADMIN;
//                $order->end_use_bike_location = json_encode( $order->end_use_bike_location);
//                $order->save();
//                DB::commit();
//                return true;
//            }

            // 计算订单数据
            $setting = AreaSetting::query()->where('area_id', $order->area_id)->first();

            if (empty($setting)) {
                Log::error('区域配置出错,无法计算');
                return false;
            }
            // 计算用车小时数
            $use_hours = ceil($second / 3600);

            // 计算用车价格
            $money = 0;
            $over_hours = 0;
            //是否需要收取超出费用
            $is_over_time = (strtotime($order->return_end_bike_time) < time());
            if ($is_over_time) {
                //超出时间
                $over_hours = ceil(Carbon::now()->diffInMinutes(Carbon::parse($order->return_end_bike_time)) / 60);
                $hours = ceil(Carbon::now()->diffInMinutes(Carbon::parse($order->start_use_bike_time)) / 60);
                // Log::info($hours);

                if ($hours > 24) {
                    //超过1天  不超过8小时
                    $day = ceil($hours / 24);
                    $end_hours = $hours % 24;
                    $money = bcmul($setting->day_rent_capping_money, ($day - 1), 2);
                    // $money = bcadd($money, $setting->day_rent_money, 2);
                    if ($end_hours > $setting->day_rent_hours) {
                        // 超过一天  又超过8小时
                        //  (超时费 + 日封顶租金*天)
                        $money = bcadd(bcmul(($end_hours - $setting->day_rent_hours), $setting->per_hours_day_rent_timeout_money, 2), $money, 2);
                    }
                } else {
                    // 不超过1天  但是超过8小时
                    $money = bcmul($over_hours, $setting->per_hours_day_rent_timeout_money, 2);
                    //  (超时费 + 基础租金) 是否大于日封顶租金
                    $total_money = bcadd($money, $setting->day_rent_money, 2);
                    if ($total_money > $setting->day_rent_capping_money) {
                        // 总租金 大于 封顶租金
                        //(封顶租金 - 基础租金)
                        $money = bcsub($setting->day_rent_capping_money, $setting->day_rent_money, 2);
                    }
                }
            }

            // 日租结算
            $order->time_money = $money;
            $order->distance_money = 0.00;
            $order->preferential_money = 0.00;
            $order->over_hours = $over_hours;

            $order->end_use_bike_time = Carbon::now();


            $order->status = OrderRent::STATUS_CLOSE_RENT_BIKE;
            $order->end_use_bike_time = now();
            $order->end_use_bike_location = [
                'latitude' => $lastLocation['lat'],
                'longitude' => $lastLocation['lng'],
            ];
            //计算用车时间 (分)
            $order->use_bike_time_length = ceil($second / 60);
            //计算骑行距离
            $start_use_bike_location = json_decode($order->start_use_bike_location);
            $order->use_bike_distance_length = getDistance($start_use_bike_location->latitude, $start_use_bike_location->longitude, $order->end_use_bike_location['latitude'], $order->end_use_bike_location['longitude']);
            $order->use_bike_distance_length = round($order->use_bike_distance_length / 1000, 2);

            $order->dispatch_money = 0;

            $areaSetting = AreaSetting::where('area_id', $order->area_id)->first();
            if ($areaSetting->is_whole_area_huanche === AreaSetting::WHOLE_AREA_HUANCHE_NO) {

                // 是否全区域可还车
                // 判断车是否在停车的区域
                $is_huanche = $BikeHandler->byLocationCheckIsInStopParking($lastLocation['lat'], $lastLocation['lng'], $order->area_id);

                // Log::info($is_huanche);

                if (!$is_huanche['status']) {
                    // 不在还车点
                    $dispatch_money = $BikeHandler->byDistanceGetDistanceMoney($is_huanche['distance'], $setting);
                    // Log::info($dispatch_money);
                    $order->dispatch_money = $dispatch_money;

                    $bike->is_in_parking = Bike::IN_PARKING_NO;
                }
            }


            $order->preferential_money = 0;
            $order->end_use_bike_location = json_encode($order->end_use_bike_location);
            // 订单价格(调度费 + 超时费 + 租用费 )
            $order->total_money = bcadd(bcadd($money, $order->dispatch_money, 2), $setting->day_rent_money, 2);

            // 订单支付价格 (超时二次支付的价格)
            $order->pay_money = $order->total_money;
            // 订单总收入
            $order->order_total_money = $order->total_money;
            $order->is_admin_settle_order = OrderRent::ADMIN_SETTLE_ORDER_ADMIN;
            $order->pay_type = OrderRent::PAY_STATUS_NO;
            $order->save();
            $bike->save();

            DB::commit();

            // 关车
            (new BaseBikeControl($bike->box_no))::closeLock();
            return true;

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            return false;
        }


    }


}