<?php

namespace Modules\Mall\Http\Controllers\Admin;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Support\MessageBag;
use Modules\Mall\Facades\Item;
use Modules\Mall\Http\Controllers\Admin\Action\Order\Delivered;
use Modules\Mall\Http\Controllers\Admin\Action\Order\Pay;
use Modules\Mall\Http\Exporter\OrderExporter;
use Modules\Mall\Models\Address;
use Modules\Mall\Models\Express;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\GoodsSku;
use Modules\Mall\Models\Order;
use Modules\Mall\Models\OrderExpress;
use Modules\Mall\Models\Shop;
use Modules\User\Models\User;
use Modules\Mall\Facades\Order as OrderFacade;

class StockOrderBySystemController extends AdminController
{

    protected $title = '公司线下发货';

    protected function grid(): Grid
    {
        $grid = new Grid(new Order());

        $grid->model()
            ->where('type', Order::TYPE_SAMPLE)
            ->where('channel', Order::CHANNEL_SYSTEM)
            ->with(['shop', 'user', 'items'])
            ->withCount('versions');


        $grid->quickSearch('order_no')->placeholder('搜索订单编号');

        $grid->filter(function (Grid\Filter $filter) {
            $filter->scope('unPay', '未付款')->unPay();
            $filter->scope('paid', '待发货')->paid();
            $filter->scope('delivered', '已发货')->delivered();
            $filter->scope('signed', '已签收')->signed();
            $filter->scope('completed', '已完成')->completed();

            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->like('order_no', '订单编号');
//                $filter->equal('shop_id', '所属店铺')->select(Shop::pluck('name', 'id'));
                $filter->equal('user_id', '提货用户')->select()->ajax(route('admin.user.users.ajax'));
//                $filter->equal('type', '订单类型')->select(Order::TYPE_MAP);
            });
            $filter->column(1 / 2, function (Grid\Filter $filter) {
//                $filter->between('created_at', '下单时间')->datetime();
//                $filter->between('paid_at', '付款时间')->datetime();
//                $filter->between('expired_at', '过期时间')->datetime();
            });
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableEdit();
            $actions->disableDelete();
            $actions->disableView();
            if ($actions->row->can('pay') && $this->row->type == Order::TYPE_NORMAL) {
                $actions->add(new Pay());
            }
            if ($actions->row->can('deliver')) {
                $actions->add(new Delivered);
            }
        });

        $grid->model()->with(['shop', 'user.info']);

        $grid->column('order_no', '订单编号')->display(function () {
            return sprintf('<a href="%s">%s</a>', route('admin.mall.stock_orders.show', $this), $this->order_no);
        });
//        $grid->column('shop.name', '所属店铺');
        $grid->column('user.username', '提货用户');
//        $grid->column('amount', '商品金额');
//        $grid->column('freight', '运费');
        $grid->column('qty', '提货数量')
            ->display(function () {
                return $this->items()->sum('qty');
            });
//        $grid->column('订单金额')->display(function () {
//            return $this->total;
//        });
        $grid->column('state', '订单状态')
            ->display(function () {
                return $this->state_text;
            })
            ->label();
        $grid->column('type', '订单类型')->using(Order::TYPE_MAP)->label();
