<?php

namespace App\Services\Sms;

use App\Dao\Sms\SmsDao;
use App\Libs\AliSMS;

class SmsService
{
    private $smsDao;

    public function __construct(SmsDao $smsDao)
    {
        $this->smsDao = $smsDao;
    }

    /**
     * 发送短信
     *
     * @param       $phone
     * @param       $templateType
     * @param array $param
     * @return bool
     */
    public function sendSms($phone, $templateType, array $param = []): bool
    {
        // 测试环境不发验证码
//        if (env('APP_ENV') === 'local') {
//            return true;
//        }

        // 根据类型找模板
        $smsTemplate = $this->smsDao->getSmsTemplate($templateType);
        if (empty($smsTemplate)) {
            return false;
        }

        // 模板id
        $sign         = env('SMS_SIGN');
        $templateCode = getProp($smsTemplate, 'template_id');
        $response     = AliSMS::sendSms($phone, $templateCode, $param, $sign);
        $status       = $response->statusCode == 200 ? 1 : 0;

        // 记录日志
        $this->smsDao->recordSmsLog([
            'template_id'    => $smsTemplate->id,
            'template_type'  => $templateType,
            'template_name'  => $smsTemplate->name,
            'phone'          => $phone,
            'template_param' => json_encode($param),
            'status'         => $status,
        ]);

        return (bool)$status;
    }
}