<?php
/**
 * Created by PhpStorm.
 * User: zilongs
 * Date: 20-9-30
 * Time: 下午10:58
 */

namespace App\Http\Controllers\Api\V1;

use App\Models\Nurse;
use App\Models\Order;
use App\Models\OrderNurse;
use App\Models\OrderPack;
use App\Models\OrderPatient;
use App\Models\OrderVaccine;
use App\Models\OrganizationVaccine;
use App\Models\Patient;
use App\Models\Payment;
use App\Models\ServicePack;
use App\Models\Team;
use App\Models\TeamDocter;
use App\Models\TimePeriod;
use App\Models\User;
use App\Models\UserCoupon;
use App\Models\Vaccine;
use EasyWeChat\Factory;
use DB;
use Exception;

class OrderController extends AuthController
{
    public function consultPlaceOrder()
    {
        $req = request()->post();
        $this->validate(request(), [
            'payment_type' => 'required|in:1,2,3',
            'product_type' => 'required|in:1,2',
            'docter_id' => 'required|integer',
            'patient_id' => 'required|integer',
            'total_amount' => 'required|integer',
            'user_coupon_id' => 'integer',
            'phone' => 'required_if:product_type,1',
            'phone_minutes' => 'required_if:product_type,1|integer',
            'symptoms' => 'required_if:product_type,2|max:2000',
            'medical_imgs' => 'required_if:product_type,2|json|max:3000',
            'order_pack_id' => 'required_if:payment_type,3|integer',
            'pay_password|支付密码' => 'integer',
        ]);
        $user = $this->user;

        if (!empty($req['pay_password'])) {
            if (empty($user['pay_password'])) {
                return out(null, 60010, '未设置支付密码');
            }
            if (sha1(md5($req['pay_password'])) !== $user['pay_password']) {
                return out(null, 10001, '密码错误');
            }
        }

        $discount_amount = 0;
        if (!empty($req['user_coupon_id'])) {
            //计算优惠金额
            $discount_amount = UserCoupon::getDiscountAmount($req['user_coupon_id'], $user['id'], $req['total_amount'], $req['product_type']);
        }
        $payment_amount = $req['total_amount'] - $discount_amount;
        $payment_amount = $payment_amount < 0 ? 0 : $payment_amount;

        if (in_array($req['payment_type'], [2,3]) && $payment_amount > 0 && empty($req['pay_password'])) {
            return out(null, 10011, '请输入支付密码');
        }

        //图文咨询订单未结束时不能针对同一医生再次下图文订单
        if ($req['product_type'] == 2 && Order::where('docter_id', $req['docter_id'])->where('product_type', 2)->where('user_id', $user['id'])->whereIn('order_status', [2,3])->exists()) {
            return out(null, 10012, '您已经下过该医生的图文订单了，并且订单还未完成');
        }

        if ($req['payment_type'] == 2) {
            if ($user['balance'] < $payment_amount) {
                return out(null, 601, '余额不足');
            }
        }

        if ($req['payment_type'] == 3) {
            OrderPack::checkUserServicePack($req['order_pack_id'], $user['id'], $req['product_type'], $payment_amount);
        }

        $order_status = $payment_status = 1;
        $payment_time = 0;
        if ($payment_amount == 0 || in_array($req['payment_type'], [2,3])) {
            $order_status = $payment_status = 2;
            $payment_time = time();
        }

        $config = null;
        DB::beginTransaction();
        try {
            //保存订单数据
            $create = [
                'user_id' => $user['id'],
                'payment_type' => $req['payment_type'],
                'product_type' => $req['product_type'],
                'docter_id' => $req['docter_id'],
                'total_amount' => $req['total_amount'],
                'payment_amount' => $payment_amount,
                'discount_amount' => $discount_amount,
                'patient_id' => $req['patient_id'],
                'order_status' => $order_status,
                'payment_status' => $payment_status,
                'payment_time' => $payment_time,
            ];
            if ($req['payment_type'] == 3) {
                $create['pay_order_pack_id'] = $req['order_pack_id'];
            }
            $order = Order::create($create);
            $order_sn = build_sn($order['id']);
            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);
            //保存订单患者信息
            $addPatient = Patient::select(['name', 'sex', 'avatar', 'birthday', 'relationship_type', 'info', 'card_type', 'card_number', 'card_img_url', 'card_back_img_url', 'email', 'phone as patient_phone', 'social_card_number', 'born_hospital', 'guardian_name', 'address'])->where('id', $req['patient_id'])->first()->getOriginal();
            $addPatient['order_id'] = $order['id'];
            $addPatient['patient_id'] = $req['patient_id'];
            if ($req['product_type'] == 1) {
                $addPatient['phone'] = $req['phone'];
                $addPatient['phone_minutes'] = $req['phone_minutes'];
            }
            elseif ($req['product_type'] == 2) {
                $addPatient['symptoms'] = $req['symptoms'];
                $addPatient['medical_imgs'] = $req['medical_imgs'];
            }
            OrderPatient::create($addPatient);

            //判断是微信支付
            if ($req['payment_type'] == 1) {
                //生成支付交易单
                if ($payment_amount > 0) {
                    $trade_sn = build_sn($order['id'], 3, 'T');
                    $payBody = '超级宝妈-'.config('config.product_type_map')[$req['product_type']];
                    Payment::create([
                        'user_id' => $user['id'],
                        'order_id' => $order['id'],
                        'trade_sn' => $trade_sn,
                        'amount' => $payment_amount,
                        'remark' => $payBody,
                    ]);
                    //请求支付
                    $payment = Factory::payment(config('config.wechat_pay'));
                    $result = $payment->order->unify([
                        'body' => $payBody,
                        'out_trade_no' => $trade_sn,
                        'total_fee' => $payment_amount,
                        'trade_type' => 'JSAPI',
                        'openid' => $user['openid'],
                    ]);

                    if (empty($result['prepay_id'])) {
                        $errorMsg = !empty($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'];
                        return out(null, 702, $errorMsg);
                    }

                    $config = $payment->jssdk->bridgeConfig($result['prepay_id'], false);
                }
            }
            //判断是余额支付
            elseif ($req['payment_type'] == 2) {
                if ($payment_amount > 0) {
                    //改变用户余额
                    $change_amount = 0 - $payment_amount;
                    User::changeBalance($user['id'], $change_amount, 1, $order['id'], '咨询订单消费');
                }
            }

            if ($payment_amount == 0 || in_array($req['payment_type'], [2, 3])) {
                Order::payCompletedHandle($order['id']);
            }

            //如果有优惠券就标记优惠券为已使用
            if (!empty($req['user_coupon_id'])) {
                UserCoupon::where('id', $req['user_coupon_id'])->update(['order_id' => $order['id'], 'status' => 2, 'use_time' => time()]);
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return out(null, 500, '下单失败，请稍后重试', $e->getMessage());
        }

        return out($config);
    }

    public function appointPlaceOrder()
    {
        $req = request()->post();
        $this->validate(request(), [
            'payment_type' => 'required|in:1,2,3',
            'product_type' => 'required|in:3,4,5',
            'patient_id' => 'required|integer',
            'organization_id' => 'required|integer',
            'schedule_date' => 'required|date',
            'time_period_id' => 'required|integer',
            'total_amount' => 'required|integer',
            'user_coupon_id' => 'integer',
            'docter_id' => 'required_if:product_type,3|integer',
            'vaccine_id' => 'required_if:product_type,4|integer',
            'nurse_ids' => 'required_if:product_type,5|json',
            'order_pack_id' => 'required_if:payment_type,3|integer',
            'pay_password|支付密码' => 'integer',
        ]);
        $user = $this->user;

        if (!empty($req['pay_password'])) {
            if (empty($user['pay_password'])) {
                return out(null, 60010, '未设置支付密码');
            }
            if (sha1(md5($req['pay_password'])) !== $user['pay_password']) {
                return out(null, 10001, '密码错误');
            }
        }

        $product_type = $req['product_type'];

        $discount_amount = 0;
        if (!empty($req['user_coupon_id'])) {
            //计算优惠金额
            $discount_amount = UserCoupon::getDiscountAmount($req['user_coupon_id'], $user['id'], $req['total_amount'], $product_type);
        }
        $payment_amount = $req['total_amount'] - $discount_amount;
        $payment_amount = $payment_amount < 0 ? 0 : $payment_amount;

        if (in_array($req['payment_type'], [2,3]) && $payment_amount > 0 && empty($req['pay_password'])) {
            return out(null, 10011, '请输入支付密码');
        }

        if ($req['payment_type'] == 2) {
            if ($user['balance'] < $payment_amount) {
                return out(null, 601, '余额不足');
            }
        }

        //疫苗预约检查库存是否足够
        if ($req['product_type'] == 4) {
            $stock = OrganizationVaccine::where('org_id', $req['organization_id'])->where('vaccine_id', $req['vaccine_id'])->value('stock');
            if ($stock <= 0) {
                return out(null, 10009, '该疫苗库存不足');
            }
        }

        if ($req['payment_type'] == 3) {
            OrderPack::checkUserServicePack($req['order_pack_id'], $user['id'], $req['product_type'], $payment_amount);
        }

        $order_status = $payment_status = 1;
        $payment_time = 0;
        if ($payment_amount == 0 || in_array($req['payment_type'], [2,3])) {
            $order_status = 3;
            $payment_status = 2;
            $payment_time = time();
        }

        $config = null;
        DB::beginTransaction();
        try {
            //保存订单数据
            $create = [
                'user_id' => $user['id'],
                'docter_id' => $req['docter_id'] ?? 0,
                'patient_id' => $req['patient_id'],
                'organization_id' => $req['organization_id'],
                'payment_type' => $req['payment_type'],
                'product_type' => $product_type,
                'order_status' => $order_status,
                'payment_status' => $payment_status,
                'total_amount' => $req['total_amount'],
                'payment_amount' => $payment_amount,
                'discount_amount' => $discount_amount,
                'payment_time' => $payment_time,
            ];
            if ($req['payment_type'] == 3) {
                $create['pay_order_pack_id'] = $req['order_pack_id'];
            }
            $order = Order::create($create);
            $order_sn = build_sn($order['id']);
            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);
            //保存订单患者信息
            $addPatient = Patient::select(['name', 'sex', 'avatar', 'birthday', 'relationship_type', 'info', 'card_type', 'card_number', 'card_img_url', 'card_back_img_url', 'email', 'phone as patient_phone', 'social_card_number', 'born_hospital', 'guardian_name', 'address'])->where('id', $req['patient_id'])->first()->getOriginal();
            $addPatient['order_id'] = $order['id'];
            $addPatient['patient_id'] = $req['patient_id'];
            $addPatient['organization_id'] = $req['organization_id'];
            $addPatient['time_period_id'] = $req['time_period_id'];
            $timePeriod = TimePeriod::where('id', $req['time_period_id'])->first();
            $addPatient['appoint_start_time'] = strtotime($req['schedule_date'].' '.$timePeriod['start_time_period'].':00');
            $addPatient['appoint_end_time'] = strtotime($req['schedule_date'].' '.$timePeriod['end_time_period'].':00');
            $orderPatient = OrderPatient::create($addPatient);
            //保存订单疫苗信息
            if ($req['product_type'] == 4) {
                $addVaccine = Vaccine::join('organization_vaccines', 'organization_vaccines.vaccine_id', '=', 'vaccines.id')->select(['vaccines.id as vaccine_id', 'organization_vaccines.type as vaccine_type', 'organization_vaccines.price as vaccine_price', 'vaccines.name as vaccine_name', 'organization_vaccines.remark as vaccine_remark', 'organization_vaccines.supplier as vaccine_supplier'])->where('organization_vaccines.org_id', $req['organization_id'])->where('organization_vaccines.vaccine_id', $req['vaccine_id'])->first()->getOriginal();
                $addVaccine['order_id'] = $order['id'];
                $addVaccine['order_patient_id'] = $orderPatient['id'];
                $addVaccine = array_filter($addVaccine);
                OrderVaccine::create($addVaccine);
            }
            //保存儿保订单信息
            if ($req['product_type'] == 5) {
                $nurse_ids = json_decode($req['nurse_ids'], true);
                foreach ($nurse_ids as $k => $v) {
                    $addNurse = Nurse::select(['id as nurse_id', 'price as nurse_price', 'name as nurse_name', 'remark as nurse_remark'])->where('id', $v)->first()->getOriginal();
                    $addNurse['order_id'] = $order['id'];
                    $addNurse['order_patient_id'] = $orderPatient['id'];
                    OrderNurse::create($addNurse);
                }
            }

            //判断是微信支付
            if ($req['payment_type'] == 1) {
                //生成支付交易单
                if ($payment_amount > 0) {
                    $trade_sn = build_sn($order['id'], 3, 'T');
                    $payBody = '超级宝妈-'.config('config.product_type_map')[$product_type];
                    Payment::create([
                        'user_id' => $user['id'],
                        'order_id' => $order['id'],
                        'trade_sn' => $trade_sn,
                        'amount' => $payment_amount,
                        'remark' => $payBody,
                    ]);
                    //请求支付
                    $payment = Factory::payment(config('config.wechat_pay'));
                    $result = $payment->order->unify([
                        'body' => $payBody,
                        'out_trade_no' => $trade_sn,
                        'total_fee' => $payment_amount,
                        'trade_type' => 'JSAPI',
                        'openid' => $user['openid'],
                    ]);

                    if (empty($result['prepay_id'])) {
                        $errorMsg = !empty($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'];
                        return out(null, 702, $errorMsg);
                    }

                    $config = $payment->jssdk->bridgeConfig($result['prepay_id'], false);
                }
            }
            //判断是余额支付
            elseif ($req['payment_type'] == 2) {
                if ($payment_amount > 0) {
                    //改变用户余额
                    $change_amount = 0 - $payment_amount;
                    User::changeBalance($user['id'], $change_amount, 1, $order['id'], '预约订单消费');
                }
            }

            if ($payment_amount == 0 || in_array($req['payment_type'], [2, 3])) {
                Order::payCompletedHandle($order['id']);
            }

            //如果有优惠券就标记优惠券为已使用
            if (!empty($req['user_coupon_id'])) {
                UserCoupon::where('id', $req['user_coupon_id'])->update(['order_id' => $order['id'], 'status' => 2, 'use_time' => time()]);
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return out(null, 500, '下单失败，请稍后重试', $e->getMessage());
        }

        return out($config);
    }

    public function packPlaceOrder()
    {
        $req = request()->post();
        $this->validate(request(), [
            'payment_type' => 'required|in:1,2',
            'patient_id' => 'required|integer',
            'total_amount' => 'required|integer',
            'user_coupon_id' => 'integer',
            'service_pack_id' => 'required|integer',
            'is_security' => 'required|in:0,1',
            'guardian_name' => 'required|max:50',
            'relationship_type' => 'required|integer',
            'pay_password|支付密码' => 'integer',
            'is_need_insurance' => 'in:0,1',
        ]);
        $user = $this->user;

        if (!empty($req['pay_password'])) {
            if (empty($user['pay_password'])) {
                return out(null, 60010, '未设置支付密码');
            }
            if (sha1(md5($req['pay_password'])) !== $user['pay_password']) {
                return out(null, 10001, '密码错误');
            }
        }

        $discount_amount = 0;
        if (!empty($req['user_coupon_id'])) {
            //计算优惠金额
            $discount_amount = UserCoupon::getDiscountAmount($req['user_coupon_id'], $user['id'], $req['total_amount'], 6);
        }

        $addPatient = Patient::select(['name', 'sex', 'avatar', 'birthday', 'relationship_type', 'info', 'card_type', 'card_number', 'card_img_url', 'card_back_img_url', 'email', 'phone as patient_phone', 'social_card_number', 'born_hospital', 'guardian_name', 'address'])->where('id', $req['patient_id'])->first()->getOriginal();

        $payment_amount = $req['total_amount'] - $discount_amount;
        $payment_amount = $payment_amount < 0 ? 0 : $payment_amount;

        if ($req['payment_type'] == 2 && $payment_amount > 0 && empty($req['pay_password'])) {
            return out(null, 10011, '请输入支付密码');
        }

        if ($req['payment_type'] == 2) {
            if ($user['balance'] < $payment_amount) {
                return out(null, 601, '余额不足');
            }
        }

        $order_status = $payment_status = 1;
        $payment_time = 0;
        if ($payment_amount == 0 || $req['payment_type'] == 2) {
            $order_status = 3;
            $payment_status = 2;
            $payment_time = time();
        }

        $config = null;
        DB::beginTransaction();
        try {
            //保存订单数据
            $order = Order::create([
                'user_id' => $user['id'],
                'patient_id' => $req['patient_id'],
                'payment_type' => $req['payment_type'],
                'product_type' => 6,
                'total_amount' => $req['total_amount'],
                'payment_amount' => $payment_amount,
                'discount_amount' => $discount_amount,
                'order_status' => $order_status,
                'payment_status' => $payment_status,
                'payment_time' => $payment_time,
            ]);
            $order_sn = build_sn($order['id']);
            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);
            //保存订单患者信息
            $addPatient['order_id'] = $order['id'];
            $addPatient['patient_id'] = $req['patient_id'];
            OrderPatient::create($addPatient);
            //保存订单服务包表
            $addPack = ServicePack::select(['id as service_pack_id', 'name as pack_name', 'intro as pack_intro', 'price as pack_price', 'insurance_policy', 'insurance_img_url', 'team_id', 'phone_minutes', 'chat_num', 'appoint_num', 'vaccine_limit_amount', 'nurses_limit_amount', 'effective_days', 'label'])->where('id', $req['service_pack_id'])->first()->getOriginal();
            $addPack['user_id'] = $user['id'];
            $addPack['order_id'] = $order['id'];
            $addPack['is_security'] = $req['is_security'];
            $addPack['guardian_name'] = $req['guardian_name'];
            $addPack['relationship_type'] = $req['relationship_type'];
            $addPack['start_time'] = time();
            $addPack['end_time'] = time() + $addPack['effective_days']*24*3600;
            $addPack['total_phone_minutes'] = $addPack['phone_minutes'];
            $addPack['total_chat_num'] = $addPack['chat_num'];
            $addPack['total_appoint_num'] = $addPack['appoint_num'];
            $addPack['total_vaccine_limit_amount'] = $addPack['vaccine_limit_amount'];
            $addPack['total_nurses_limit_amount'] = $addPack['nurses_limit_amount'];
            $addPack['label'] = json_decode($addPack['label'], true);
            $addPack['is_need_insurance'] = !empty($req['is_need_insurance']) ? $req['is_need_insurance'] : 0;
            OrderPack::create($addPack);

            //判断是微信支付
            if ($req['payment_type'] == 1) {
                //生成支付交易单
                if ($payment_amount > 0) {
                    $trade_sn = build_sn($order['id'], 3, 'T');
                    $payBody = '超级宝妈-'.config('config.product_type_map')[6];
                    Payment::create([
                        'user_id' => $user['id'],
                        'order_id' => $order['id'],
                        'trade_sn' => $trade_sn,
                        'amount' => $payment_amount,
                        'remark' => $payBody,
                    ]);
                    //请求支付
                    $payment = Factory::payment(config('config.wechat_pay'));
                    $result = $payment->order->unify([
                        'body' => $payBody,
                        'out_trade_no' => $trade_sn,
                        'total_fee' => $payment_amount,
                        'trade_type' => 'JSAPI',
                        'openid' => $user['openid'],
                    ]);

                    if (empty($result['prepay_id'])) {
                        $errorMsg = !empty($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'];
                        return out(null, 702, $errorMsg);
                    }

                    $config = $payment->jssdk->bridgeConfig($result['prepay_id'], false);
                }
            }
            //判断是余额支付
            elseif ($req['payment_type'] == 2) {
                if ($payment_amount > 0) {
                    //改变用户余额
                    $change_amount = 0 - $payment_amount;
                    User::changeBalance($user['id'], $change_amount, 1, $order['id'], '购买服务包');
                }
            }

            if ($payment_amount == 0 || $req['payment_type'] == 2) {
                Order::payCompletedHandle($order['id']);
            }

            //如果有优惠券就标记优惠券为已使用
            if (!empty($req['user_coupon_id'])) {
                UserCoupon::where('id', $req['user_coupon_id'])->update(['order_id' => $order['id'], 'status' => 2, 'use_time' => time()]);
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return out(null, 500, '下单失败，请稍后重试', $e->getMessage());
        }

        return out($config);
    }

    public function orderList()
    {
        $req = request()->post();
        $this->validate(request(), [
            'list_type' => 'required|in:0,1,2',
            'product_type' => 'integer',
            'order_status' => 'integer',
            'time_sort' => 'in:0,1',
            'is_pack_expire' => 'in:0,1,2',
        ]);
        $user = $this->user;

        $builder = Order::with(['docter.office', 'docter.qualification', 'orderPatient', 'orderPack', 'orderNurse', 'orderVaccine', 'organization.docter', 'suggest'])->where('user_id', $user['id']);
        if (!empty($req['product_type'])) {
            $builder->where('product_type', $req['product_type']);
        }
        else {
            if (!empty($req['list_type'])) {
                if ($req['list_type'] == 1) {
                    $builder->whereIn('product_type', [1,2]);
                }
                elseif ($req['list_type'] == 2) {
                    $builder->whereIn('product_type', [3,4,5]);
                }
            }
            else {
                $builder->where('product_type', '<', 7);
            }
        }
        if (!empty($req['order_status'])) {
            $builder->where('order_status', $req['order_status']);
        }
        if (!empty($req['is_pack_expire'])) {
            $tmpBuilder  = OrderPack::join('orders as o', 'o.id', '=', 'order_packs.order_id')->where('o.user_id', $user['id']);
            if ($req['is_pack_expire'] == 1) {
                $tmpBuilder->where('order_packs.end_time', '<', time());
            }
            else {
                $tmpBuilder->where('order_packs.end_time', '>=', time());
            }
            $order_ids = $tmpBuilder->pluck('o.id')->toArray();
            $builder->whereIn('id', $order_ids);
        }
        if (!empty($req['time_sort'])) {
            $builder->orderBy('id', 'desc');
        }
        else {
            $builder->orderBy('id', 'asc');
        }

        $data = $builder->paginate();

        return out($data);
    }

    public function orderDetail()
    {
        $req = request()->post();
        $this->validate(request(), [
            'order_id' => 'required|integer'
        ]);
        $user = $this->user;

        $data = Order::with(['docter.office', 'docter.qualification', 'orderPatient', 'orderPack', 'orderNurse', 'orderVaccine', 'organization.docter', 'suggest'])->where('id', $req['order_id'])->where('user_id', $user['id'])->first()->toArray();
        if (!empty($data['order_pack'])) {
            $data['order_pack']['team'] = [];
            if (!empty($data['order_pack']['team_id'])) {
                $data['order_pack']['team'] = Team::with(['docter.office', 'docter.qualification'])->whereIn('id', $data['order_pack']['team_id'])->get()->toArray();
            }
        }

        return out($data);
    }

    public function topup()
    {
        $req = request()->post();
        $this->validate(request(), [
            'amount' => 'required|integer',
        ]);
        $user = $this->user;

        DB::beginTransaction();
        try {
            //保存订单数据
            $order = Order::create([
                'user_id' => $user['id'],
                'product_type' => 7,
                'total_amount' => $req['amount'],
                'payment_amount' => $req['amount'],
            ]);
            $order_sn = build_sn($order['id']);
            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);

            //生成支付交易单
            $trade_sn = build_sn($order['id'], 3, 'T');
            $payBody = '超级宝妈-'.config('config.product_type_map')[7];
            Payment::create([
                'user_id' => $user['id'],
                'order_id' => $order['id'],
                'trade_sn' => $trade_sn,
                'amount' => $req['amount'],
                'remark' => $payBody,
            ]);
            //请求支付
            $payment = Factory::payment(config('config.wechat_pay'));
            $result = $payment->order->unify([
                'body' => $payBody,
                'out_trade_no' => $trade_sn,
                'total_fee' => $req['amount'],
                'trade_type' => 'JSAPI',
                'openid' => $user['openid'],
            ]);

            if (empty($result['prepay_id'])) {
                $errorMsg = !empty($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'];
                return out(null, 702, $errorMsg);
            }

            $config = $payment->jssdk->bridgeConfig($result['prepay_id'], false);

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return out(null, 500, '下单失败，请稍后重试', $e->getMessage());
        }

        return out($config);
    }

    public function orderCancel()
    {
        $req = request()->post();
        $this->validate(request(), [
            'order_id' => 'required|integer'
        ]);

        $order = Order::with(['orderPatient'])->where('id', $req['order_id'])->first();
        if ($order['order_status'] == 4) {
            return out(null, 10001, '订单已完成，不能取消了');
        }
        if ($order['order_status'] == 5) {
            return out(null, 10002, '订单已取消了，请勿重复操作');
        }

        if ($order['product_type'] == 3) {
            if ($order['order_patient']['appoint_start_time'] - 1800 < time()) {
                return out(null, 10003, '预约时间临近，不能取消订单了');
            }

            DB::beginTransaction();
            try {
                Order::orderCancel($req['order_id']);

                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();

                return out(null, 500, '取消订单失败，请稍后重试', $e->getMessage());
            }
        }
        else {
            return out(null, 10001, '暂时只支持取消门诊预约的订单');
        }

        return out();
    }

    public function orderPackPayList()
    {
        $req = request()->post();
        $this->validate(request(), [
            'docter_id' => 'required|integer',
        ]);
        $user = $this->user;

        $orderPacks = OrderPack::where('user_id', $user['id'])->where('end_time', '>', time())->get()->toArray();
        if (!empty($orderPacks)) {
            foreach ($orderPacks as $k => $v) {
                if ($v['usable_status'] == 0) {
                    unset($orderPacks[$k]);
                }
                if (!empty($v['team_id'])) {
                    if (!TeamDocter::whereIn('team_id', $v['team_id'])->where('docter_id', $req['docter_id'])->exists()) {
                        unset($orderPacks[$k]);
                    }
                }
            }
            $orderPacks = array_values($orderPacks);
        }

        return out($orderPacks);
    }
}
