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

use App\Http\Controllers\Controller;
use Encore\Admin\Form\Field\Embeds;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Modules\Project\Entities\Transport;
use Modules\Project\Entities\TransportExtend;
use Modules\Project\Entities\TransportExtendArea;
use Modules\Project\Services\TransportService;
use SMG\Admin\Controllers\ModelForm;
use SMG\Admin\Facades\Admin;
use SMG\Admin\Form;
use SMG\Admin\Grid;
use SMG\Admin\Layout\Content;
use SMG\Area\AreaModel;

class TransportExtendController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        Admin::script('jQuery("a.grid-refresh").remove();');

        return Admin::content(function (Content $content) {
            $content->header('运输模板物流');
            $content->description('说明');
            $content->body($this->withlog());
        });

        return;
    }

    public function withlog()
    {
        return Admin::form(Transport::class, function (Form $form) {
            $all = $form->model()->where('id', '>', 0)->get();

            foreach ($all as $k => $transport) {
                $transport->transportExtends;
                //dump($transport->toArray());
                $form->view($transport->id);
                $form->html('<div class="form-control-static">'.$transport->name.'</div>', '运送方式');
                $form->html($this->transport_extends($transport->id)->render())->setWidth(12, 0);
                //$form->divider();
            }

            $form->setAction('#');

            $form->tools(function ($tools) {
                // 去掉返回按钮
                $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                $tools->add('<a class="btn btn-sm btn-success" href="/admin/transport/create"><i class="fa fa-save"></i>&nbsp;&nbsp;新增快递模板</a>');
            });
            $form->disableSubmit();
            $form->disableReset();
        });
    }

    public function transport_extends($transport_id)
    {
        $grid = Admin::grid(TransportExtend::class, function (Grid $grid) use ($transport_id) {
            $grid->resource('/admin/transport_extend');
            $grid->model()->where('transport_id', $transport_id);

            $grid->column('extendAreas', '运送到')->display(function () {
                $TransportExtendArea = new TransportExtendArea();
                $TransportExtendArea = $TransportExtendArea->where('transport_extend_id', '=', $this->id)->get();
                $areas = '';
                $collection = $TransportExtendArea->each(function ($item, $key) use (&$areas) {
                    $areas = $item->provinceArea->name.'&nbsp;&nbsp;'.$areas;
                });

                return $areas;
            })->limit(200);

            //$grid->snum('首重（kg）');
            $grid->sprice('首重运费（元）');
            //$grid->xnum('续重（kg）');
            $grid->xprice('续重运费（元）');

            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->disableRowSelector();

            $grid->tools(function ($tools) use ($transport_id) {
                $html = '<a class="btn btn-sm btn-success" href="/admin/transport_extend/create?transport_id='.$transport_id.'"><i class="fa fa-save"></i>&nbsp;&nbsp;新增物流城市</a>';
                $tools->append($html);
            });
        });

        return $grid;
    }

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

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        if (($province_id = request('province_id')) && request()->method() == 'GET') {
            $embeds = new Embeds('city', ['附加运费', $this->getTypeCity($province_id)]);
            $embeds->setForm($this->form());
            $content = $embeds->render()->render();
            //$content .= Admin::script();

            return $content;
        }

        return Admin::content(function (Content $content) {
            $content->header('创建');
            $content->description('说明');

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

    /**
     * 获取省下城市配置
     *
     * @param $province_id
     *
     * @return \Closure
     */
    protected function getTypeCity($province_id)
    {
        $city = TransportService::getCityPreay($province_id);

        return function ($form) use ($city) {
            if (!is_array($city)) {
                return;
            }
            foreach ($city as $key => $one) {
                $elemnt = null;
                foreach ($one as $method => $args) {
                    if (!$elemnt) {
                        $elemnt = $form->$method(...$args);
                    } else {
                        $elemnt->$method(...$args);
                    }
                }
            }
        };
    }

    protected function form()
    {
        Admin::addJs('/js/admin/transport.js');

        return Admin::form(TransportExtend::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->number('snum', '首重（kg）')->default(1)->rules('required');
            $form->currency('sprice', '首重运费（元）')->symbol('￥')->rules('required');
            $form->number('xnum', '续重')->default(1);
            $form->currency('xprice', '续重运费（元）')->symbol('￥')->help('运费计算方法为 重量(公斤)×2×续重运费+首重运费-续重运费');
            $form->html('', '选择运费省');
            $TransportExtend = new TransportExtend();

            $id = request()->route('transport_extend');
            $transport_id = request()->transport_id;
            $area = new AreaModel();
            $TransportExtendArea = new TransportExtendArea();
            if ($id) {
                $row = $form->model()->find($id);
                $transport_id = $row->transport_id;
            }
            if ($transport_id) {
                $form->hidden('transport_id')->value($transport_id);
            }
            $province_ids = $TransportExtendArea->where('transport_id', $transport_id);

            if ($id) {
                $province_ids = $province_ids->where('transport_extend_id', '<>', $id);
            }
            $province_ids = $province_ids->get()->pluck('province_id')->toArray();

            $provinces = $citys = [];
            $provinces = $area->whereNull('parent_id');
            if ($province_ids) {
                $provinces = $provinces->whereNotIn('id', $province_ids);
            }
            $provinces = $provinces->get()->pluck('name', 'id')->toArray();

            $form->checkbox('province_ids', '')->options($provinces)->stacked()->setWidth(2, 2);
        });
    }

    public function saveform($request, $id)
    {
        $validator = Validator::make($request->all(), [
            'snum' => 'required',
            'sprice' => 'required',
            'xnum' => 'required|gt:0',
            'province_ids' => 'required',
        ], [], $this->messages());

        if ($validator->fails()) {
            $errors = $validator->errors();
            foreach ($errors->all() as $message) {
                admin_toastr($message, 'error');
            }

            return false;
        }

        if ($id) {
            //edit
            $model = new TransportExtend();
            $info = $model->findorFail($id);
        } else {
            $info = new TransportExtend();
            $info->transport_id = request()->transport_id;
        }
        $info->snum = $request->snum ? $request->snum : 1;
        $info->sprice = $request->sprice;
        $info->xnum = $request->xnum ? $request->xnum : 1;
        $info->xprice = $request->xprice ? $request->xprice : 0;
        $province_ids = '';

        foreach ($request->province_ids as $key => $val) {
            if ($val) {
                $area_data[] = ['province_id' => $val,'transport_id' => $info->transport_id];
                $province_ids .= trim($val, ',').',';
            }
        }
        $province_ids = trim($province_ids, ',');

        if (empty($province_ids)) {
            $message = '提交失败,选择区域为空';
            admin_toastr($message, 'error');

            return false;
        }
        $info->province_ids = $province_ids;

        $info->save();
        $bool = $info->extendAreas()->delete();
        if (isset($area_data)) {
            $info->extendAreas()->createMany($area_data);
        }

        return true;
    }

    public function store(Request $request)
    {
        $flag = $this->saveform($request, '');

        return redirect('admin/transport_extend');
    }

    public function update(Request $request, $id)
    {
        $flag = $this->saveform($request, $id);

        return redirect('admin/transport_extend');
    }

    /**
     * 获取已定义验证规则的错误消息。
     *
     * @return array
     */
    public function messages()
    {
        return [
            'snum' => '首重是必填的',
            'xnum' => '续重',
            'sprice' => '首重价格是必填的',
            'province_ids' => '请选择省',
        ];
    }
}
