<?php

namespace Modules\User\Http\Controllers\Admin;

use App\Admin\Traits\WithUploads;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Grid;
use Modules\User\Models\Identity;

class IdentitiesController extends AdminController
{

    use WithUploads;

    protected $title = '用户身份';

    public function grid(): Grid
    {

        $grid = new Grid(new Identity());
        $grid->model()->oldest('id')->oldest('order');
        $grid->filter(function (Grid\Filter $filter) {
            $filter->scope('trashed', '回收站')->onlyTrashed();

            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->like('name', '身份名称');
            });
            $filter->column(1 / 3, function (Grid\Filter $filter) {
                $filter->equal('status', '状态')->select([
                    0 => '禁用',
                    1 => '正常',
                ]);
            });
        });

        $grid->model()->oldest()->withCount('users');

        $grid->column('id', '#ID#');
        $grid->column('cover', '展示图片')->image('', 40);
        $grid->column('name', '身份名称');
        $grid->column('order', '排序')->editable();
        $grid->column('status', '状态')->bool();
        $grid->column('serial_open', '是否开启编号')->bool();
        $grid->column('serial_places', '编号长度');
        $grid->column('serial_prefix', '编号前缀');
        $grid->column('years', '有效期（月）')
            ->display(function () {
                return $this->years > 0 ? $this->years : '永久';
            });
        $grid->column('stock', '送水（箱）');
        $grid->column('users_count', '组内用户');
        $grid->column('job', '身份')->using(Identity::JOBS)->label();
        $grid->column('total', '可开通总数');
        $grid->column('channel', '缴费渠道')
            ->using(Identity::CHANNELS)
            ->label([
                Identity::CHANNEL_ONLINE  => 'primary',
                Identity::CHANNEL_OFFLINE => 'success',
            ]);
        foreach (config('identity.conditions') as $key => $title) {
            $grid->column($title)->display(function () use ($key) {
                return $this->getCondition($key, '无');
            });
        }
        foreach (config('identity.rules') as $key => $title) {
            $grid->column($title)->display(function () use ($key) {
                return $this->getRule($key, '无');
            });
        }

        $states = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'primary'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'default'],
        ];
        $grid->column('default', '默认身份')->switch($states);
        $grid->column('can_buy', '前台开通')->switch($states);

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

        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new Identity());
        $form->text('name', '身份名称')
            ->required()
            ->rules([
                'unique:Modules\User\Models\Identity,name,{{id}}',
            ], [
                'unique' => '身份名称已经存在',
            ]);
        $this->cover($form, 'cover', '展示图片');
        $form->number('order', '排序')
            ->required()
            ->default(0);
        $form->textarea('description', '身份简介')
            ->rules(['max:255'], [
                'max' => '简介内容最大不能超过:max个字符',
            ]);
        $form->switch('default', '默认身份')
            ->default(0);
        $form->switch('can_buy', '前台开通')
            ->help('是否可以在前台开通身份')
            ->default(0);
        $form->number('stock', '库存')
            ->help('开通身份送多少水')
            ->default(0);

        $form->number('years', '有效期(月)')
            ->help('0未长期有效')
            ->default(0);

        $form->switch('status', '状态')
            ->required()
            ->default(1);
        $form->select('serial_open', '是否开启编号')
            ->options([
                false => '关闭',
                true  => '开启',
            ])
            ->required();
        $form->number('serial_places', '编号长度')
            ->rules([
                'exclude_if:serial_open,true',
                'required',
            ], [
                'required' => '编号开启必填',
            ]);
        $form->text('serial_prefix', '编号前缀');
        $form->text('protocol_url', '协议地址')->help('显示开通身份签署的协议');
        $form->radioButton('channel', '缴费渠道')
            ->options(Identity::CHANNELS)
            ->default(1);
        $form->radioButton('job', '身份')
            ->options(Identity::JOBS)
            ->default(0);
        $form->divider();

        $form->table('conditions', '升级条件', function (NestedForm $form) {
            $form->select('name', '条件')
                ->required()
                ->options(config('identity.conditions'))
                ->rules('required');
            $form->select('compare', '规则')
                ->options([
                    '>'  => '大于',
                    '>=' => '大于等于',
                    '='  => '等于',
                    '<'  => '小于',
                    '<=' => '小于等于',
                ])
                ->required()
                ->rules('required');
            $form->text('value', '值')
                ->required()
                ->rules('required');
        });
//
        $form->table('rules', '身份权益', function (NestedForm $form) {
            $form->select('name', '权益')
                ->required()
                ->options(config('identity.rules'))
                ->rules('required');
            $form->select('compare', '规则')
                ->options([
                    '>'  => '大于',
                    '>=' => '大于等于',
                    '='  => '等于',
                    '<'  => '小于',
                    '<=' => '小于等于',
                ])
                ->required()
                ->rules('required');
            $form->text('value', '值')
                ->required()
                ->rules('required');
        });
        $form->table('ruleshows', '身份权益(前台展示)', function (NestedForm $form) {
            $form->image('icon', '权益图片');
            $form->select('name', '权益')
                ->options(config('identity.show_rules'))
                ->required()
                ->rules('required');
            $form->text('value', '值')
                ->required()
                ->rules('required');
        });
//
        $form->table('rights', '可享受权益', function (NestedForm $form) {
            $form->text('name', '名称')
                ->required()
                ->rules('required');
            $form->image('cover', '权益图片');
            $form->text('remark', '备注')
                ->required()
                ->rules('required');
            $form->number('order', '排序');
        });

//        $form->saving(function ($form) {
////            dd(request()->all());
//        });


        $form->saved(function ($form) {
            $model = $form->model();
            if ($model->default == 1) {
                Identity::where('id', '!=', $model->id)
                    ->where('default', 1)
                    ->update([
                        'default' => 0,
                    ]);
            }
        });

        return $form;
    }

}