<?php

namespace app\admin\service\order;

use app\admin\controller\member\BenefitController;
use app\admin\controller\member\QuotaController;
use app\admin\service\member\MemberService;
use app\model\Appointment;
use app\model\Goods;
use app\model\GoodsSku;
use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberBenefit;
use app\model\MemberCert;
use app\model\MemberInfo;
use app\model\MemberQuota;
use app\model\MemberRole;
use app\model\Order;
use app\model\OrderSheet;
use app\model\PayDetail;
use app\model\SysDept;
use app\model\SysSerial;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use function _PHPStan_cc8d35ffb\RingCentral\Psr7\str;

class AppointmentService
{
    public static function select(Request $request)
    {
        $page = $request->get('page');
        $pageSize = $request->get('pageSize');
        $id = $request->get('id', '');
        $mobile = $request->get('mobile', '');
        $status = $request->get('status', '');
        $premisesName = $request->get('premises', '');
        $appointmentMode = $request->get('appointment_mode', '');
        $type = $request->get('type', '');
        $memberId = $request->get('join_appointment_member_id', '');

        $rows = Db::table('appointment')
            ->leftJoin('member', 'member.member_id', '=', 'appointment.join_appointment_member_id')
            ->leftJoin('member_cert', 'member_cert.join_cert_member_id', '=', 'appointment.join_appointment_member_id')
            ->leftJoin('member_info', 'member_info.join_info_member_id', '=', 'appointment.join_appointment_member_id')
            ->leftJoin('goods', 'goods.goods_id', '=', 'appointment.join_appointment_goods_id')
            ->leftJoin('order', 'order.order_id', '=', 'appointment.join_appointment_order_id')
            ->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'appointment.join_appointment_order_id')
            ->leftJoin('member_benefit', 'member_benefit.member_benefit_id', '=', 'appointment.join_appointment_member_benefit_id')
            ->leftJoin('goods_sku', 'goods_sku.goods_sku_id', '=', 'appointment.join_appointment_goods_sku_id')
            ->whereIn('appointment_status', ['PAYING', 'WAITING', 'PENDING', 'DOING', 'DONE', 'CANCEL', 'REVOKE'])
            ->when($id != '', function ($query) use ($id) {
                $query->where('appointment.appointment_id', 'like', '%' . $id . '%');
            })->when($mobile != '', function ($query) use ($mobile) {
                $query->where(function ($query2) use ($mobile) {
                    $query2->where('member.member_mobile', 'like', '%' . $mobile . '%')
                        ->orWhere('member_cert.member_cert_name', 'like', '%' . $mobile . '%');
                });
            })->when($status != '', function ($query) use ($status) {
                $query->where('appointment.appointment_status', $status);
            })->when($premisesName != '', function ($query) use ($premisesName) {
                $query->whereJsonContains('appointment_apply_json->premises', $premisesName);
            })->when($appointmentMode != '', function ($query) use ($appointmentMode) {
                if ($appointmentMode == 'ONLINE') {
                    $query->whereIn('appointment_mode', ['ONLINE', 'ORDER']);
                } else {
                    $query->where('appointment_mode', $appointmentMode);
                }
            })->when(!empty($memberId), function ($query) use ($memberId) {
                $query->where('join_appointment_member_id', $memberId);
            })->when(!empty($type), function ($query) use ($type) {
                if ($type == 'todayDONE') {
                    $query->where('appointment_status', 'DONE');
                    $query->whereRaw('LEFT(appointment_done_datetime,10)=?', [date('Y-m-d')]);
                } elseif ($type == 'todayAppointment') {
                    $query->where('appointment_datetime', date('Y-m-d'));
                }
            });

        $pendingModel = clone $rows;
        $pendingTotal = $pendingModel->where('appointment.appointment_status', 'PENDING')->count();
        $doingModel = clone $rows;
        $doingTotal = $doingModel->where('appointment.appointment_status', 'DOING')->count();
        $doneModel = clone $rows;
        $doneTotal = $doneModel->where('appointment.appointment_status', 'DONE')->count();

