<?php

namespace Dipper\Sms\Gateways;

use Dipper\Sms\Support\Config;
use Illuminate\Support\Facades\Log;
use Dipper\Sms\Traits\HasHttpRequest;
use Dipper\Sms\Contracts\MessageInterface;
use Dipper\Sms\Exceptions\GatewayErrorException;

class HuyiGateway extends Gateway
{
    use HasHttpRequest;

    const ENDPOINT_URL = 'http://106.ihuyi.com/webservice/sms.php?method=Submit';

    const ENDPOINT_FORMAT = 'json';

    const SUCCESS_CODE = 2;

    /**
     * Get gateway name.
     *
     * @return string
     */
    public function getName()
    {
        return 'huyi';
    }

    /**
     * @param array|int|string                             $to
     * @param \Dipper\Sms\Contracts\MessageInterface $message
     * @param \Dipper\Sms\Support\Config             $config
     *
     * @return array
     *
     * @throws \Dipper\Sms\Exceptions\GatewayErrorException;
     */
    public function send($to, MessageInterface $message, Config $config)
    {
        $params = [
            'account' => $config->get('api_id'),
            'mobile' => strval($to),
            'content' => $message->getContent(),
            'time' => time(),
            'format' => self::ENDPOINT_FORMAT,
        ];

        $params['password'] = $this->generateSign($params);

        $result = $this->post(self::ENDPOINT_URL, $params);

        if (self::SUCCESS_CODE != $result['code']) {
            Log::error('短信发送失败', $result);
            throw new GatewayErrorException($result['msg'], $result['code'], $result);
        }

        return $result;
    }

    /**
     * Generate Sign.
     *
     * @param array $params
     *
     * @return string
     */
    protected function generateSign($params)
    {
        return md5($params['account'].$this->config->get('api_key').$params['mobile'].$params['content'].$params['time']);
    }
}
