<?php

namespace App\Admin\Controllers\Account;

use App\Models\AccountLog;
use App\Models\User;
use App\Models\AccountRule;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;

class LogController extends AdminController
{

    protected $title = '账户日志';

    function grid()
    {
        $grid = new Grid(new AccountLog);
        $grid->model()->with(['account'])->latest();
        $userId = request()->user_id;
        $grid->model()->when($userId, function ($query, $userId) {
            $query->where('user_id', $userId);
        });

        $grid->disableActions();
        $grid->disableCreateButton();

        $grid->filter(function ($filter) {
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('rule_id', '触发规则')->select(AccountRule::pluck('title', 'id'));
                $filter->equal('type', '账户类型')->select(config('account.account_type'));
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('account', function ($query) {
                        $query->whereHasMorph('accountable', 'App\Models\User', function ($query) {
                            $query->where('id', $this->input);
                        });
                    });
                }, '会员账号', 'id')->select(User::whereHas('identity', function ($q) {
                    $q->where('identity_id', 1);
                })->get()->pluck('info.nickname', 'id'));
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('frozen', '冻结')->select([
                    0 => '否',
                    1 => '是',
                ]);
                $filter->between('created_at', '创建时间')->datetime();
            });
        });

        $grid->column('会员账号')->display(function () {
            return $this->account->accountable->username;
        });
        $grid->column('会员昵称')->display(function () {
            return $this->account->accountable->info->nickname;
        });
        $grid->column('rule.title', '触发规则');
        $grid->column('type', '类型')
             ->using(config('account.account_type'));
        $grid->column('variable', '变量');
        $grid->column('balance', '余额');
        $grid->column('frozen', '冻结')
             ->using([0 => '否', 1 => '是'])
             ->label([
                 0 => 'success',
                 1 => 'warning',
             ]);
        $grid->column('created_at', '获取时间');

        return $grid;
    }

}
