<?php

namespace Modules\Cms\Http\Controllers\Admin;

use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Routing\Controller;
use Overtrue\LaravelVersionable\Version;

class VersionController extends Controller
{

    public function index(Content $content, $model, $key): Content
    {
        return $content
            ->header($model . ' => ' . $key)
            ->description('数据操作日志')
            ->body($this->grid($model, $key));
    }

    public function grid($model, $key): Grid
    {
        $grid = new Grid(new Version());

        $grid->disableCreateButton();
        $grid->disableActions();
        $grid->disableTools();

        $grid->model()->whereHasMorph(
            'versionable',
            $model,
            function (Builder $query) use ($key) {
                $query->where('id', $key);
            }
        )->orderByDesc('id');

        $grid->column('操作用户')->display(function () {
            if ($this->user_id < config('mall.administrator_max_id')) {
                config(['versionable.user_model' => Administrator::class]);

                return '[Admin] ' . ($this->user->name ?? '--SYSTEM--');
            } else {
                return '[USER] ' . ($this->user->username ?? '--USER--');
            }
        });
        $grid->column('versionable_type', '数据变动')->expand(function () {
            $data = [];
            foreach ($this->contents as $key => $item) {
                $data[] = [
                    $key,
                    is_array($item) ? json_encode($item, JSON_UNESCAPED_UNICODE) : $item,
                ];
            }

            return new Table(['字段名称', '变更值'], $data);
        });

        $grid->column('操作时间')->display(function () {
            return $this->created_at->toDateTimeString();
        });

        return $grid;
    }

}