<?php

namespace Modules\User\Http\Controllers\Admin;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Modules\User\Http\Controllers\Admin\Actions\Certification\ConfigPublish;
use Modules\User\Http\Controllers\Admin\Actions\Certification\Replicate;
use Modules\User\Models\UserCertificationConfig;

class CertificationConfigController extends AdminController
{
    protected $title = '认证配置';

    protected function grid(): Grid
    {
        $grid = new Grid(new UserCertificationConfig());

        $grid->disableFilter();
        $grid->model()->orderBy('id', 'desc');
        $grid->actions(function ($action) {
            $action->disableView();
            $action->add(new Replicate);

            if ($this->row->status == 0) {
                $action->add(new ConfigPublish);
            } else {
                $action->disableEdit();
                $action->disableDelete();
            }
        });
        $grid->column('id', 'ID');
        $grid->column('配置HASH')->display(function () {
            return md5($this->created_at);
        });
        $grid->column('is_open', '开通网络认证')->bool();
        $grid->column('is_ocr_open', '开通OCR认证')->bool();
        $grid->column('type', '认证类型')
            ->using(UserCertificationConfig::TYPE)
            ->label();
        $grid->column('status', '状态')->bool();
        $grid->column('created_at', '创建时间');

        return $grid;
    }

    protected function form(): Form
    {
        $form = new Form(new UserCertificationConfig());

        $states = [
            'on'  => ['value' => 1, 'text' => '开启', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
        ];
        $form->switch('is_open', '开通网络认证')->states($states);
        $form->switch('is_ocr_open', '开通OCR认证')->states($states);
        $form->radioButton('type', '认证类型')
            ->options(UserCertificationConfig::TYPE)
            ->required();
        $form->password('code', '阿里云code')->help('开启认证时必填');
        $form->url('url', '阿里云接口地址')->help('开启OCR认证时必填');
        $form->text('ocr_appid', 'OCRAPPID')->help('开启OCR认证时必填');
        $form->password('ocr_secretkey', 'OCRSecret')->help('开启OCR认证时必填');

        return $form;
    }
}