<?php
namespace app\api\controller;

use app\admin\controller\SettingController;
use app\model\OrderBooks;
use app\model\Orders;
use app\model\ProductSchedules;
use Respect\Validation\Validator;
use support\Redis;
use support\Request;

/**
 *
 */
class OrderController extends base
{
    /**
     * 订单查询
     * @param Request $request
     * @return \support\Response
     * @throws \think\db\exception\DbException
     */
    public function index(Request $request) {
        $mobile = $request->get('mobile');
        if (empty($mobile) || !Validator::mobile()->validate($mobile)) {
            return $this->error('请输入正确的手机号');
        }
        $where = [];
        $os = [1, 7];
        $query = Orders::where($where)
            ->whereLike('mobile', $mobile)
            ->fieldRaw('*, (select 1 from order_books where order_id = orders.id limit 1) as is_book')
            ->whereIn('os', $os)
            ->order('create_at','desc')
            ->order('id','desc');

        $orders = $query->paginate($request->get('limit',10));
        $orders->each(function($order) {
            $order->total_price = bcdiv($order->total_price, 100, 2);
            $order->actual_price = bcdiv($order->actual_price, 100, 2);
        });
        $list = $orders->hidden(['check_sn'])->append(['h5_os_status_name', 'h5_os_name' , 'can_book']);

        return $this->success($list);
    }

    /**
     * 订单详情
     * @param Request $request
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(Request $request) {
        $id = $request->get('order_id');
        if (empty($id)) {
            return $this->error('请选择订单');
        }

        $orderDetail = Orders::where('id', $id)->with(['admin', 'product'])->find();
        if (empty($orderDetail)) {
            return $this->error('订单未找到');
        }
        $orderDetail->admin->job = '金牌旅行管家';
        $orderDetail->admin->service_promise = '我以真诚、热情、专业的态度服务好每一位顾客，全力确保您的旅行体验美好、愉快、安全。';
        // 旅游合同
        $orderDetail->travel_contract = Redis::get(SettingController::SETTING_DOMESTIC) ?? '';
        if ($orderDetail->product->type == 2) {
            $orderDetail->travel_contract = Redis::get(SettingController::SETTING_DOMESTIC) ?? '';
        }

        return $this->success($orderDetail);
    }

    /**
     * 订单预约
     * @param Request $request
     * @return \support\Response
     */
    public function book(Request $request) {
        try {
            $data = $request->post();
            Validator::input($data, [
                'order_id' => Validator::number()->length(1, 10)->setName('订单号'),
                'travel_date' => Validator::date()->setName('出游日期'),
                'num' => Validator::number()->length(1, 3)->setName('出游人数'),
                'name' => Validator::length(1, 10)->setName('出行人名称'),
                'mobile' => Validator::mobile()->setName('联系电话'),
            ]);

            if (!$order = Orders::where('id', $data['order_id'])->find()) {
                return $this->error('订单未找到');
            }
            if ($order->is_apply_appointment == 1) {
                return $this->error('已申请预约');
            }
            if ($data['code_pic'] && is_array($data['code_pic'])) {
                $data['code_pic'] = json_encode($data['code_pic']);
            }
            // 检查排期
            $schedules = ProductSchedules::where(['date' => $data['travel_date'], 'third_product_id' => $order->product_id])->find();
            if (!empty($schedules) && $schedules->num > 0) {
                // 已预约人数
                $booksNum = OrderBooks::join('orders', 'orders.id=order_books.order_id')
                    ->where(['order_books.travel_date' => $data['travel_date'], 'orders.product_id' => $order->product_id])
                    ->sum('order_books.num');

                if (($schedules->num-$booksNum) < $data['num']) {
                    return $this->error('当前日期预约已满,请选择其他日期');
                }
            }

            $res = OrderBooks::create($data);
            if (!empty($res)) {
                $order->is_apply_appointment = 1;
                $order->save();
            }
            return $this->success($res);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}