//        $grid->column('paid_at', '支付时间')->sortable();
//        $grid->column('expired_at', '过期时间')->sortable();
        $grid->column('versions_count', '操作日志')->link(function () {
            return route('admin.mall.versions', [
                'model' => get_class($this),
                'key'   => $this->id,
            ]);
        }, '_self');
        $grid->column('created_at', '下单时间')->sortable();

        $grid->disableExport(false);
        $grid->export(function ($export) {
            $export->column('order_no', function ($value, $original) {
                return strip_tags($value)."\n";
            });
            $export->column('type', function ($value, $original) {
                return strip_tags($value);
            });
            $export->column('state', function ($value, $original) {
                return strip_tags($value);
            });

            $export->except(['versions_count', 'paid_at', 'expired_at']);

            $export->filename($this->title.date("YmdHis"));
        });
        return $grid;
    }

    /**
     * Notes: 添加订单
     *
     * @Author: 玄尘
     * @Date: 2022/7/29 13:21
     * @return Form
     */
    public function form(): Form
    {
        $form = new Form(new Order());

        $form->select('user_id', '会员')
            ->options(function ($userId) {
                $user = User::find($userId);

                if ($user) {
                    return [$user->id => $user->username.' ['.$user->info->nickname.']'];
                }
            })
            ->ajax(route('admin.user.users.ajax'))
            ->load('address_id', route('admin.mall.ajax.address'))
            ->required();

        $form->select('address_id', '收货地址')
            ->load('goods_sku_id', route('admin.mall.ajax.goods'))
            ->required();
        $form->html("<div id='showImage' style='margin-top:10px'><a href='/admin/mall/addresses/create'>添加收货地址</a></div>",
            '');
        $form->select('goods_sku_id', '剩余箱数')->required();

        $form->number('qty', '发货箱数')->default(1);
        $form->radioButton('type', '方式')
            ->options(OrderExpress::TYPE_MAP)
            ->required()
            ->when(OrderExpress::TYPE_EXPRESS, function ($form) {
                $form->select('express_id', '物流')
                    ->options(function () {
                        return Express::pluck('name', 'id');
                    })
                    ->rules('required', ['required' => '物流公司必须选择']);
                $form->text('express_no', '物流单号')->rules('required');

            })
            ->when(OrderExpress::TYPE_LOGISTICS, function ($form) {
                $form->text('person', '经办人');
            });

        return $form;
    }

    /**
     * Notes: 获取提交数据
     *
     * @Author: 玄尘
     * @Date: 2022/7/29 14:16
     * @return mixed|void
     * @throws \Exception
     */
    public function store()
    {
        $user_id      = request('user_id', 0);
        $remark       = request('remark', '后台录入');
        $address_id   = request('address_id', 0);
        $goods_sku_id = request('goods_sku_id', 0);
        $qty          = request('qty', 0);
        $express_id   = request('express_id');
        $express_no   = request('express_no');
        $type         = request('type');
        $person       = request('person');

        $user      = User::find($user_id);
        $address   = Address::find($address_id);
        $goods_sku = GoodsSku::find($goods_sku_id);

        if (! $goods_sku) {
            $error = new MessageBag([
                'title'   => '错误',
                'message' => '未找到商品',
            ]);

            return back()->withInput()->with(compact('error'));
        }

        $stockData = $user->getStockData();

        if ($qty > $stockData['residue']) {
            $error = new MessageBag([
                'title'   => '错误',
                'message' => '用户库存不足',
            ]);

            return back()->withInput()->with(compact('error'));
        } else {
            $detail = collect();
            $item   = new Item($goods_sku, $address, $qty);
            $detail->push($item);

            $orders = (new OrderFacade)->user($user)
                ->remark($remark)
                ->channel(Order::CHANNEL_SYSTEM)
                ->type(Order::TYPE_SAMPLE)
                ->items($detail)
                ->address($address)
                ->create();

            foreach ($orders as $order) {
                $order->pay();//设置已支付
                $order->deliver($express_id, $express_no, $type, $person);//发货
            }

            admin_toastr('操作完成');
            return redirect()->to('/admin/mall/stock_orders_by_system?user_id='.$user->id);
        }
    }


    /**
     * Notes   : 订单详情
     *
     * @Date   : 2021/3/16 1:46 下午
     * @Author : < Jason.C >
     * @param  string  $orderNo  订单的 order_no
     */
    protected function detail(string $orderNo)
    {
        $order = Order::query()->firstWhere(['order_no' => $orderNo]);

        return view('mall::admin.stock_order.detail', compact('order'));
    }

}
