<?php

namespace App\Admin\Forms;

use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Arr;

class AdminSetting extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 主题颜色.
     *
     * @var array
     */
    protected $colors;

    public function __construct($data = [], $key = null)
    {
        parent::__construct($data, $key);
        $this->colors = [
            'default'    => trans('site-setting.Dark_blue'),
            'blue'       => trans('site-setting.blue'),
//        'blue-light' => '浅蓝',
//        'blue-dark'  => '深蓝',
            'green'      => trans('site-setting.green'),
        ];
    }

    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $input['layout']['horizontal_menu'] = in_array('horizontal_menu', $input['layout']['body_class'], true);

        foreach (Arr::dot($input) as $k => $v) {
            $this->update($k, $v);
        }

        return $this->response()->success(trans('site-setting.Set_successfully'));
    }

    /**
     * 构建表单.
     */
    public function form()
    {
//        $this->text('name')->required()->help(trans('site-setting.Website_name'));
//        $this->text('logo')->required()->help(trans('site-setting.logo'));
//        $this->text('logo-mini', 'Logo mini')->required();
        $this->radio('lang', trans('site-setting.language'))->required()->options(['en' => 'English', 'zh' => '简体中文']);
//        $this->radio('layout.color', trans('site-setting.theme'))
//            ->required()
//            ->help(trans('site-setting.theme_color'))
//            ->options($this->colors);

//        $this->radio('layout.sidebar_style', trans('site-setting.menu_style'))
//            ->options(['light' => 'Light', 'primary' => 'Primary'])
//            ->help(trans('site-setting.t_menu_style'));

        $this->checkbox('layout.body_class', trans('site-setting.Menu_layout'))
            ->options([
                'horizontal_menu' => 'Horizontal',
                'sidebar-separate' => 'sidebar-separate',
            ])
            ->help(trans('site-setting.Switch_menu_layout'));
//        $this->switch('https', '启用HTTPS');
        $this->switch('helpers.enable', trans('site-setting.development_tool'));
    }

    /**
     * 设置接口保存成功后的回调JS代码.
     *
     * 1.2秒后刷新整个页面.
     *
     * @return string|void
     */
    public function savedScript()
    {
        return <<<'JS'
    if (data.status) {
        setTimeout(function () {
          location.reload()
        }, 1200);
    }
JS;
    }

    /**
     * 返回表单数据.
     *
     * @return array
     */
    public function default()
    {
        return user_admin_config();
    }

    /**
     * 更新配置.
     *
     * @param string $key
     * @param string $value
     */
    protected function update($key, $value)
    {
        user_admin_config([$key => $value]);
    }
}
