<?php

namespace App\Http\Controllers\Main;


use App\Constant\PayConstant;
use App\Http\Controllers\Support\BaseController;
use App\Types\EventOrderStatus;
use App\Types\EventShowStatus;
use Carbon\Carbon;
use Edwin404\Base\Support\InputHelper;
use Edwin404\Base\Support\ModelHelper;
use Edwin404\Base\Support\PageHelper;
use Edwin404\Base\Support\Response;
use Edwin404\Common\Helpers\AgentHelper;
use Edwin404\Config\Facades\ConfigFacade;
use Edwin404\Member\Services\MemberService;
use Edwin404\Member\Support\MemberLoginCheck;
use Edwin404\Oauth\Types\OauthType;
use Edwin404\Pay\Services\PayOrderService;
use Edwin404\Pay\Types\PayOrderStatus;
use Edwin404\Pay\Types\PayType;
use Edwin404\Tecmz\Helpers\PayHelper;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;

class MemberOrderController extends BaseController implements MemberLoginCheck
{
    public function index()
    {
        $page = intval(Input::get('page', 1));
        $pageSize = 12;
        $option = [];
        $option['order'] = ['id', 'desc'];
        $option['where'] = [];
        $option['where'] ['memberUserId'] = $this->memberUserId();
        if ($status = intval(Input::get('status', 0))) {
            $option['where']['status'] = $status;
        }

        $paginateData = ModelHelper::modelPaginate('event_order', $page, $pageSize, $option);
        $orders = $paginateData['records'];
        $pageHtml = PageHelper::render($paginateData['total'], $pageSize, $page, View::shared('request_path') . '?page={page}');

        if (!empty($orders)) {
            $orderIds = [];
            foreach ($orders as $order) {
                $orderIds[] = $order['id'];
            }
            $orderItems = ModelHelper::model('event_order_item')
                ->whereIn('orderId', $orderIds)
                ->orderBy('id', 'asc')
                ->get()->toArray();
            ModelHelper::modelJoin($orderItems, 'eventId', '_event', 'event', 'id');
            foreach ($orders as $orderIndex => $order) {
                if (!isset($orders[$orderIndex]['_items'])) {
                    $orders[$orderIndex]['_items'] = [];
                }
                foreach ($orderItems as $orderItem) {
                    if ($orderItem['orderId'] == $order['id']) {
                        $orders[$orderIndex]['_items'][] = $orderItem;
                    }
                }
            }
        }

        return $this->_view('member.order.index', compact('orders', 'pageHtml'));
    }

    public function payWatch($orderId)
    {
        $order = ModelHelper::load('event_order', ['id' => $orderId, 'memberUserId' => $this->memberUserId()]);

        switch ($order['status']) {
            case EventOrderStatus::WAIT_PAY:
                return Response::send(0, null, ['status' => 'new']);
            case EventOrderStatus::WAIT_SIGN_IN:
                return Response::send(0, null, ['status' => 'payed']);
            case EventOrderStatus::EXPIRED:
                return Response::send(0, null, ['status' => 'expired']);
            default:
                return Response::send(-1, 'order status error');
        }
    }

    public function detail($orderId)
    {
        $order = ModelHelper::load('event_order', ['id' => $orderId, 'memberUserId' => $this->memberUserId()]);
        if (empty($order)) {
            return Response::send(-1, '订单不存在');
        }
        $order['_items'] = ModelHelper::find('event_order_item', ['orderId' => $order['id']]);
        ModelHelper::modelJoin($order['_items'], 'eventId', '_event', 'event', 'id');
        return $this->_view('member.order.detail', compact('order'));
    }

    public function pay(PayOrderService $payOrderService,
                        MemberService $memberService,
                        $orderId)
    {
        $order = ModelHelper::load('event_order', ['id' => $orderId, 'memberUserId' => $this->memberUserId()]);
        if (empty($order)) {
            return Response::send(-1, 'order not found');
        }
        if ($order['status'] != EventOrderStatus::WAIT_PAY) {
            return Response::send(-1, '订单不能支付');
        }

        // 免费的直接支付成功
        if (!($order['payFee'] > 0)) {
            ModelHelper::updateOne('event_order', ['id' => $order['id']], ['status' => EventOrderStatus::COMPLETED, 'payTime' => Carbon::now(),]);
            ModelHelper::updateOne('event_order_item', ['id' => $order['id']], ['orderStatus' => EventOrderStatus::COMPLETED]);
            return Response::send(0, null, null, '/member/order_detail/' . $orderId);
        }

        if (Request::isMethod('post')) {
            $payType = InputHelper::getType('payType', PayType::class, null);
            if (empty($payType)) {
                return Response::send(-1, '支付方式错误');
            }
            if (!PayHelper::isPayEnable($payType)) {
                return Response::send(-1, '支付方式未开启');
            }

            $data = [];
            $data['payType'] = $payType;

            switch ($payType) {
                case PayType::ALIPAY:
                    $ret = $payOrderService->create(
                        PayConstant::BIZ_ORDER,
                        $order['id'],
                        $payType,
                        $order['payFee'],
                        '订单:' . $order['sn'],
                        '订单:' . $order['sn'],
                        '/member/order_detail/' . $order['id'],
                        ['alipay_wap' => $this->isMobile() ? true : false]
                    );
                    if ($ret['code']) {
                        return Response::send(-1, $ret['msg']);
                    }
                    $data['payRedirect'] = $ret['data']['link'];
                    $data['successRedirect'] = '/member/order_detail/' . $order['id'];
                    return Response::send(0, null, $data);

                case PayType::WECHAT_MOBILE:

                    $openId = $memberService->getOauthOpenId($this->memberUserId(), OauthType::WECHAT_MOBILE);
                    if (empty($openId)) {
                        return Response::send(-1, null, null, '/oauth_login_' . OauthType::WECHAT_MOBILE . '?redirect=' . urlencode(View::shared('request_path')));
                    }

                    $ret = $payOrderService->create(
                        PayConstant::BIZ_ORDER,
                        $order['id'],
                        $payType,
                        $order['payFee'],
                        '订单:' . $order['sn'],
                        '订单:' . $order['sn'],
                        '/member/order_detail/' . $order['id'],
                        ['openId' => $openId]
                    );
                    if ($ret['code']) {
                        return Response::send(-1, $ret['msg']);
                    }
                    $data['json'] = $ret['data']['json'];
                    $data['successRedirect'] = $ret['data']['successRedirect'];
                    return Response::send(0, null, $data);

                case PayType::WECHAT:

                    $ret = $payOrderService->create(
                        PayConstant::BIZ_ORDER,
                        $order['id'],
                        $payType,
                        $order['payFee'],
                        '订单:' . $order['sn'],
                        '订单:' . $order['sn'],
                        '/member/order_detail/' . $order['id'],
                        []
                    );
                    if ($ret['code']) {
                        return Response::send(-1, $ret['msg']);
                    }
                    $data['codeUrl'] = $ret['data']['codeUrl'];
                    $data['successRedirect'] = $ret['data']['successRedirect'];
                    $data['watchUrl'] = '/member/order_pay_watch/' . $order['id'];
                    return Response::send(0, null, $data);

                default:
                    return Response::send(-1, '支付方式错误');
            }
        }

        return $this->_view('member.order.pay', compact('order'));
    }

}