<?php

namespace Modules\Base\Providers;

use Illuminate\Database\Eloquent\Factory;
use Illuminate\Support\ServiceProvider;
use Modules\Base\Events\FileUploaded;
use Modules\Base\Listeners\ProcessUploadImage;
use Modules\Base\Services\SmsService;

class BaseServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Boot the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->registerFactories();
        $this->loadMigrationsFrom(__DIR__.'/../Database/Migrations');

        //密码验证
        \Validator::extend('check_password', function ($attribute, $value, $parameters, $validator) {
            $hashed_password = blank($parameters) ? \Auth::user()->getAuthPassword() : $parameters[0];

            return \Hash::check($value, $hashed_password);
        });
        \Validator::replacer('check_password', function ($message, $attribute, $rule, $parameters) {
            return '密码验证失败';
        });

        //密码验证
        \Validator::extend('check_sms', function ($attribute, $value, $parameters, $validator) {
            $data = $validator->getData();
            $phone = $parameters[0] ?? array_get($data, 'phone');
            $type = $parameters[1] ?? array_get($data, 'type');

            if (!$type || !$phone) {
                return false;
            }

            return app(SmsService::class)->verifyCode($value, $type, $phone, true);
        });

        \Validator::replacer('check_sms', function ($message, $attribute, $rule, $parameters) {
            return '手机验证码错误或已过期，请重试';
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // API 模型找不到时返回404
        \API::error(static function (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
            abort(404);
        });

        //API没有权限返回403
        \API::error(static function (\Illuminate\Auth\Access\AuthorizationException $exception) {
            abort(403, $exception->getMessage());
        });

        //API请求验证错误
        \API::error(static function (\Illuminate\Validation\ValidationException $exception) {
            throw new \Dingo\Api\Exception\ValidationHttpException($exception->errors());
        });

        //图片上传事件
        $this->app['events']->listen(FileUploaded::class, ProcessUploadImage::class);
        $this->app['events']->listen("Illuminate\Auth\Events\Authenticated", "Modules\Base\Listeners\AuthenticatedListener");
    }

    /**
     * Register config.
     *
     * @return void
     */
    protected function registerConfig()
    {
        $this->publishes([
            __DIR__.'/../Config/config.php' => config_path('base.php'),
        ], 'config');
        $this->mergeConfigFrom(
            __DIR__.'/../Config/config.php',
            'base'
        );
    }

    /**
     * Register views.
     *
     * @return void
     */
    public function registerViews()
    {
        $viewPath = resource_path('views/modules/base');

        $sourcePath = __DIR__.'/../Resources/views';

        $this->publishes([
            $sourcePath => $viewPath,
        ], 'views');

        $this->loadViewsFrom(array_merge(array_map(function ($path) {
            return $path.'/modules/base';
        }, \Config::get('view.paths')), [$sourcePath]), 'base');
    }

    /**
     * Register translations.
     *
     * @return void
     */
    public function registerTranslations()
    {
        $langPath = resource_path('lang/modules/base');

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, 'base');
        } else {
            $this->loadTranslationsFrom(__DIR__.'/../Resources/lang', 'base');
        }
    }

    /**
     * Register an additional directory of factories.
     *
     * @return void
     */
    public function registerFactories()
    {
        if (!app()->environment('production')) {
            app(Factory::class)->load(__DIR__.'/../Database/factories');
        }
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }
}
