<?php

namespace App\Http\Controllers\Admin;


use App\Types\EventOrderStatus;
use Carbon\Carbon;
use Edwin404\Admin\Cms\Field\FieldDatetime;
use Edwin404\Admin\Cms\Field\FieldEmpty;
use Edwin404\Admin\Cms\Field\FieldModel;
use Edwin404\Admin\Cms\Field\FieldSelect;
use Edwin404\Admin\Cms\Field\FieldText;
use Edwin404\Admin\Cms\Handle\BasicCms;
use Edwin404\Admin\Helpers\AdminLogHelper;
use Edwin404\Admin\Http\Controllers\Support\AdminCheckController;
use Edwin404\Base\Support\InputHelper;
use Edwin404\Base\Support\ModelHelper;
use Edwin404\Base\Support\RequestHelper;
use Edwin404\Base\Support\Response;
use Edwin404\Demo\Helpers\DemoHelper;
use Edwin404\Shop\Services\GoodsService;
use Edwin404\Shop\Types\OrderStatus;
use Edwin404\SmartAssets\Helper\AssetsHelper;
use Edwin404\Tecmz\Helpers\AdminCmsHelper;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;

class OrderController extends AdminCheckController
{
    private $cmsConfigBasic = [
        'model' => 'event_order',
        'pageTitle' => '订单管理',
        'group' => 'data',
        'primaryKeyShow' => false,
        'fields' => [
            'sn' => ['type' => FieldText::class, 'title' => '订单号', 'list' => true, 'search' => true,],
            'created_at' => ['type' => FieldDatetime::class, 'title' => '时间', 'list' => true,],
            'totalFee' => ['type' => FieldText::class, 'title' => '价格', 'list' => true,],
            'payFee' => ['type' => FieldText::class, 'title' => '支付价格', 'list' => true,],
            'status' => ['type' => FieldSelect::class, 'title' => '状态', 'list' => true, 'edit' => true, 'add' => true, 'search' => true, 'optionType' => EventOrderStatus::class],
            '_memberUser' => ['type' => FieldEmpty::class, 'title' => '用户', 'list' => true,],
            '_item' => ['type' => FieldEmpty::class, 'title' => '报名信息', 'list' => true,],
            '_action' => ['type' => FieldEmpty::class, 'title' => '操作', 'list' => true,],
        ]
    ];

    public function dataProcessView(&$item, &$record)
    {
        $statusColorMap = [
            EventOrderStatus::WAIT_PAY => '<span class="uk-text-muted">待付款</span>',
            EventOrderStatus::COMPLETED => '<span class="uk-text-success">已完成</span>',
            EventOrderStatus::EXPIRED => '<span class="uk-text-muted">已过期</span>',
        ];
        if (isset($statusColorMap[$record['status']])) {
            $item['status'] = $statusColorMap[$record['status']];
        }

    }

    public function dataProcessViewField($key, &$record)
    {
        switch ($key) {
            case '_item':
                $orderItems = ModelHelper::find('event_order_item', ['orderId' => $record['id']]);
                ModelHelper::modelJoin($orderItems, 'eventId', '_event', 'event', 'id');
                return View::make('admin.order.item', [
                    'orderItems' => $orderItems,
                ])->render();
                break;
            case '_memberUser':
                return AdminCmsHelper::memberUserId($record['memberUserId']);
            case '_action':
                return View::make('admin.order.viewListAction', [
                    'record' => $record,
                ])->render();
        }
    }

    public function dataList(BasicCms $basicCms)
    {
        return $basicCms->executeList($this, $this->cmsConfigBasic);
    }

    public function dataListWaitPay(BasicCms $basicCms)
    {
        $this->cmsConfigBasic['fields']['status']['search'] = false;
        $this->cmsConfigBasic['listFilter'] = ['where' => ['status' => OrderStatus::WAIT_PAY]];
        return $basicCms->executeList($this, $this->cmsConfigBasic);
    }

    public function dataListCompleted(BasicCms $basicCms)
    {
        $this->cmsConfigBasic['fields']['status']['search'] = false;
        $this->cmsConfigBasic['listFilter'] = ['where' => ['status' => EventOrderStatus::COMPLETED]];
        return $basicCms->executeList($this, $this->cmsConfigBasic);
    }

    public function dataListExpired(BasicCms $basicCms)
    {
        $this->cmsConfigBasic['fields']['status']['search'] = false;
        $this->cmsConfigBasic['listFilter'] = ['where' => ['status' => EventOrderStatus::EXPIRED]];
        return $basicCms->executeList($this, $this->cmsConfigBasic);
    }

    public function detail($id)
    {
        $order = ModelHelper::load('event_order', ['id' => $id]);
        $order['_items'] = ModelHelper::find('event_order_item', ['orderId' => $order['id']]);
        ModelHelper::modelJoin($order['_items'], 'eventId', '_event', 'event', 'id');
        return view('admin.order.view', [
            'order' => $order,
        ]);
    }

    public function changeFee($id)
    {
        $order = ModelHelper::load('event_order', ['id' => $id]);
        if ($order['status'] != EventOrderStatus::WAIT_PAY) {
            return Response::send(-1, '订单状态错误');
        }
        $order['_items'] = ModelHelper::find('event_order_item', ['orderId' => $order['id']]);
        ModelHelper::modelJoin($order['_items'], 'eventId', '_event', 'event', 'id');

        if (RequestHelper::isPost()) {
            if (DemoHelper::shouldDenyAdminDemo()) {
                return Response::send(-1, '演示账号禁止修改信息');
            }
            $payFee = Input::get('payFee');
            ModelHelper::updateOne('event_order', ['id' => $id], ['payFee' => $payFee]);
            AdminLogHelper::addInfoLogIfChanged('修改订单价格(ID:' . $id . ')', [
                '金额' => $order['payFee'],
            ], [
                '金额' => $payFee
            ]);
            return Response::send(0, null, null, '[js]$.dialogClose()');
        }
        return view('admin.order.changeFee', [
            'order' => $order,
        ]);
    }

    public function cancel($id)
    {
        if (DemoHelper::shouldDenyAdminDemo()) {
            return Response::send(-1, '演示账号禁止修改信息');
        }
        $order = ModelHelper::load('event_order', ['id' => $id]);
        switch ($order['status']) {
            case OrderStatus::WAIT_PAY:
                ModelHelper::updateOne('event_order', ['id' => $id], ['status' => EventOrderStatus::EXPIRED]);
                AdminLogHelper::addInfoLog('取消订单(ID:' . $id . ')');
                return Response::send(0, null, null, '[js]window.__cms.action.refresh();');
        }
        return Response::send(-1, '订单状态错误');
    }

    public function pay($id)
    {
        if (DemoHelper::shouldDenyAdminDemo()) {
            return Response::send(-1, '演示账号禁止修改信息');
        }
        $order = ModelHelper::load('event_order', ['id' => $id]);
        switch ($order['status']) {
            case OrderStatus::WAIT_PAY:
                ModelHelper::updateOne('event_order', ['id' => $id], ['status' => EventOrderStatus::COMPLETED, 'payTime' => Carbon::now(),]);
                ModelHelper::updateOne('event_order_item', ['orderId' => $id], ['orderStatus' => EventOrderStatus::COMPLETED]);
                AdminLogHelper::addInfoLog('设置订单已支付(ID:' . $id . ')');
                return Response::send(0, null, null, '[js]window.__cms.action.refresh();');
        }
        return Response::send(-1, '订单状态错误');
    }
}