<?php

namespace App\Admin\Controllers;

use App\Admin\Renderable\DistDistributorTable;
use App\Admin\Repositories\DistAppearance;
use App\Admin\Repositories\DistAppearanceVariable;
use App\Libraries\CommonHelper;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Dropdown;


class DistAppearanceVariableController extends AdminController
{

    public function index(Content $content)
    {
        return $content->full()->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $templateCode = isset($_GET['templateCode']) ? $_GET['templateCode'] : 0;
        $appearanceId = isset($_GET['appearanceId']) ? intval($_GET['appearanceId']) : 0;
        $distId = isset($_GET['distId']) ? intval($_GET['distId']) : 0;
        if (empty($appearanceId)) {
            die(' <h3>Please select the theme.<h3>');
        }
        return Grid::make(DistAppearanceVariable::with(['distributor','appearance']), function (Grid $grid) use ($templateCode, $appearanceId, $distId) {
            $grid->column('id')->sortable();
            $grid->column('distributor.company_name','Distributor Name')->display(function ($company_name) {
                if (empty($company_name)) {
                    return '-';
                }
                return $company_name;
            });
            $grid->column('appearance.title','Appearance');
            //变量名
            $grid->column('variable_name');
            //变量类型
            $grid->column('variable_type')->using(['1' => 'text', '2' => 'textarea', '3' => 'json']);
            //是否是站点变量
            $grid->column('templateCode','site variable')->display(function ($templateIds) {
                if ($templateIds == 0) {
                    return 'Yes';
                } else {
                    return 'No';
                }
            })->label([
                '0' => 'success',
                '1' => 'default',
            ]);;
            //搜索
            $grid->quickSearch(['variable_name']);
            //工具栏
            $grid->disableViewButton();
            $grid->showQuickEditButton();
            $grid->enableDialogCreate();
            $grid->disableEditButton();
            $addUrl = 'templateCode='. $templateCode . '&appearanceId='. $appearanceId . '&distId='. $distId;
            //排序
            $grid->model()->where('appearance_id', $appearanceId)->where('dist_id', $distId)->whereIn('template_code', [0, $templateCode])->orderBy("id",'asc');
            //增加js 向新增按钮添加参数还有编辑按钮添加参数


            CommonHelper::replaceAddEditerUrl('.dialog-create', '.quick-edit', $addUrl);

            /*
            Admin::script(
<<<JS
var button = $('.dialog-create');
var currentUrl = button.attr('data-url');
if (currentUrl.indexOf('?') === -1) {
    button.attr('data-url', currentUrl + '{$addUrl}');
} else {
    button.attr('data-url', currentUrl + '{$addUrl}');
}

$('.quick-edit').each(function() {
    var currentUrl = $(this).attr('data-url');
    if (currentUrl.indexOf('?') === -1) {
        $(this).attr('data-url', currentUrl + '{$addUrl}');
    } else {
        // 如果已经有查询参数，添加 &id=123
        $(this).attr('data-url', currentUrl + '{$addUrl}');
    }
});
JS
            );
            */
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
//    protected function detail($id)
//    {
//        return Show::make($id, DistAppearanceVariable::with(['distributor','appearance']), function (Show $show) {
//            $show->field('id');
//            $show->field('distributor.company_name','Distributor Name')->as(function ($company_name) {
//                if (empty($company_name)) {
//                    return 'Site Variable';
//                }
//                return $company_name;
//            });
//            $show->field('appearance.title','Appearance Title');
//            $show->field('variable_type')->using(['1' => 'text', '2' => 'textarea', '3' => 'json']);
//            $show->field('variable_name');
//            $show->field('variable_value');
//
//            $show->field('created_at');
//            $show->field('updated_at');
//        });
//    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $templateCode = isset($_GET['templateCode']) ? $_GET['templateCode'] : 0;
        $appearanceId = isset($_GET['appearanceId']) ? intval($_GET['appearanceId']) : 0;
        $distId = isset($_GET['distId']) ? intval($_GET['distId']) : 0;
        return Form::make(new DistAppearanceVariable(), function (Form $form) use ($templateCode, $appearanceId, $distId) {
            $form->hidden('appearance_id')->value($appearanceId);
            $form->hidden('dist_id')->value($distId);
            $form->hidden('template_code')->value($templateCode);
            $form->hidden('variable_code');
            //编辑时当template_id为0时，site_variable为默认值1，否则为0
            $variableDefaul = 0;
            if (!$form->isCreating()) {
                if ($form->model()->template_id == 0) {
                    $variableDefaul = 1;
                }
            }
            $form->switch('site_variable')->value($variableDefaul)->width(9,3);
            $form->radio('variable_type')->options([
                '1'=>'text',
                '2'=>'textarea',
                '3'=>'json'
            ])->width(9,3)->default(1);
            $form->text('variable_name')->width(9,3);
            $form->textarea('variable_value')->rows(12)->width(9,3);
            $form->ignore(['site_variable']);

            $form->submitted(function (Form $form) {
                if ($form->input('site_variable') == 1) {
                    $form->template_code = 0;
                }
                if ($form->isCreating()) {
                    $form->variable_code = uniqueCode();
                }
                //检查json格式是否正确
                if ($form->input('variable_type') == 3) {
                    if (!isValidJson($form->input('variable_value'))) {
                        return $form->response()->error('The JSON format is incorrect');
                    }
                }
            });

        });
    }
}
