<?php

namespace App\Admin\Controllers;

use App\Models\Course;
use App\Models\CourseField;
use App\Models\CourseHole;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;

class CourseFieldController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(CourseField::with('course'), function (Grid $grid) {
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append('<a class="btn btn-md btn-primary" onClick="javascript :history.back(-1);"  style="color:#586cb1;margin-left:10px">返回</a>');
            });
            $course_id = request()->input('course_id');
            Cache::put('course_id', $course_id); //设置缓存，添加场地是可用
            $grid->model()->where('course_id', '=', $course_id);
            $grid->model()->orderByDesc('id');
            $grid->column('id')->sortable();
            $grid->column('course_id')->display(function () {
                $str = "";
                $str .= "<div style='margin-right:10px;display: flex;align-items: center'>";
                $str .= '<img data-action="preview-img" src="' . $this->course->img . '" style="height:50px;width:50px;cursor:pointer;margin-right:10px;" class="img img-thumbnail">';
                $str .= '<p style="margin-bottom: 5px">' . $this->course->name . '</p>';
                $str .= "</div>";
                return $str;
            });
            $grid->column('name');
            $grid->column('hole_list')->display(function ($res) {
                $res = json_decode($res, true);
                //总标杆
                $par_total = 0;
                foreach ($res as $key => $val) {
                    $par_total += $val['par'];
                }
                //前九标杆
                $bf9_par_total = 0;
                foreach ($res as $key => $val) {
                    if ($val['sort'] <= 9) {
                        $bf9_par_total += $val['par'];
                    }
                }
                //球洞
                $hole_con = '';
                foreach ($res as $key => $val) {
                    $hole_con .= "<td>" . ($key + 1) . "</td>";
                    if ($val['sort'] == 9) {
                        $hole_con .= "<td>" . trans('game-user.fields.before9') . "</td>";
                    }
                }
                //难度
                $diff_con = '';
                foreach ($res as $key => $val) {
                    $diff_con .= "<td>" . $val['difficulty'] . "</td>";
                    if ($val['sort'] == 9) {
                        $diff_con .= "<td>" . '#' . "</td>";
                    }
                }
                //标杆
                $par_con = '';
                foreach ($res as $key => $val) {
                    $par_con .= "<td>" . $val['par'] . "</td>";
                    if ($val['sort'] == 9) {
                        $par_con .= "<td>" . $bf9_par_total . "</td>";
                    }
                }
                $str = "<style>
                        .scores_table td{
                            border: 1px solid #ccc!important;
                            width: 40px;
                        }
                    </style>
                    <table class='scores_table' style='text-align: center'>
                        <tr>
                            <td>" . trans('game-user.fields.hole') . "</td>
                            " . $hole_con . "
                        </tr>
                        <tr>
                            <td>" . trans('game-user.fields.difficulty') . "</td>
                            " . $diff_con . "
                        </tr>
                        <tr>
                            <td>" . trans('game-user.fields.par') . "</td>
                            " . $par_con . "
                        </tr>
                       
                    </table>";

                return $str;
            });

            $grid->disableViewButton();

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new CourseField(), function (Form $form) {

            $courseId = Cache::get('course_id');
            $course = Course::find($courseId);

            $form->column(9, function (Form $form)use ($course) {
                $form->html(function () use ($course) {
                    $str  = "";
                    $str .= "<div style='display: flex;align-items: center'>";
                    $str .= '<img data-action="preview-img" src="' . $course->img . '" style="height:50px;width:50px;cursor:pointer;margin-right:10px;" class="img img-thumbnail">';
                    $str .= '<div>';
                    $str .= '<p style="margin-bottom: 5px">球场名：' . $course->name . '</p>';
                    $str .= "</div>";
                    $str .= "</div>";
                    return $str;
                });

                $form->text('name')->width(4);
                $form->table('hole_list', function (Form\NestedForm $table) {
                    //$table->setOriginal(CourseField::$baseHoleList, 'sort');
                    $table->text('sort', trans('course.labels.sort'));
                    $table->text('par', trans('course.labels.par'));
                    $table->text('difficulty', trans('course.labels.difficulty'));
                    $table->text('gold_dis', trans('course.labels.gold_dis'));
                    $table->text('blue_dis', trans('course.labels.blue_dis'));
                    $table->text('white_dis', trans('course.labels.white_dis'));
                    $table->text('red_dis', trans('course.labels.red_dis'));
                })->label(trans('course.labels.hole_list'))->width(12, 0);
            });

            $form->saving(function (Form $form) {
                if (is_array($form->hole_list)) {
                    $this->hole_list = array_values($form->hole_list);
                    $form->deleteInput('hole_list');
                }
            });

            $form->saved(function (Form $form) {
                $id = $form->getKey(); //新增数据后返回的主键 id
                if (!empty($this->hole_list) && is_array($this->hole_list)) {
                    foreach ($this->hole_list as $val) {
                        unset($val['id']);
                        unset($val['_remove_']);
                        $val['course_field_id'] = $id;
                        $map = ['course_field_id' => $id, 'sort' => $val['sort']];
                        if ($info = CourseHole::query()->where($map)->first()) {
                            CourseHole::query()->where($map)->update($val);
                        } else {
                            CourseHole::query()->create($val);
                        }
                    }
                    $list = CourseHole::query()
                        ->where('course_field_id', $id)
                        ->select('sort', 'par', 'difficulty', 'gold_dis', 'blue_dis', 'white_dis', 'red_dis')
                        ->orderBy('sort', 'asc')
                        ->get();
                    if($list->isNotEmpty()){
                        $list = $list->toArray();
                    }else{
                        $list = false;
                    }
                    $courseField = CourseField::find($id);
                    $courseField->hole_list = $list ? json_encode($list) : '';;
                    $courseField->save();
                }
                return $form->response()->success('保存成功')->redirect('course_field/'.$id.'/edit');
            });

            $form->disableViewButton();
            $form->disableListButton();
            $form->tools(function (Form\Tools $tools) {
                $tools->append('<a class="btn btn-sm btn-primary" onClick="javascript :history.back(-1);"  style="color:#ffffff;margin-right:10px">返回</a>');
            });

            $form->footer(function ($footer) {
                // 去掉`查看`checkbox
                $footer->disableViewCheck();
                // 去掉`继续编辑`checkbox
                $footer->disableEditingCheck();
                // 去掉`继续创建`checkbox
                $footer->disableCreatingCheck();
            });
        });
    }
}
