<?php

namespace App\Admin\Extensions\Form;

use Dcat\Admin\Form\Field;

class JsonEditor extends Field
{
    protected $view = 'admin.json-editor';

    protected static $css = [
        'vendor/jsoneditor-6.2.1/dist/jsoneditor.min.css',
    ];

    protected static $js = [
        'vendor/jsoneditor-6.2.1/dist/jsoneditor.min.js',
    ];

    public function render()
    {
        $json = old($this->column, $this->value());

        if (empty($json)) {
            $json = '{}';
        }

        if (! is_string($json)) {
            $json = json_encode($json);
        } else {
            $json = json_encode(json_decode($json));   //兼容json里有类似</p>格式，首次初始化显示会丢失的问题
        }
        $this->value = $json;

        $options = json_encode(config('admin.extension.json-editor.config'));

        if (empty($options)) {
            $options = '{}';
        }

        $this->script = <<<EOT
// 生成editor
var container = document.getElementById('jsonEditor');
const options = {
    mode: 'tree',
    modes: ["code", "form", "text", "tree"],
    onChangeJSON(json) {
        $('input[id=json_input]').val(JSON.stringify(json))
    },
    onChangeText(text) {
        $('input[id=json_input]').val(text)
    },
    history: false
}
window['editor_json'] = new JSONEditor(container, options);

// 赋值json
var json = {$json};
window['editor_json'].set(json);
EOT;

        return parent::render();
    }
}