        $total = $rows->count('member.member_id');
        $rows = $rows->select('appointment.*',
            'member.member_mobile', 'member.join_member_role_id', 'member.member_is_owner', 'member.member_is_vip', 'member.member_is_partner', 'member.member_is_referrer', 'member.member_is_franchisee',
            'member_cert.member_cert_name',
            'member_info.member_info_nickname', 'member_info.member_info_headimg',
            'goods.goods_name', 'goods.goods_cover', 'goods.goods_sales_price',
            'order.order_id', 'order.order_groupby', 'order.order_name', 'goods_sku.goods_sku_specs_json', 'order.order_amount_total', 'order.order_amount_pay',
            'order.order_category', 'order.order_status_system', 'order.order_status_payment', 'order.order_status_storage', 'order.order_is_complete',
            'order.order_addtimes', 'order_return.order_return_status',
            'member_benefit.member_benefit_name', 'member_benefit.member_benefit_id as benefit_id'
        )
            ->orderBy('appointment.appointment_addtimes', 'desc')
            ->forPage($page, $pageSize)
            ->get();

        foreach ($rows as &$row) {
            $row->goods_cover = getenv('STORAGE_DOMAIN') . $row->goods_cover;
            $row->goods_sku_specs_json = !empty($row->goods_sku_specs_json) ? json_decode($row->goods_sku_specs_json, true) : [];
            $row->order_addtimes = date('Y-m-d H:i:s', $row->order_addtimes);
            $row->appointment_addtimes = date('Y-m-d H:i:s', $row->appointment_addtimes);
            $row->appointment_apply_json = !empty($row->appointment_apply_json) ? json_decode($row->appointment_apply_json, true) : [];
            $row->appointment_doing_json = !empty($row->appointment_doing_json) ? json_decode($row->appointment_doing_json, true) : [];
            $row->appointment_result_json = !empty($row->appointment_result_json) ? json_decode($row->appointment_result_json, true) : [];
            if ($row->appointment_category == 'NOFEE') {
                $row->member_benefit_name = "后付费预约";
            } elseif ($row->appointment_category == 'GREENWAY') {
                $row->member_benefit_name = "就医绿通";
            }
            if (!empty($row->appointment_apply_json)) {
                $applyJson = $row->appointment_apply_json;
                $row->person = $applyJson['person'] ?? '';
                $row->appointment_times = $applyJson['times'] ?? '';
            }

            $skus = GoodsSku::where('join_sku_goods_id', $row->join_appointment_goods_id)->where('goods_sku_status', 'ON')
                ->where('goods_sku_id', $row->join_appointment_goods_sku_id)
                ->select('goods_sku_id', 'goods_sku_specs_json', 'goods_sku_sales_price')
                ->get();
            $skuJson = [];
            foreach ($skus as $key => $sku) {
                if (!empty($sku->goods_sku_specs_json)) {
                    $specsJson = json_decode($sku->goods_sku_specs_json, true);
                    $skuTitle = '';
                    foreach ($specsJson as $item3) {
                        if (is_array($item3)) {
                            $item3 = implode(',', $item3);
                        }
                        $skuTitle .= $item3 . '-';
                    }
                    $skuJson[$key] = [
                        'goods_sku_id' => $sku->goods_sku_id,
                        'goods_sku_sales_price' => $sku->goods_sku_sales_price,
                        'sku_name' => rtrim($skuTitle, '-')
                    ];
                }
            }

            $row->sku = $skuJson;
            // 会员等级
            if (!empty($row->join_member_role_id)) {
                $row->role_name = MemberRole::where('member_role_id', $row->join_member_role_id)->value('member_role_name');
            }
            $row->member_info_headimg = MemberService::getAvatarUrl($row->member_info_headimg ?? '');
        }
        return json_success('', compact('rows', 'page', 'pageSize', 'total', 'pendingTotal', 'doingTotal', 'doneTotal'));
    }

    public static function confirm($id)
    {
        $appointment = Appointment::where('appointment_id', $id)->where('appointment_status', 'WAITING')->first();
        if (!$appointment) {
            return json_fail('数据异常');
        }

        try {
            $appointment->appointment_status = 'PENDING';
            $appointment->save();

            return json_success('操作成功');
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail("操作失败");
        }
    }

    /**
     * 到店-生成未支付订单
     */
    public static function arrival(Request $request)
    {
        $appointmentId = $request->post('id', '');
        if (!$appointmentId) {
            return json_fail("参数异常");
        }

        $appointment = Appointment::where('appointment_id', $appointmentId)->first();

        Db::beginTransaction();
        try {
            $appointment->appointment_doing_datetime = date('Y-m-d H:i:s');
            $appointment->appointment_status = 'DOING';
            $appointment->save();
            Db::commit();

            return json_success('操作成功');
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollBack();
            return json_fail('到店状态修改失败');
        }

    }

    /**
     * 服务完成
     */
    public static function done(Request $request)
    {
        $appointmentId = $request->post('id', '');
        $isGenerateOrder = $request->post('is_generate_order', '');
        if (!$appointmentId || !$isGenerateOrder) {
            return json_fail("参数异常");
        }

        $appointment = Appointment::where('appointment_id', $appointmentId)->first();


        Db::beginTransaction();
        try {
            $appointment->appointment_done_datetime = date('Y-m-d H:i:s');
            $appointment->appointment_status = 'DONE';
            // 不产生订单，走核销
            if ($isGenerateOrder == 'N') {
                $appointment->save();

                Db::commit();
                return json_success('操作成功');
            }
            $applyJson = json_decode($appointment->appointment_apply_json, true);
            $goods = Goods::where('goods_id', $appointment->join_appointment_goods_id)->first();
            $sku = GoodsSku::where('goods_sku_id', $appointment->join_appointment_goods_sku_id)->where('goods_sku_status', 'ON')->first();
            $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
            $groupBy = 'OD' . date('ymdHi') . random_string(4, 'up');
            $order = [
                'order_id' => $orderId,
                'order_groupby' => $groupBy,
                'join_order_member_id' => $appointment->join_appointment_member_id,
                'order_name' => "预约-" . $goods->goods_name,
                'order_amount_total' => $sku->goods_sku_sales_price * $applyJson['person'],
                'order_amount_pay' => $sku->goods_sku_sales_price * $applyJson['person'],
                'order_is_complete' => 'N',
                'order_category' => $goods->goods_classify,
                'order_status_system' => 'PAYING',
                'order_status_payment' => 'PENDING',
                'order_status_storage' => 'PENDING',
                'order_platform' => 'SYSTEM',
                'order_addtimes' => time(),
                'order_config_json' => json_encode(['premises' => $applyJson['premises']])
            ];
            Order::insert($order);
            // 订单号更新到预约
            Appointment::where('appointment_id', $appointmentId)->update(['join_appointment_order_id' => $orderId]);
            // 订单详情
            $sheet = [
                'join_sheet_member_id' => $appointment->join_appointment_member_id,
                'join_sheet_order_id' => $orderId,
                'join_sheet_goods_id' => $appointment->join_appointment_goods_id,
                'join_sheet_goods_sku_id' => $appointment->join_appointment_goods_sku_id,
                'order_sheet_status' => 'PAYING',
                'order_sheet_category' => 'APPOINTMENT',
                // 'order_sheet_unit' => '套',
                'order_sheet_num' => $applyJson['person'],
                'order_sheet_price' => $sku->goods_sku_sales_price,
                'order_sheet_amount' => $sku->goods_sku_sales_price * $applyJson['person'],
                'order_sheet_pay' => $sku->goods_sku_sales_price * $applyJson['person'],
                'order_sheet_task_status' => 'NONE',
                'order_sheet_addtimes' => time()
            ];
            OrderSheet::insert($sheet);

            // 支付数据
            $pay = [
                'join_pay_member_id' => $appointment->join_appointment_member_id,
                'join_pay_order_id' => $groupBy,
                'pay_status' => 'WAITING',
                'pay_amount' => $sheet['order_sheet_pay'],
                'pay_remark' => '预约单',
                'pay_addtimes' => time(),
                'pay_paytimes' => date('Y-m-d H:i:s'),
                'pay_prepayid' => $appointment->join_appointment_member_id . '-CASH',
                'pay_category' => $goods->goods_classify,
                'join_pay_object_json' => ['order_id' => $orderId]
            ];
            PayDetail::insert($pay);

            $appointment->save();
            Db::commit();

            return json_success('操作成功');
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollBack();
            return json_fail('到店状态修改失败');
        }
    }

    /**
     * @Desc 添加预约
     * @Author Gorden
     * @Date 2024/9/6 9:22
     *
     * @param Request $request
     * @return \support\Response
     */
    public static function add(Request $request)
    {
        $params = $request->post();
        Db::beginTransaction();
        try {
            // 如果没有，新建
            if (empty($params['join_appointment_member_id']) && !empty($params['username']) && !empty($params['mobile'])) {
                if (Member::where('member_mobile', $params['mobile'])->exists()) {
                    Db::rollBack();
                    return json_fail('会员已存在，请勿重复创建');
                }
                $memberId = 'MR' . date('ymdHi') . random_string(4, 'up');
                $params['join_appointment_member_id'] = $params['member_id'] = $memberId;
                // 创建会员
                MemberService::createMember($params);
            }
            $appointmentId = "AP" . date('ymdHi') . random_string(4, 'up');
            $data = [
                'appointment_id' => $appointmentId,
                'join_appointment_member_id' => $params['join_appointment_member_id'] ?? '',
                'join_appointment_goods_id' => $params['join_appointment_goods_id'] ?? '',
                'join_appointment_goods_sku_id' => $params['join_appointment_goods_sku_id'] ?? '',
                'appointment_status' => $params['appointment_status'] ?? '',
                'appointment_datetime' => isset($params['appointment_datetime']) ? date('Y-m-d', strtotime($params['appointment_datetime'])) : '',
                'appointment_apply_datetime' => isset($params['appointment_apply_datetime']) ? date('Y-m-d H:i:s', strtotime($params['appointment_apply_datetime'])) : '',
                'appointment_doing_datetime' => isset($params['appointment_doing_datetime']) ? date('Y-m-d H:i:s', strtotime($params['appointment_doing_datetime'])) : '',
                'appointment_done_datetime' => isset($params['appointment_done_datetime']) ? date('Y-m-d H:i:s', strtotime($params['appointment_done_datetime'])) : '',
                'appointment_cancel_datetime' => isset($params['appointment_cancel_datetime']) ? date('Y-m-d H:i:s', strtotime($params['appointment_cancel_datetime'])) : '',
                'appointment_remark' => $params['appointment_remark'] ?? '',
                'appointment_category' => 'NOFEE',
                'appointment_addtimes' => time(),
                'appointment_mode' => $params['appointment_mode'] ?? '',
                'settlement_mode' => $params['settlement_mode'] ?? '',
                'appointment_platform' => 'SYSTEM'
            ];

            if (!empty($params['join_appointment_member_id'])) {
                $member = Member::with([
                    'cert' => function ($query) {
                        $query->select('join_cert_member_id', 'member_cert_name');
                    }
                ])->where('member_id', $params['join_appointment_member_id'])
                    ->first()
                    ->toArray();
                $data['appointment_apply_json'] = json_encode([
                    'name' => !empty($member['cert']['member_cert_name']) ? $member['cert']['member_cert_name'] : $member['member_mobile'],
                    'mobile' => $member['member_mobile'],
                    'person' => $params['person'],
                    'remark' => '',
                    'remark_apply_employe' => $params['remark_apply_employe'] ?? '',
                    'premises' => $params['premises'],
                    'times' => $params['appointment_times']
                ]);
            }

            Appointment::insert($data);
            Db::commit();
            _syslog("预约", "添加预约成功");
            return json_success("添加预约成功");
        } catch (BusinessException $e) {
            Db::rollBack();

            _syslog("预约", "添加预约失败");
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            dump($e->getMessage());
            _syslog("预约", "添加预约失败");
            return json_fail("添加预约失败");
        }
    }


    public static function update(Request $request)
    {
        $params = $request->post();
        $appointmentId = $params['appointment_id'];
        $appointment = Appointment::where('appointment_id', $appointmentId)->first();
        if (empty($appointment)) {
            return json_fail("数据不存在");
        }
        Db::beginTransaction();
        try {
            // 先检查选择的时段是否可预约
            $goods = Goods::where('goods_id', $params['join_appointment_goods_id'])->first();
            // $appointments = Appointment::where('appointment_datetime', $params['appointment_datetime'])
            //     ->where('appointment_id', '<>', $params['appointment_id'])
            //     ->get()
            //     ->toArray();
            // if ($goods->is_support_appointment == 'Y' && !empty($goods->goods_attribute_json) && $appointment->appointment_category != 'GREENWAY') {
            //     $extendJson = json_decode($goods->goods_attribute_json, true);
            //     foreach ($extendJson['times'] as $key => $time) {
            //         if ($time['duration'] == $params['appointment_times']) {
            //             if (!empty($appointments)){
            //                 foreach ($appointments as $appointmentItem) {
            //                     $applyJson = json_decode($appointmentItem['appointment_apply_json'], true);
            //                     $applyJsonTimes = $applyJson['times'] ?? '';

            //                     if ($time['duration'] == $applyJsonTimes) {
            //                         $extendJson['times'][$key]['person'] -= $applyJson['person'];
            //                         if ($extendJson['times'][$key]['person'] < $params['person']) {
            //                             return json_fail('当前时段名额不足，请选择其他时段');
            //                         }
            //                     }
            //                 }
            //             }else{
            //                 if ($extendJson['times'][$key]['person'] < $params['person']) {
            //                     return json_fail('当前时段名额不足，请选择其他时段');
            //                 }
            //             }
            //         }
            //     }
            // }
            $data = [
                'appointment_status' => $params['appointment_status'],
//                'join_appointment_goods_sku_id' => $params['join_appointment_goods_sku_id'] ?? '',
                'appointment_datetime' => $params['appointment_datetime'] ? date('Y-m-d', strtotime($params['appointment_datetime'])) : null,
                'appointment_apply_datetime' => $params['appointment_apply_datetime'] ? date('Y-m-d H:i:s', strtotime($params['appointment_apply_datetime'])) : null,
                'appointment_doing_datetime' => $params['appointment_doing_datetime'] ? date('Y-m-d H:i:s', strtotime($params['appointment_doing_datetime'])) : null,
                'appointment_done_datetime' => $params['appointment_done_datetime'] ? date('Y-m-d H:i:s', strtotime($params['appointment_done_datetime'])) : null,
                'appointment_cancel_datetime' => $params['appointment_cancel_datetime'] ? date('Y-m-d H:i:s', strtotime($params['appointment_cancel_datetime'])) : null,
                // 'appointment_remark' => $params['appointment_remark'] ?? '',
                'appointment_mode' => $params['appointment_mode'] ?? '',
                'settlement_mode' => $params['settlement_mode'] ?? '',
            ];
            // 如果是完成状态
            // if ($params['appointment_status'] == 'DONE' && $appointment->appointment_status != 'DONE') {
            //     if (empty($params['appointment_done_datetime'])) {
            //         $data['appointment_done_datetime'] = date('Y-m-d H:i:s');
            //     }
            //     MemberBenefit::where('member_benefit_id', $appointment->join_appointment_member_benefit_id)->increment('member_benefit_used_count');
            // }
            if (!empty($params['join_appointment_member_id'])) {
                $member = Member::with([
                    'cert' => function ($query) {
                        $query->select('join_cert_member_id', 'member_cert_name');
                    }
                ])->where('member_id', $params['join_appointment_member_id'])
                    ->first();
                if (!$member) {
                    throw new BusinessException("核销人员不存在");
                }
                $member = $member->toArray();
                $applyJson = [];
                if (!empty($appointment->appointment_apply_json)) {
                    $applyJson = json_decode($appointment->appointment_apply_json, true);
                }
                $applyJson['name'] = !empty($member['cert']['member_cert_name']) ? $member['cert']['member_cert_name'] : $member['member_mobile'];
                $applyJson['mobile'] = $member['member_mobile'];
                $applyJson['person'] = $params['person'];
                $applyJson['remark_apply_employe'] = $params['remark_apply_employe'] ?? '';
                $applyJson['remark_done_employe'] = $params['remark_done_employe'] ?? '';
                $applyJson['remark_cancel_employe'] = $params['remark_cancel_employe'] ?? '';
                $applyJson['premises'] = $params['premises'];
                $applyJson['times'] = $params['appointment_times'];
                $data['appointment_apply_json'] = json_encode($applyJson);
                // $data['appointment_apply_json'] = json_encode([
                //     'name' => !empty($member['cert']['member_cert_name']) ? $member['cert']['member_cert_name'] : $member['member_mobile'],
                //     'mobile' => $member['member_mobile'],
                //     'person' => $params['person'],
                //     'remark' => $data['appointment_remark'],
                //     'premises' => $params['premises'],
                //     'times' => $params['appointment_times']
                // ]);
            }

            Appointment::where('appointment_id', $appointmentId)->update($data);

            // 如果服务结束,没有生成过订单，生成订单
            if ($params['appointment_status'] == 'DONE' && empty($appointment->join_appointment_order_id) && $params['settlement_mode'] != 'QUOTA') {
                $sku = GoodsSku::find($params['join_appointment_goods_sku_id']);
                $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
                $groupBy = 'OD' . date('ymdHi') . random_string(4, 'up');
                $order = [
                    'order_id' => $orderId,
                    'order_groupby' => $groupBy,
                    'join_order_member_id' => $params['join_appointment_member_id'],
                    'order_name' => "预约-" . $goods->goods_name,
                    'order_amount_total' => $sku->goods_sku_sales_price * $params['person'],
                    'order_amount_pay' => $sku->goods_sku_sales_price * $params['person'],
                    'order_is_complete' => 'N',
                    'order_category' => $goods->goods_classify,
                    'order_status_system' => 'PAYING',
                    'order_status_payment' => 'PENDING',
                    'order_status_storage' => 'PENDING',
                    'order_platform' => 'SYSTEM',
                    'order_addtimes' => time()
                ];
                Order::insert($order);
                // 订单详情
                $sheet = [
                    'join_sheet_member_id' => $params['join_appointment_member_id'],
                    'join_sheet_order_id' => $orderId,
                    'join_sheet_goods_id' => $params['join_appointment_goods_id'],
                    'order_sheet_status' => 'PAYING',
                    'order_sheet_category' => 'APPOINTMENT',
                    'order_sheet_unit' => '套',
                    'order_sheet_num' => $params['person'],
                    'order_sheet_price' => $sku->goods_sku_sales_price,
                    'order_sheet_amount' => $sku->goods_sku_sales_price * $params['person'],
                    'order_sheet_pay' => $sku->goods_sku_sales_price * $params['person'],
                    'order_sheet_task_status' => 'NONE',
                    'order_sheet_addtimes' => time()
                ];
                OrderSheet::insert($sheet);
                // 订单号更新到预约
                Appointment::where('appointment_id', $appointmentId)->update(['join_appointment_order_id' => $orderId]);

                // 支付数据
                $pay = [
                    'join_pay_member_id' => $params['join_appointment_member_id'],
                    'join_pay_order_id' => $groupBy,
                    'pay_amount' => $sheet['order_sheet_pay'],
                    'pay_remark' => '预约单',
                    'pay_addtimes' => time(),
                    'pay_prepayid' => $params['join_appointment_member_id'] . '-' . $params['settlement_mode'],
                    'pay_paytimes' => date('Y-m-d H:i:s'),
                    'pay_category' => $goods->goods_classify
                ];
                // 现金余额结算
                if ($params['settlement_mode'] == 'CASH') {
                    $account = MemberAccount::where('join_account_member_id', $params['join_appointment_member_id'])
                        ->where('member_account_classify', 'CASH')
                        ->where('member_account_status', 'ACTIVED')
                        ->first();
                    if (!$account) {
                        throw new BusinessException("当前账户不存在或已过期");
                    }
                    $amount = $account->member_account_surplus + $account->member_account_added;
                    if ($amount < $sheet['order_sheet_pay']) {
                        throw new BusinessException("账户余额不足");
                    } else {
                        if ($account->member_account_surplus < $sheet['order_sheet_pay']) {
                            $account->member_account_added = $account->member_account_added - ($sheet['order_sheet_pay'] - $account->member_account_surplus);
                            $account->member_account_surplus = 0;
                        } else {
                            $account->member_account_surplus = $account->member_account_surplus - $sheet['order_sheet_pay'];
                        }
                        MemberAccount::where('member_account_id', $account->member_account_id)->update([
                            'member_account_expend' => $account->member_account_expend + $sheet['order_sheet_pay'],
                            'member_account_surplus' => $account->member_account_surplus,
                            'member_account_added' => $account->member_account_added
                        ]);
                        $pay['pay_status'] = 'SUCCESS';
                        $pay['join_pay_object_json'] = json_encode(['payment' => ['member_account_id' => $account->member_account_id]]);
                        // 更新订单状态

                        Order::where('order_id', $orderId)->update(['order_status_system' => 'DONE', 'order_is_complete' => 'Y', 'order_status_payment' => 'SUCCESS']);
                        OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
                    }
                    // $pay['pay_category'] = 'CASH';
                    PayDetail::insert($pay);
                } elseif ($params['settlement_mode'] == 'WELFARE') {
                    $account = MemberAccount::where('join_account_member_id', $params['join_appointment_member_id'])
                        ->where('member_account_classify', 'WELFARE')
                        ->where('member_account_status', 'ACTIVED')
                        ->first();
                    if (!$account) {
                        throw new BusinessException("当前账户不存在或已过期");
                    }
                    if ($account->member_account_surplus < $sheet['order_sheet_pay']) {
                        throw new BusinessException("账户余额不足");
                    } else {
                        MemberAccount::where('member_account_id', $account->member_account_id)->update([
                            'member_account_expend' => $account->member_account_expend + $sheet['order_sheet_pay'],
                            'member_account_surplus' => $account->member_account_surplus - $sheet['order_sheet_pay']
                        ]);
                        $pay['pay_status'] = 'SUCCESS';
                        $pay['join_pay_object_json'] = json_encode(['payment' => ['member_account_id' => $account->member_account_id]]);
                        // 更新订单状态
                        Order::where('order_id', $orderId)->update(['order_status_system' => 'DONE', 'order_is_complete' => 'Y', 'order_status_payment' => 'SUCCESS']);
                        OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
                    }
                    // $pay['pay_category'] = 'CASH';
                    PayDetail::insert($pay);
                } elseif ($params['settlement_mode'] == 'QRCODE' && empty($appointment->join_appointment_order_id)) {
                    // $pay['pay_category'] = 'QRCODE';
                    $pay['pay_status'] = 'SUCCESS';
                    PayDetail::insert($pay);
                    // 更新订单状态
                    Order::where('order_id', $orderId)->update(['order_status_system' => 'DONE', 'order_is_complete' => 'Y', 'order_status_payment' => 'SUCCESS']);
                    OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
                }

                // 回写权益表
                $benefitId = 'BF' . date('ymdHi') . random_string(4, 'up');
                $benefitData = [
                    'member_benefit_id' => $benefitId,
                    'join_benefit_member_id' => $params['join_appointment_member_id'],
                    'join_benefit_goods_id' => $params['join_appointment_goods_id'],
                    'join_benefit_goods_sku_id' => $params['join_appointment_goods_sku_id'] ?? '',
                    'join_benefit_order_id' => $orderId,
                    'member_benefit_status' => 'DONE',
                    'member_benefit_name' => $goods->goods_name,
                    'member_benefit_limit_count' => 1,
                    'member_benefit_used_count' => 1,
                    'member_benefit_addtimes' => time()
                ];
                MemberBenefit::insert($benefitData);

                // $premisesName = SysDept::where('dept_id',$params['premises'])->value('dept_name');
                // 记录核销
                $paramsData = [
                    'dept_premises_id' => $params['premises'],
                    'order_remark' => $params['appointment_remark'],
                    'write_off_member_id' => $params['write_off_member_id'],
                    'join_order_member_id' => $params['join_appointment_member_id'],
                ];
                $writeOffData = OrderService::generateWriteOffData($paramsData);

                Appointment::where('appointment_id', $appointmentId)->update([
                    'join_appointment_member_benefit_id' => $benefitId,
                    'appointment_status' => 'DONE',
                    'appointment_done_datetime' => $params['appointment_done_datetime'] ? date('Y-m-d H:i:s', strtotime($params['appointment_done_datetime'])) : null,
                    'appointment_done_json' => json_encode($writeOffData)
                ]);
            }
            // 已有服务核销
            if ($params['appointment_status'] == 'DONE' && $params['settlement_mode'] == 'QUOTA' && !empty($params['quota_id'])) {
                // $premisesName = SysDept::where('dept_id',$params['premises'])->value('dept_name');
                $paramsData = [
                    'member_id' => $params['join_appointment_member_id'],
                    'nbr' => $params['person'],
                    'times' => date('Y-m-d H:i:s'),
                    'write_off_member_id' => $params['write_off_member_id'],
                    'remark' => $params['appointment_remark'],
                    'dept_premises_id' => $params['premises']
                ];
                $quotaType = substr($params['quota_id'], 0, 2);
                if ($quotaType == 'MQ') {
                    $quota = MemberQuota::where('member_quota_id', $params['quota_id'])
                        ->select('member_quota_id', 'join_member_rule_added_component_id')
                        ->first()
                        ->toArray();
                    $paramsData['component_id'] = $quota['join_member_rule_added_component_id'];

                    QuotaController::doWriteOff($paramsData);
                    // 回写权益ID
                    if (empty($appointment->join_appointment_member_benefit_id)) {
                        Appointment::where('appointment_id', $appointmentId)->update(['join_appointment_member_benefit_id' => $params['quota_id']]);
                    }
                } else if ($quotaType == 'BF') {
                    $paramsData['benefit_id'] = $params['quota_id'];
                    BenefitController::doWriteOff($paramsData, $appointment);

                    // 清除后付费预约
                    if ($appointment->appointment_category == 'NOFEE') {
                        Appointment::where('appointment_id', $appointmentId)->delete();
                    }
                }

                _syslog("预约", "已有服务核销");
            }


            Db::commit();
            _syslog("预约", "预约数据更新成功");
            return json_success("数据更新成功");
        } catch (\support\exception\BusinessException $e) {
            Db::rollBack();
            dump($e->getFile() . '--' . $e->getLine());
            _syslog("预约", "预约数据更新失败");
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            dump($e->getFile() . '--' . $e->getLine());
            _syslog("预约", "预约数据更新失败");
            return json_fail("数据更新失败");
        }
    }

    /**
     * 取消预约
     */
    public static function cancelApply(Request $request)
    {

        $appointmentId = $request->post('id', '');
        if (!$appointmentId) {
            return json_fail("参数异常");
        }

        $appointment = Appointment::where('appointment_id', $appointmentId)->first();
        if (!$appointment) {
            return json_fail("参数异常");
        }

        try {
            $appointment->appointment_status = 'CANCEL';
            $appointment->appointment_cancel_datetime = date('Y-m-d H:i:s');
            $appointment->save();

            return json_success('取消成功');
        } catch (\Exception $e) {
            return json_fail('取消失败');
        }

    }

    public static function getTimes(Request $request)
    {
        $goodsId = $request->get('goods_id', '');
        $date = $request->get('date', '');
//        $memberId = $request->get('member_id', '');
        $appointmentId = $request->get('appointment_id', '');
        $premisesName = $request->get('premisses', '');
        if (!$goodsId || !$date) {
            return json_fail("查询时间段失败！");
        }

        if (!$premisesName) {
            return json_fail("请先选择预约场所");
        }

        $goods = Goods::where('goods_id', $goodsId)->first();
        if (!$goods) {
            return json_fail('数据不存在');
        }

        // 当前服务已预约出去的
        $appointments = Appointment::where('join_appointment_goods_id', $goodsId)
            ->where('appointment_datetime', $date)
            ->whereJsonContains('appointment_apply_json->premises', $premisesName)
            ->when($appointmentId != '', function ($query) use ($appointmentId) {
                $query->where('appointment_id', '<>', $appointmentId);
            })
            ->get()
            ->toArray();
        if ($goods->is_support_appointment == 'Y' && !empty($goods->goods_attribute_json)) {
            $extendJson = json_decode($goods->goods_attribute_json, true);
            $times = $extendJson['times'];
            foreach ($times as $key => $time) {
                if (strtotime($date) < strtotime(date('Y-m-d')) || ($date == date('Y-m-d') && strtotime($date . ' ' . $key) < time())) {
                    unset($times[$key]);
                    continue;
                }
                $times[$key]['timesStr'] = $time['duration'];
                foreach ($appointments as $appointment) {
                    if (!empty($appointment['appointment_apply_json'])) {
                        $applyJson = json_decode($appointment['appointment_apply_json'], true);
                        $applyJsonTimes = $applyJson['times'] ?? '';

                        if ($time['duration'] == $applyJsonTimes) {
                            $times[$key]['person'] -= $applyJson['person'];
                            if ($times[$key]['person'] < 1) {
                                $times[$key]['person'] = 0;
                                $times[$key]['disabled'] = true;
                            }
                        }
                    }
                }
            }
            return json_success('', $times);
        }
    }
}