<?php

namespace Modules\User\Facades;

use Illuminate\Support\Arr;
use Modules\User\Models\Sms as SmsModel;
use Modules\User\Models\SmsConfig;
use Modules\User\Services\VerificationCode;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Overtrue\EasySms\Strategies\OrderStrategy;

class Sms
{

    /**
     * Notes   : 获取短信配置
     *
     * @Date   : 2021/5/27 4:01 下午
     * @Author : <Jason.C>
     * @param  string|null  $key  配置的主键
     * @return mixed
     */
    public static function getConfig(string $key = null)
    {
        $model = SmsConfig::orderByDesc('in_use')->first();

        $config = [
            'debug'      => $model->debug ?? true,
            'debug_code' => $model->debug_code ?? '0000',
            'length'     => $model->length ?? 4,
            'template'   => $model->template ?? [],
            'default'    => [
                'strategy' => OrderStrategy::class,
                'gateways' => [
                    $model->default_gateway ?? 'aliyun',
                ],
            ],
            'gateways'   => [
                $model->default_gateway => $model->getGateway(),
            ],
        ];

//        dd($config);

        if (isset($config['gateways']['aliyun'])) {
            $config['gateways']['aliyun']['access_key_id'] = $config['gateways']['aliyun']['APP_ID'];
            $config['gateways']['aliyun']['access_key_secret'] = $config['gateways']['aliyun']['APP_SECRET'];
            $config['gateways']['aliyun']['sign_name'] = $config['gateways']['aliyun']['SIGN_NAME'];
        }

        return Arr::get($config, $key) ?? $config;
    }

    /**
     * Notes   : 发送验证码短信
     *
     * @Date   : 2021/5/26 4:17 下午
     * @Author : <Jason.C>
     * @param  string  $mobile  手机号码
     * @param  string  $channel  验证通道
     * @throws InvalidArgumentException
     * @throws NoGatewayAvailableException
     */
    public static function sendVerificationCode(string $mobile, string $channel = 'DEFAULT')
    {
        $message = new VerificationCode(self::getConfig(), $channel);

        if (! self::getConfig('debug')) {
            app('sms')->send($mobile, $message);
        }

        SmsModel::create([
            'mobile'  => $mobile,
            'channel' => $channel,
            'gateway' => self::getConfig('debug') ? 'debug' : self::getConfig('default.gateways.0'),
            'content' => $message->code,
        ]);
    }

    /**
     * 验证短信
     *
     * @Author:<C.Jason>
     * @Date  :2018-11-07T14:26:38+0800
     * @param  string  $mobile  手机号码
     * @param  string  $code  验证码
     * @param  string  $channel  验证通道
     * @return bool
     */
    public static function checkCode(string $mobile, string $code, string $channel = 'DEFAULT'): bool
    {
        $Sms = SmsModel::where('mobile', $mobile)->where('channel', $channel)->first();

        if ($Sms && $Sms->content == $code) {
            if ($Sms->used && ! self::getConfig('debug')) {
                return false;
            }
            # todo 有效期判定
            $Sms->used = 1;
            $Sms->save();

            return true;
        } else {
            return false;
        }
    }

    /**
     * Notes   : 发送通知短信
     *
     * @Date   : 2021/5/26 5:08 下午
     * @Author : <Jason.C>
     * @param  string|array  $mobile  接受短信的手机号
     * @param  string  $content  短信内容
     */
    public static function sendNotification($mobile, string $content)
    {
        # todo. 这里要实现批量发送，短信通道等操作，待测试
    }

}
