<?php

namespace Modules\Payment\Http\Controllers\Admin;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Modules\Payment\Models\Alipay;
use Modules\Payment\Models\Setting;
use Modules\Payment\Models\Wechat;

class SettingController extends AdminController
{

    protected $title = '支付配置';

    public function grid(): Grid
    {
        $grid = new Grid(new Setting());
        $grid->disableFilter();

        $grid->model()->orderByDesc('in_use');

        $grid->column('name', '配置名称');
        $grid->column('trade_id_counter_length', '计数器位数');
        $grid->column('in_use', '使用中')->bool();
        $grid->column('wechat.name', '微信支付');
        $grid->column('alipay.name', '支付宝');
        $grid->column('created_at', '创建时间');

        return $grid;
    }

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

        $form->text('name', '配置名称')
            ->required();
        $form->number('trade_id_counter_length', '计数器位数')
            ->required()
            ->default(4)
            ->rules('integer|max:16', [
                'max' => '计数器最大不能超过16',
            ]);
        $form->switch('in_use', '当前配置');

        $form->select('wechat_id', '微信支付')
            ->options(function ($wechatId) {
                if ($wechatId) {
                    $wechat = Wechat::find($wechatId);
                    if ($wechat) {
                        return [$wechat->id => $wechat->name];
                    }
                }
            })
            ->ajax(route('admin.payment.wechats.ajax'));
        $form->select('alipay_id', '支付宝')
            ->options(function ($alipayId) {
                if ($alipayId) {
                    $alipay = Alipay::find($alipayId);
                    if ($alipay) {
                        return [$alipay->id => $alipay->name];
                    }
                }
            })
            ->ajax(route('admin.payment.alipays.ajax'));

        return $form;
    }

}

