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

class SmsService extends BaseService
{
    const REGISTER = 1;
    const FIND_PASSWORD = 2;
    const CHANGE_PHONE = 3;
    const ADD_CARD = 4;
    const SET_PAY_PASSWORD = 5;

    /**
     * 检查要发送的类型是应该向新手机号发还是已经存在的手机号发
     *
     * @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)
    {
        switch ($type) {
            case self::SET_PAY_PASSWORD:
                return true;
            default:
                return false;
        }
    }

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

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

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

        return true;
    }

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

        return $code;
    }

    public function verifyCode($code, $type, $phone, $return = false)
    {
        $key = 'sms_'.$type.'_'.$phone;
        if (\Cache::get($key) == $code) {
            //\Cache::forget($key);
            return true;
        } else {
            if ($return) {
                return false;
            }
            $error = \Illuminate\Validation\ValidationException::withMessages([
                'code' => ['手机验证码错误或已过期，请重试'],
            ]);
            throw $error;
        }
    }
}
