<?php

namespace Modules\Payment\Http\Controllers\Admin;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Modules\Payment\Models\Wechat;

class WechatController extends AdminController
{

    protected $title = '微信支付';

    public function grid(): Grid
    {
        $grid = new Grid(new Wechat());

        $grid->disableFilter();
        $grid->column('id', '#ID#');
        $grid->column('name', '支付名称');
        $grid->column('appid', 'APP APPID');
        $grid->column('app_id', '公众号 APPID');
        $grid->column('miniapp_id', '小程序 APPID');
        $grid->column('mch_id', '商户号');

        $grid->column('created_at', '创建时间');

        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new Wechat());

        $form->text('name', '支付名称')
             ->required();

        $form->text('appid', 'APP APPID');
        $form->text('app_id', '公众号 APPID');
        $form->text('miniapp_id', '小程序 APPID');
        $form->text('mch_id', '商户号')
             ->required()
             ->rules('required|size:10', [
                 'required' => '商户号必须填写',
                 'size'     => '商户号长度应为:size位',
             ]);
        $form->text('key', '支付密钥')
             ->required()->rules('required|size:32', [
                'required' => '支付密钥必须填写',
                'size'     => '支付密钥长度应为:size位',
            ]);
        $form->url('notify_url', '通知地址');

        //        $form->file('cert_client', '公钥证书')
        //             ->disk('local')
        //             ->move('certs')
        //             ->removable();
        //
        //        $form->file('cert_key', '私钥证书')
        //             ->disk('local')
        //             ->move('certs')
        //             ->removable();

        $form->text('cert_client', '公钥证书')->help('相对/storage/app下的路径如：certs/apiclient_key.pem');
        $form->text('cert_key', '私钥证书')->help('相对/storage/app下的路径如：certs/apiclient_cert.pem');

        $form->embeds('log', '日志配置', function (Form\EmbeddedForm $form) {
            $form->text('file', '日志文件名')->default('wechat');
            $form->select('level')->options([
                'info'  => 'info',
                'debug' => 'debug',
            ])->default('info');
            $form->select('type', '记录方式')->options([
                'daily'  => '按日期',
                'single' => '单文件',
            ])->default('daily');
            $form->number('max_file')
                 ->default(30)
                 ->help('当 【记录方式】 为 【按日期】 时有效');
        });

        return $form;
    }

    public function ajax(Request $request)
    {
        $q = $request->q;

        return Wechat::where('name', 'like', "%$q%")
                     ->orWhere('mch_id', 'like', "%$q%")
                     ->paginate(null, ['id', 'name as text']);
    }

}