<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use \app\common\util\http;


class Sms extends BaseController
{

    protected $users = [
        [
            'keyID'     => '123456',
            'keySecret' => '',
        ]
    ];


    /**
     * 未做，日志记录，出错记录等
     *
     * 格式
    POST https://stest.uzipm.com/sms/send HTTP/1.1
    User-Agent: okhttp/2.7.5
    Accept-Encoding: gzip
    Connection: Keep-Alive
    Host: stest.uzipm.com
    Content-Length: 82
    Content-Type: application/json; charset=utf-8

    {"senderid":"MiChat","to":"6590511066","countryID":"SG","content":"test from gzh"}

     * 未做，日志记录，出错记录等
     */
    function send(){


        $input = file_get_contents("php://input");
        $input = json_decode($input,true);
        $countryID = $input['countryID']; //CN,SG
        $phoneNumber = $input['to'];
        $content = $input['content'];


        $param['user']=$content;
        $params['smsTemplateId'] = '0a2dc8e2-0f64-4b41-a10c-50222d8b6e65';
        $params['paramValues'] = $param; //        paramValues:{"user":"XXX"}
        $params['msisdn']      = $phoneNumber;
        $params['countryID']   = $countryID;


        $url                     = "https://www.huaweiita.com:17131/apiaccess/sms/sendTemplateSms/v1";
        $retCurl = curl_huawei_sms($url, json_encode($params));
        $retCurl = json_decode($retCurl,true); //原始信息入库
        if($retCurl['code'] == '0000000'){
            $ret['code'] = 1;
            $ret['msg']  = $retCurl['description'];
        }else{
            $ret['code'] = 0;
            $ret['msg']  = $retCurl['description'];
            $ret['error_code'] = $retCurl['code'];
            $ret['error_msg'] = $retCurl['exErrorMessage'];

            //记录原始错误消息入库
        }


    }

    /**
     * $templateId
     * $param
     * $phone_number
     * countryID
     */
    function sendByAuth()
    {

        $headerAuthorization = I('server.HTTP_AUTHORIZATION');
        $headerAuthorization = str_replace('"', '', $headerAuthorization);
        $headerAuthorization = explode(',', $headerAuthorization);
        $headerAuthorization = array_map(function ($v) {
            return trim($v);
        }, $headerAuthorization);
        parse_str(implode('&', $headerAuthorization), $headerAuthorization);


        $postDta = file_get_contents('php://input');
        $postDta = json_decode($postDta, true);

        $postNonce = $headerAuthorization['nonce'];
        $postTime  = $headerAuthorization['time'];
        $postKeyID = $headerAuthorization['keyID'];
        $postSign  = $headerAuthorization['sign'];


        $dbUserInfo = Db::name('user')->where(['key_id' => $headerAuthorization['keyID']])->find();
        $param      = $postDta['paramValues'];

        $dbUserInfo               = [];
        $dbUserInfo['key_id']     = "123456";
        $dbUserInfo['key_secret'] = "12345678";


        $ret = [];

        $sign = $this->makeSign($postNonce, $postTime, $dbUserInfo['key_secret']);
        if ($sign != $postSign) {
            $templateId  = I('template_id');
            $templateId  = "sms_123456";
            $phoneNumber = I('phoneNumber'); //8615812345678

            $templateContent = '短信内容 {$content} [test]';
            $smsContent      = str_replace('{$user}', $param['user'], $templateContent);

            $countryID = I('countryID');

            $countryID = 'CN';


            $url                     = "https://www.huaweiita.com:17131/apiaccess/sms/sendTemplateSms/v1";
            $params['smsTemplateId'] = '695db7b5-6d4f-4791-aea0-f733f2ef06ce';

            $params['paramValues'] = $param; //        paramValues:{"user":"XXX"}
            $params['msisdn']      = $phoneNumber;
            $params['countryID']   = $countryID;
            $params['operatorCode']   = $postDta['operatorCode'];


            $retCurl = curl_huawei_sms($url, json_encode($params));
            $retCurl = json_decode($retCurl,true); //原始信息入库
            if($retCurl['code'] == '0000000'){
                $ret['code'] = 1;
                $ret['msg']  = $retCurl['description'];
            }else{
                $ret['code'] = 0;
                $ret['msg']  = $retCurl['description'];
                $ret['error_code'] = $retCurl['code'];
                $ret['error_msg'] = $retCurl['exErrorMessage'];

                //记录原始错误消息入库
            }
            //var_dump($ret);exit('sb');


        } else {
            $ret         = [];
            $ret['code'] = 0;
            $ret['msg']  = 'authentication failure';
            //return $ret;
            //echo json_encode($ret);
            // exit;

        }

        return $ret;


        //$sign      = "";


    }

