<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/12
 * Time: 17:35
 */
namespace Modules\Base\Services;

use SMG\Support\Traits\ConstantInfo;

class SmsService extends BaseService
{
    use ConstantInfo;

    public const REGISTER = 1;
    public const FIND_PASSWORD = 2;
    public const CHANGE_PHONE = 3;
    public const ADD_CARD = 4;
    public const SET_PAY_PASSWORD = 5;
    public const LOGIN = 6;

    /**
     * 检查要发送的类型是应该向新手机号发还是已经存在的手机号发
     *
     * @param $type
     *
     * @return bool
     */
    public static function needNewPhone($type)
    {
        return in_array($type, [self::REGISTER, self::CHANGE_PHONE]);
    }

    /**
     * 短信验证时附加检查规则
     *
     * @param $type
     *
     * @return string
     */
    public static function appendPhoneValidateRule($type)
    {
        switch ($type) {
            case self::REGISTER:
            case self::CHANGE_PHONE:
                return '|unique:users';
            case self::FIND_PASSWORD:
            case self::SET_PAY_PASSWORD:
                return '|exists:users';
            default:
                return '';
        }
    }

    /**
     * 发送该类型短信是否需要登陆
     *
     * @param $type
     *
     * @return string
     */
    public static function needAuth($type)
    {
        switch ($type) {
            case self::CHANGE_PHONE:
            case self::SET_PAY_PASSWORD:
                return true;
            default:
                return false;
        }
    }

    /**
     * 发送该类型短信是否需要检查手机号信息
     *
     * @param $type
     *
     * @return string
     */
    public static function needUserPhone($type)
    {
        return in_array($type, [self::SET_PAY_PASSWORD]);
    }

    public static function getTypes()
    {
        $oClass = new \ReflectionClass(static::class);

        return array_values($oClass->getConstants());
    }

    public function send($phone, $type, $args = [])
    {
        $this->generateCode($phone, $type);

        return true;
    }

    public function generateCode($phone, $type)
    {
        $code = '1234';
        $key = 'sms_'.$type.'_'.$phone;
        \Cache::put($key, $code, 5);

        return $code;
    }

    /**
     * @param $code
     * @param $type
     * @param $phone
     * @param bool $return
     *
     * @return bool
     */
    public function verifyCode($code, $type, $phone, $return = false)
    {
        if (env('IGNORE_SMS_CHECK', 'false') == 'true') {
            return true;
        }

        if ($code == '88888888') {
            return true;
        }

        $key = 'sms_'.$type.'_'.$phone;

        if ($code != '' && \Cache::get($key) == $code) {
            //\Cache::forget($key);
            return true;
        }

        if ($return) {
            return false;
        }

        $error = \Illuminate\Validation\ValidationException::withMessages([
            'code' => ['手机验证码错误或已过期，请重试'],
        ]);

        throw $error;
    }
}
