<?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 = "";
                if($this->course){
                    $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('before9')->display(function ($res) {
                $str = "";
                if(!empty($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('course-field.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->column('after9')->display(function ($res) {
                $str = "";
                if(!empty($res)){
                    $res = json_decode($res, true);
                    //总标杆
                    $par_total = 0;
                    foreach ($res as $key => $val) {
                        $par_total += $val['par'];
                    }
                    //后九标杆
                    $af9_par_total = 0;
                    foreach ($res as $key => $val) {
                        if ($val['sort'] <= 9) {
                            $af9_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('course-field.fields.after9') . "</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>" . $af9_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)->required();

                $form->table('before9', function (Form\NestedForm $table) {
                    $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'))->default(CourseField::$baseHoleList)->disableCreate()->disableDelete()->width(12, 0);

                $form->table('after9', function (Form\NestedForm $table) {
                    $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'))->default(CourseField::$baseHoleList)->disableCreate()->disableDelete()->width(12, 0);
            });

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

            $form->saved(function (Form $form) {
                $id = $form->getKey(); //新增数据后返回的主键 id
                //前九
                if (!empty($this->before9) && is_array($this->before9)) {
                    foreach ($this->before9 as $val) {
                        unset($val['id']);
                        unset($val['_remove_']);
                        $val['course_field_id'] = $id;
                        $val['type'] = 1;
                        $map = [
                            'type' => $val['type'],
                            'sort' => $val['sort'],
                            'course_field_id' => $id,
                        ];
                        if ($info = CourseHole::query()->where($map)->first()) {
                            CourseHole::query()->where($map)->update($val);
                        } else {
                            CourseHole::query()->create($val); //这里记得给字段在 Model中添加到 $fillable
                        }
                    }
                    $listBefore9 = CourseHole::query()
                        ->where('course_field_id', $id)
                        ->where('type',1)
                        ->select('sort', 'par', 'difficulty', 'gold_dis', 'blue_dis', 'white_dis', 'red_dis')
                        ->orderBy('sort', 'asc')
                        ->get();
                    if($listBefore9->isNotEmpty()){
                        $listBefore9 = $listBefore9->toArray();
                    }else{
                        $listBefore9 = null;
                    }
                }else{
                    $listBefore9 = [];
                }

                //后九
                if (!empty($this->after9) && is_array($this->after9)) {
                    foreach ($this->after9 as $val2) {
                        unset($val2['id']);
                        unset($val2['_remove_']);
                        $val2['course_field_id'] = $id;
                        $val2['type'] = 2;
                        $map2 = [
                            'type' => $val2['type'],
                            'course_field_id' => $id,
                            'sort' => $val2['sort'],
                        ];
                        if ($info = CourseHole::query()->where($map2)->first()) {
                            CourseHole::query()->where($map2)->update($val2);
                        } else {
                            CourseHole::query()->create($val2); //这里记得给字段在 Model中添加到 $fillable
                        }
                    }
                    $listAfter9 = CourseHole::query()
                        ->where('course_field_id', $id)
                        ->where('type',2)
                        ->select('sort', 'par', 'difficulty', 'gold_dis', 'blue_dis', 'white_dis', 'red_dis')
                        ->orderBy('sort', 'asc')
                        ->get();
                    if($listAfter9->isNotEmpty()){
                        $listAfter9 = $listAfter9->toArray();
                    }else{
                        $listAfter9 = null;
                    }
                }else{
                    $listAfter9 = [];
                }

                $courseField = CourseField::find($id);
                $courseField->before9 = $listBefore9 ? json_encode($listBefore9) : '';
                $courseField->after9 = $listAfter9 ? json_encode($listAfter9) : '';
                $courseField->course_id = Cache::get('course_id');
                $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();
            });
        });
    }
}
