<?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 FxftGateway extends Gateway
{
    use HasHttpRequest;


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

    /**
     * @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 = [
            'username' => $config->get('username'),
            'password' => $config->get('password'),
            'mobile' => strval($to),
            'content' => $message->getContent(),
        ];

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

        $result = $this->post($config->get('url'), $params);

        if ($result < 0) {
            $res = [
                '0' => "失败",
                '-1' => "用户名或者密码不正确",
                '-2' => "必填选项为空",
                '-3' => "短信内容0个字节",
                '-4' => "0个有效号码",
                '-5' => "余额不够",
                '-10' => "用户被禁用",
                '-11' => "短信内容超过500字",
                '-12' => "无扩展权限（ext字段需填空）",
                '-13' => "IP校验错误",
                '-14' => "内容解析异常",
                '-990' => "未知错误",
                '-25' => "没有权限(只支持web和http用户)"

            ];
            Log::error('短信发送失败', $res[$result]);
            throw new GatewayErrorException($res[$result], $result, $res[$result]);
        }

        return $result;
    }

    /**
     * Generate Sign.
     *
     * @param array $params
     *
     * @return string
     */
    protected function generateSign($params)
    {
        return md5($params['username'] . md5($params['password']));
    }
}
