<?php
namespace Modules\Project\Http\Controllers\Admin;

use Modules\Project\Extensions\OrderExcelExpoter;
use App\Http\Controllers\Controller;
use Encore\Admin\Grid\Column;
use Illuminate\Support\Facades\Input;
use Modules\Project\Entities\Express;
use Modules\Project\Entities\Order;
use Modules\Project\Extensions\OrderStatus;
use Modules\Project\Services\Order\ChangeStatus;
use Modules\Project\Services\OrderService;
use SMG\Admin\Controllers\ModelForm;
use SMG\Admin\Facades\Admin;
use SMG\Admin\Form;
use SMG\Admin\Grid;
use SMG\Admin\Layout\Content;

class OrderController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->body('

            <script type="text/javascript">
            
                function order_delivery_submit(){
                    console.log($("#order_delivery_form").serializeArray());
                    $.ajax({
                        url:$("#order_delivery_form").attr("action"),
                        async:false,
                        data:$("#order_delivery_form").serializeArray(),
                        type:"POST",
                        success:function(){
                            $("#order_delivery").modal("hide");
                            setTimeout(function(){
                                $.pjax.reload("#pjax-container");
                                toastr.success("操作成功 !");
                            },200)
                        },
                        error:function(){
                            toastr.success("操作失败 !");
                        }
                    }
                    );
                    
                    
                    
                    return false;
                }
            
            </script>
            
            
            <!-- 模态框 -->
    <div class="modal fade" id="order_delivery">
        <div class="modal-dialog">
            <div class="modal-content">

                <!-- 模态框头部 -->
                <div class="modal-header">
                    <h4 class="modal-title">发货</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>

                <!-- 模态框主体 -->
                <div class="modal-body">

                    <form id="order_delivery_form" method="post" accept-charset="UTF-8" onsubmit="return order_delivery_submit()">

                        <div class="form-group">
                            <label for="user_name">姓名:</label>
                            <input type="text" class="form-control" value="" id="order_delivery_user_name" disabled="disabled">
                        </div>

                        <div class="form-group">
                            <label for="mobile">联系电话:</label>
                            <input type="text" class="form-control" value="" id="order_delivery_mobile" disabled="disabled">
                        </div>

                        <div class="form-group">
                            <label for="address">地址:</label>
                            <input type="text" class="form-control" value="" id="order_delivery_address" disabled="disabled">
                        </div>

                        <div class="form-group">
                            <label for="express_id">快递公司:</label>
                            <input type="text" class="form-control" name="express_id" id="order_delivery_express_id">
                        </div>

                        <div class="form-group">
                            <label for="tracking_no">快递号:</label>
                            <input type="text" class="form-control" name="tracking_no" id="order_delivery_tracking_no">
                        </div>
                        
                        <input type="hidden" name="_token" value="" id="order_delivery_token">

                        <button type="submit" class="btn btn-primary">提交</button>
                    </form>

                </div>

                <!-- 模态框底部 -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>

            </div>
        </div>
    </div>
            
            ');

            Admin::script("
            $.get('/admin/order/transport', function (data) {
                
                $('#order_delivery_express_id').select2({
                    data: $.map(data, function (d) {
                        d.id = d.id;
                        d.text = d.text;
                        return d;
                    })
                }).trigger('change');
            
            });
            
            $('#order_delivery').on('shown.bs.modal', function (event) {
              var button = $(event.relatedTarget) // Button that triggered the modal
              var id = button.data('id') 
              var username = button.data('username') 
              var mobile = button.data('mobile') 
              var address = button.data('address')
              $('#order_delivery_form').attr('action','/admin/order/'+id+'/delivery');
              $('#order_delivery_user_name').val(username);
              $('#order_delivery_mobile').val(mobile);
              $('#order_delivery_address').val(address);
              $('#order_delivery_token').val(LA.token);
              
            })
        
        ");

            $content->body($this->grid());
        });
    }

    public function grid()
    {
        Column::extend('order_status', OrderStatus::class);

        Column::extend('order_goods', function ($order_goods) {
            $res = [];

            foreach ($order_goods as $v) {
                $spec_srt = '';

                $spec = json_decode($v['spec'], true);
                /*
                foreach ($spec as $vv) {
                    $spec_srt = $spec_srt." [{$vv['group']}:{$vv['spec_name']}]";
                }
                */

                $res[] = $v['goods_title'].$spec_srt." × {$v['qty']}";
            }

            return join("<hr/>\n", $res);
        });

        $grid = Admin::grid(Order::class, function (Grid $grid) {
            $grid->enableFilter();

            //$grid->id('ID');
            $grid->order_no('订单号');

            $grid->user_id('用户id');

            $grid->user()->name('用户名');

            $grid->orderGoods('商品')->order_goods();

            /*
            $grid->column('address', '地址')->display(function($a){
                return $this->address->area->getArea() .   $this->address->detail;
            });
            */

            $grid->goods_price('商品价格');

            $grid->discount_amount('优惠金额');

            //$grid->payable_amount('应付金额');

            $grid->paid_amount('已支付金额');

            $grid->status('订单状态')->order_status();

            $grid->remarks('订单备注');

            $grid->created_at('创建时间');

            $grid->actions(function ($actions) {
                $actions->disableDelete();

                $actions->disableView();
            });

            $grid->option('useExporter', true);

            $grid->filter(function ($filter) {

                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                // 在这里添加字段过滤器
                $filter->like('order_no', '订单号');

                $filter->in('status', '订单状态')->multipleSelect([
                    Order::STATUS_DEFAULT => '待付款',
                    Order::STATUS_CANCEL => '已取消',
                    Order::STATUS_PAID => '已支付',
                    Order::STATUS_SHIPPED => '已发货',
                    Order::STATUS_COMPLETE => '已完成',
                ]);
            });

            $grid->disableCreateButton();

            $grid->model()->orderBy('id', 'desc');

            $grid->exporter(new OrderExcelExpoter());
        });

        return $grid;
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('编辑');

            $content->description('编辑');

            $form = $this->form()->edit($id);

            $content->body($form);
        });
    }

    public function form()
    {
        return Admin::form(Order::class, function (Form $form) {
            $order = '';

            $form->display('id', 'ID');

            $form->display('user_id', '用户id');

            $form->display('order_no', '订单号');

            $form->display('goods_price', '商品价格');

            $form->display('discount_amount', '优惠金额');

            $form->display('payable_amount', '应付金额');

            $form->display('paid_amount', '已支付金额');

            $form->select('status', '订单状态')->options([
                Order::STATUS_DEFAULT => '待支付',
                Order::STATUS_CANCEL => '已取消',
                Order::STATUS_PAID => '已支付',
                Order::STATUS_SHIPPED => '已发货',
                //Order::STATUS_CONFIRM => '已确认',
                Order::STATUS_COMPLETE => '已完成',
            ]);

            $form->textarea('remarks', '订单备注');

            $form->html('<hr>收货信息', '');

            $id = request()->route('order');
            if ($id) {
                $form->text('address.name', '收货人');
                $form->text('address.mobile', '手机号');
                /*
                $form->display('address.detail', '地址');
                $form->display('address.area.getArea()', '地址');
                */
                $order = Order::find($id);
                $form->html("<div class=\"box-body\">{$order->address->area->getArea()}{$order->address->detail}</div>", '地址');
            }

            $form->smg_select('express_id', '快递公司')->options('/admin/order/transport');

            $form->text('tracking_no', '快递号');

            $form->display('created_at', '创建时间');

            $form->display('updated_at', '更新时间');

            $form->saving(function ($form) use ($order) {
                if ($order && $form->status != $order->status) {
                    if ($order->status == Order::STATUS_CANCEL) {
                        throw new \Exception('已取消订单 无法修改状态');
                    } elseif ($order->status == Order::STATUS_COMPLETE) {
                        throw new \Exception('已完成订单 无法修改状态');
                    } else {
                        $order_service = new ChangeStatus($form->model());

                        $order_service->before_status = $form->status;

                        $form->order_service = $order_service;
                    }
                }
            });

            $form->saved(function ($form) {
                if ($form->order_service) {
                    $form->order_service->is_order_save = false;

                    $form->order_service->after_status = $form->model()->status;

                    $form->is_order_save = false;

                    $form->order_service->changeStatus();
                }
            });
        });
    }

    /**
     * 发货
     *
     * @param $id
     *
     * @throws \Exception
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function delivery($id)
    {
        $s_order = new OrderService(Order::find($id));

        $input_data = Input::toArray();

        $log_data = [
            'extend' => json_encode($input_data),
            'remarks' => '商家发货',
        ];

        $order_data = [
            'express_id' => $input_data['express_id'],
            'tracking_no' => $input_data['tracking_no'],
        ];

        $s_order->delivery($order_data, $log_data);

        return redirect('/admin/order');
    }

    public function transport()
    {
        $list = (new Express())->all()->toArray();

        $res = [];

        foreach ($list as $k => $v) {
            $res[] = [

                'id' => $v['id'],

                'text' => $v['name'],

            ];
        }

        return $res;
    }
}
