<?php

namespace Modules\User\Http\Controllers\Admin;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Exception;
use Modules\User\Http\Controllers\Admin\Actions\Pay;
use Modules\User\Http\Controllers\Admin\Actions\Refund;
use Modules\User\Models\Identity;
use Modules\User\Models\Order;

class OrderController extends AdminController
{

    protected $title = '升级订单';

    /**
     * Notes: 升级订单
     *
     * @Author: 玄尘
     * @Date  : 2021/6/7 15:19
     * @return Grid
     */
    public function grid(): Grid
    {
        try {
            trait_exists('Modules\Payment\Traits\WithPayments');
            $grid = new Grid(new Order());
            $grid->model()->latest()->where('identity_id', '>', 2);
            $grid->disableCreateButton();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->disableView();
                if ($actions->row->canPay()) {
                    $actions->add(new Pay());
                }

                if ($actions->row->canRefund()) {
                    $actions->add(new Refund());
                }

            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->like('user.username', '用户名');
                    $filter->like('user.info.nickname', '用户昵称');
                });

                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('identity.id', '身份')->select(function () {
                        return Identity::query()->where('order', '>', 1)->pluck('name', 'id');
                    });
                    $filter->equal('state', '状态')->select(Order::STATES);
                });

            });

            $grid->column('id', '用户ID');
            $grid->column('升级用户')->display(function () {
                return $this->user->username."({$this->user->info->nickname})";
            });
            $grid->column('name', '打款人姓名');
            $grid->column('cover', '打款凭证')->gallery(['width' => 60, 'height' => 60]);
            $grid->column('identity.name', '开通身份');
            $grid->column('price', '应打款额')->editable();
            $grid->column('state', '状态')->using(Order::STATES)->label();
            $grid->column('type', '类型')->using(Order::TYPES)->label();

            $grid->column('created_at', '升级时间');

            return $grid;
        } catch (Exception $exception) {
            dd('Payment 模块不存在，无法加载订单数据');
        }
    }

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

        $form->decimal('price', '金额')->required();

        return $form;
    }

}
