<?php


namespace common\libs\api\sms\meilian;

use yii\helpers\Json;
use yii\httpclient\Client;

class SmsSend
{
    private $_username;
    private $_password;
    private $_apikey;

    private $_url='https://m.5c.com.cn/api/send/index.php';
    private $_encode='UTF-8';

    private $_client;
    private $_response;
    private $_error = [];

    private $_errorCode;

    public function __construct($username, $password, $apikey) {
        $this->_username = $username;
        $this->_password = $password;
        $this->_apikey = $apikey;
        $this->_errorCode = require \Yii::getAlias('@common/libs/api/sms/meilian/') . 'errorCode.php';
    }

    public function getError(){
        return $this->_error;
    }

    public function send(array $params) {
        $this->_error = null;
        if($this->_client === null) {
            $this->_client = new Client();
        }
        $data = [
            'type' => 'send',
            'apikey' => $this->_apikey,
            'username' => $this->_username,
            'password_md5' => md5($this->_password),
            'encode' => $this->_encode,
            'mobile' => $params['mobiles'],
            'content' => urlencode($params['content']),
        ];
        $sendData = [
            'format' => 'json',
            'data' => Json::encode($data),
        ];
        $this->_response = $this->_client->createRequest()
            ->setMethod('post')
            ->setUrl($this->_url)
            ->setData($sendData)
            ->send();

        if(!$this->_response->isOk){
            $this->_error[] = '网络错误，短信发送失败';
            return false;
        }
        if($this->_response->data['status'] == 'error'){
            $errKey = $this->_response->data['msg'];
            if(isset($this->_errorCode[$errKey])){
                $this->_error[] = $this->_errorCode[$errKey];
            } else {
                $this->_error[] = $errKey;
            }
            return false;
        }
        unset($data);
        return true;
    }




}