<?php

namespace Modules\User\Http\Controllers\Admin;

use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as AdminController;
use Illuminate\Support\MessageBag;
use Modules\User\Models\User;

class JoinCsVIpController extends AdminController
{

    use HasResourceActions;

    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '开通初始会员';

    /**
     * Get content title.
     *
     * @return string
     */
    protected function title(): string
    {
        return $this->title;
    }

    /**
     * Create interface.
     *
     * @param  Content  $content
     * @return Content
     */
    public function create(Content $content, User $user): Content
    {
        return $content
            ->title($this->title())
            ->description($this->description['create'] ?? trans('admin.create'))
            ->body($this->form($user));
    }

    public function form($user): Form
    {
        $channel = config('account.sms.template.balance');
        $form    = new Form(new User);

        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();
        });

        $form->display('联名卡会员账户')->default($user->account->drill);
        $form->display('用户昵称')->default($user->info->nickname)->readonly();
        $form->display('手机号')->default($user->username)->readonly();
        $form->select('rule_id', '规则')
            ->options(function () {
                return AccountRule::query()
                    ->whereIn('name', [
                        'system_drill_in',
                    ])
                    ->get()
                    ->pluck('longname', 'id');
            })
            ->required();

        $form->text('mobile', '手机号')
            ->value(config('account.sms.mobile'))
            ->disable()
            ->required();

        $form->text('amount', '数值')->required();
        $form->hidden('user_id', '用户id')->value($user->id);
        $form->text('remark', '备注')->help('告知用户调整原因')->required();

        $form->html(view('admin.tools.sms', compact('channel')), '验证码');
        $form->setAction('/admin/user/csvip');

        return $form;
    }

    /**
     * Notes: 设置积分
     *
     * @Author: 玄尘
     * @Date  : 2021/4/26 13:52
     * @param  \Illuminate\Http\Request  $request
     */
    public function setIdentity(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'user_id' => 'required',
            'rule_id' => 'required',
            'amount'  => 'required|integer',
            'code'    => 'required',
        ], [
            'user_id.required' => '缺少操作的用户',
            'rule_id.required' => '缺少规则id',
            'amount.required'  => '缺少增加/减少的数值',
            'amount.integer'   => '数值必须是整数',
            'code.required'    => '缺少短信验证码',
        ]);

        if ($validator->fails()) {
            return $this->backErrorMessage($validator->errors()->first());
        }

        $amount  = $request->amount;
        $channel = $request->channel ?? config('account.sms.template.default');

        $user = User::find($request->user_id);

        $res = \Sms::check(config('account.sms.mobile'), $request->code, $channel);

        if ($res != true) {
            return $this->backErrorMessage('验证码校验失败');
        }

        $rule = AccountRule::find($request->rule_id);
        if (! $rule) {
            return $this->backErrorMessage('规则未找到');
        }

        if (in_array($rule->name, config('account.system_set_score.in'))) {
            $res = $user->account->rule($rule->id, $amount, false, [
                'expired_at' => now()->addYear(),
                'remark'     => '后台操作增加余额',
            ]);
        } elseif (in_array($rule->name, config('account.system_set_score.out'))) {
            if ($user->account->{$rule->type} < $amount) {
                return $this->backErrorMessage('账户余额不足。扣除失败');
            }

            $res = $user->account->rule($rule->id, -$amount, false, [
                'remark' => '后台操作扣除余额',
            ]);
        } else {
            return $this->backErrorMessage('规则出错');
        }

        if ($res === true) {
            admin_toastr('操作完成');

            return redirect()->to('/admin/users?username='.$user->username);
        }

        return $this->backErrorMessage('操作失败'.$res);
    }

    public function backErrorMessage($message)
    {
        $error = new MessageBag([
            'title'   => '错误',
            'message' => $message,
        ]);

        return back()->withInput()->with(compact('error'));
    }

}