    function makeSign($nonce, $time, $key)
    {
        $signRawString = $nonce . $time . $key;
        return base64_encode(hash('sha256', $signRawString));

    }

    /**
     *
     * 检测签名
     */
    public function CheckSign()
    {

        $sign = $this->MakeSign();
        if ($this->GetSign() == $sign) {
            return true;
        }
        throw new WxPayException("签名错误！");
    }


    function sendToH3c()
    {
        $url                     = "https://www.huaweiita.com:17131/apiaccess/sms/sendTemplateSms/v1";
        $params                  = [];
        //$params['smsTemplateId'] = '695db7b5-6d4f-4791-aea0-f733f2ef06ce';
        $params['smsTemplateId'] = '0a2dc8e2-0f64-4b41-a10c-50222d8b6e65';
        $paramValues             = [];
        $paramValues['user']     = 'test1';
        $params['paramValues']   = $paramValues; //        paramValues:{"user":"XXX"}
        $params['msisdn']        = '8615821868265';
        $params['countryID']     = 'SG';
        //$params['msisdn']        = '8613162836361';
        //$params['countryID']     = 'CN';



        $ret = curl_huawei_sms($url, json_encode($params));
    }


    function sendByGuzzle()
    {


        $url                     = "https://www.huaweiita.com:17131/apiaccess/sms/sendTemplateSms/v1";
        //$url                     = "http://stest.uzipm.com/index/index";
        $params                  = [];
        $params['smsTemplateId'] = '695db7b5-6d4f-4791-aea0-f733f2ef06ce';
        $params['smsTemplateId'] = '0a2dc8e2-0f64-4b41-a10c-50222d8b6e65';
        $paramValues             = [];
        $paramValues['user']     = 'test1';
        $params['paramValues']   = $paramValues; //        paramValues:{"user":"XXX"}
        $params['msisdn']        = '8615821868265';
        $params['countryID']     = 'SG';
//        $params['msisdn']        = '8613162836361';
//        $params['countryID']     = 'CN';



        //$ret = curl_post_json($url, json_encode($params));

        $header = $this->getHeader();

        $http = new http();
        $http->request($url,'post',json_encode($params),$header);
    }

    function getHeader(){
        date_default_timezone_set("UTC");
        //$nonce          = '66C92B11FF8A425FB8D4CCFE';
        $nonce = $nonce1          = mt_rand(100000,9999999999);
        $time           = time();
        $created        = date('Y-m-d', $time) . 'T' . date('H:i:s', $time) . 'Z';
        //$created        = '2019-07-10T15:02:08Z';

        //test
        $username = 'd9c3190120db4b2ab078a543d59ba47d';
        $password       = '33ab0a75ee246f85e41f2c15d867ca5d';

        //正式
        $username='67ef6805e6004cce9cce24b7f13767c6';
        $password       = '1e88f55b4e034b1783e2686ec9dfbffd';
        $nonce = base64_encode($nonce);// . $created . $password;
        $signRawString = $nonce . $created . $password;//;//
        echo "明文:", $signRawString,"\n";
        echo "明文:", $signRawString,"\n";
        //$signRawString = '66C92B11FF8A425FB8D4CCFE2019-07-08T17:56:46Z33ab0a75ee246f85e41f2c15d867ca5d';
        //$signRawString='a';
        //var_dump(hash('sha256',$signRawString,true));exit;
        $passwordDigest = base64_encode(hash('sha256',$signRawString,true));

        //echo "明文: $signRawString \n";
        //echo "密文: $passwordDigest \n";
        //exit;

        $headerArr=[];
        $headerArr['Authorization'] = 'WSSE realm="SDP", profile="UsernameToken", type="Appkey"';
        $headerArr['X-WSSE'] = 'UsernameToken Username="'.$username.'",PasswordDigest="' . $passwordDigest . '",Nonce="' . $nonce . '",Created="' . $created . '"';
        $headerArr['Content-Type'] = 'application/json; charset=UTF-8';
        return $headerArr;
    }


}

