<?php

namespace Modules\Project\Http\Controllers\Admin;

use App\Admin\Extensions\WithdrawExcelExpoter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Modules\Project\Entities\UserWallet;
use Modules\Project\Entities\UserWithdraw;
use Modules\Project\Services\UserWithdrawService;
use SMG\Admin\Controllers\ModelForm;
use SMG\Admin\Facades\Admin;
use SMG\Admin\Form;
use SMG\Admin\Grid;
use SMG\Admin\Layout\Content;

class UserWithdrawController
{
    use ModelForm;
    private $msg = '提交成功';
    private $code = 1;
    private $data = [];

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('提现');
            $content->description(' 说明..');
            $content->breadcrumb(
                ['text' => '首页', 'url' => '/'],
                ['text' => '管理', 'url' => '/user/withdraw'],
                ['text' => '列表']
            );

            $content->body($this->grid('')->render());
        });
    }

    public function grid($action)
    {
        $grid = Admin::grid(UserWithdraw::class, function (Grid $grid) use ($action) {
            $grid->exporter(new WithdrawExcelExpoter());

            $UserWithdrawService = resolve(UserWithdrawService::class);
            if ($action == 'trash') {
                $grid->model()->onlyTrashed()->where('id', '>', 0);
            }

            $grid->column('id', 'ID')->sortable();
            $grid->column('user.name');
            $grid->name('姓名');
            $grid->money('申请金额（元）');
            $grid->type('申请者类型')->display(function ($type) {
                return array_get(UserWithdraw::$arrType, $type);
            });
            $grid->column('code','归属行')->display(function ($code) {

                return $code ? $this->bank->org : '';
            });
            $grid->branch('支行信息');
            $grid->number('银行卡号');
            $grid->phone('手机号');
            $grid->status('申请状态')->display(function ($status) use ($UserWithdrawService) {
                return $UserWithdrawService->htmlstatus($status);
            });
            if ($action == 'trash') {
                $grid->deleted_at(trans('deleted_at'));
            } else {
                $grid->created_at(trans('admin.created_at'));
                $grid->updated_at(trans('admin.updated_at'));
            }

            $grid->tools(function ($tools) {
                $tools->batch(function ($actions) {
                    $actions->disableDelete();
                });
            });

            $grid->actions(function ($actions) {
                $actions->disableView();
            });
            $grid->disableCreateButton();
            $grid->enableFilter();
            $grid->option('useExporter', true);
            $grid->filter(function ($filter) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                // 在这里添加字段过滤器
                $filter->like('name', '姓名');
                $filter->equal('status', '申请状态')->select(UserWithdraw::$arrStatus);
            });

            if ($action == 'trash') {
                $grid->disableActions();
            }
        });

        return $grid;
    }

    protected function tabform($id)
    {
        $card_info = UserWithdraw::findorfail($id);
        $grid = Admin::form(UserWithdraw::class, function (Form $form) use ($id,$card_info) {
            $UserWithdrawService = resolve(UserWithdrawService::class);
            $htmlstatus = $UserWithdrawService->htmlstatus($card_info->status);

            $form->tab('提现详情', function ($form) use ($id,$card_info,$htmlstatus) {
                $tpl = '<p class="form-control-static">{A}</p>';
                $name = str_replace('{A}', $card_info->name, $tpl);
                $org = str_replace('{A}', $card_info->org, $tpl);
                $branch = str_replace('{A}', $card_info->branch, $tpl);
                $phone = str_replace('{A}', $card_info->phone, $tpl);
                $money = str_replace('{A}', $card_info->money, $tpl);
                $created_at = str_replace('{A}', $card_info->created_at, $tpl);
                $form->html($name, '提现申请名');
                $form->html($org, '归属行');
                $form->html($branch, '支行信息');
                $form->html($phone, '电话');
                $form->html($money, '提现金额');
                $form->html($created_at, '申请时间');
                $form->html($htmlstatus, '申请状态');
            });
            if ($card_info->status == 0) {
                $form->tab('提现处理', function ($form) use ($id, $card_info, $htmlstatus) {
                    $tpl = '<p class="form-control-static">{A}</p>';
                    $name = str_replace('{A}', $card_info->name, $tpl);
                    $type = str_replace('{A}', $card_info->type, $tpl);
                    $created_at = str_replace('{A}', $card_info->created_at, $tpl);
                    $bank_msg = str_replace('{A}', $card_info->number.'&nbsp;'.$card_info->org.'&nbsp;'.$card_info->branch, $tpl);
                    $form->html($name, '收款人');
                    $form->html($type, '申请类型');
                    $form->html($created_at, '申请时间');
                    $form->html($bank_msg, '收款账号');
                    $form->html($htmlstatus, '当前状态');
                    $form->select('status', '状态选择')->options(UserWithdraw::$arrStatus)->default($card_info->status)->help('失败处理会返回金额到用户钱包');
                    $form->textarea('remark', '操作人admin备注(不能为空)')->rows(10)->placeholder('请填写，不能为空');
                    $form->html('<button type="button" class="btn btn-primary btn-flat " onclick="edit_withdraw(this)" en_id="'.$id.'">提交</button>', '');
                });
            }
            $form->tab('操作记录', function ($form) use ($id) {
                $form->html($this->withdrawloggrid($id)->render())->setWidth(12, 0);
            });

            $form->setAction('#');
            $form->tools(function ($tools) {
            });
            $form->disableSubmit();
            $form->disableReset();
        });

        return $grid;
    }

    public function withdrawloggrid($id)
    {
        $grid = Admin::grid(UserWithdraw::class, function (Grid $grid) use ($id) {
            $grid->model()->find($id)->logs();
            $grid->id('ID')->sortable();
            $grid->status_desc('提现处理状态');
            $grid->admin_user('操作人名字');
            $grid->remark('操作人备注');
            $grid->created_at(trans('admin.created_at'));
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableActions();
        });

        return $grid;
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content
     */
    public function edit($id)
    {
        $app_js = '/js/admin/user_withdraws.js';
        Admin::addJs($app_js);

        return Admin::content(function (Content $content) use ($id) {
            $content->header('提现列表');
            $content->description('提现详情');

            $content->body($this->tabform($id)->edit($id));
        });
    }

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'status' => 'required',
            'remark' => 'required',
        ], [], $this->messages());

        if ($validator->fails()) {
            $errors = $validator->errors();
            foreach ($errors->all() as $message) {
                admin_toastr($message, 'error');
            }

            return;
        }

        DB::beginTransaction();
        $UserWithdraws = new UserWithdraw();
        $info = $UserWithdraws->findorFail($id);
        if (in_array($info->status, UserWithdraw::$lockStatus)) {
            admin_toastr('已提交处理', 'error');

            return;
        }
        $info->status = $request->status;
        $info->save();
        $info = $info->find($id);
        if ($info->status == UserWithdraw::SUCCESS) {
            try {
                UserWallet::get($info->user_id)->addWallet($info->money, UserWallet::WITHDRAWAL_FAIL_BACK, $info->id);
            } catch (\Exception $e) {
                DB::rollback();
                $message = $e->getMessage();
                admin_toastr($message, 'error');

                return;
            }
        }

        $log = [
            'status_desc' => UserWithdraw::$arrStatus[$request->status],
            'admin_user' => Admin::user()->username,
            'remark' => $request->remark,
        ];

        $info->logs()->create($log);

        admin_toastr($this->msg);

        DB::commit();

        return ;
    }

    /**
     * 获取已定义验证规则的错误消息。
     *
     * @return array
     */
    public function messages()
    {
        return [
            'status' => '状态选择是必填的',
            'remark' => '备注是必填的',
        ];
    }

    public function destroy($id)
    {
        $ids = explode(',', $id);
        if (UserWithdraw::whereIn('id', array_filter($ids))->delete()) {
            return response()->json([
                'status' => true,
                'message' => trans('admin.delete_succeeded'),
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => trans('admin.delete_failed'),
            ]);
        }
    }

    public function trash()
    {
        return Admin::content(function (Content $content) {
            $content->header('回收站');
            $content->description('详情');

            $content->body($this->grid('trash'));
        });
    }
}
