<?php
use phpDocumentor\Reflection\Types\Array_;
defined('ReqURL') or define('ReqURL', 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx');
//独立后台商家地址
// function mweb($do,$params = array(),$addhost=false){

//     if(empty($do)){
//         return false;
//     }
//     $do.="mweb".$do;
//     $url = $this->createMobileUrl($do,$params);
//     if ($addhost) {
//        $url = $_W['siteroot'] . 'app/' . substr($url, 2);
//     }
// }
function mweb($do,$params = array(),$addhost=false){
    global $_W;
    if(empty($do)){
        return false;
    }
    $do="mweb".$do;
//     list($ctrl, $ac, $op, $ta) = explode('/', $do);
    $basic = array('do' =>$do, 'm' => 'evzg_express');
    $params = array_merge($basic, $params);
    $url = murl('entry', $params);
    if ($addhost) {
        $url = $_W['siteroot'] . 'app/' . substr($url, 2);
    }
    return $url;
}
function cweb($do,$params = array(),$addhost=false){
    global $_W;
    if(empty($do)){
        return false;
    }
    $do="mweb".$do;
    //     list($ctrl, $ac, $op, $ta) = explode('/', $do);
    $basic = array('do' =>$do, 'm' => 'evzg_express','a'=>'entry');
    $params = array_merge($basic, $params);
    $url = url('site', $params);
    if ($addhost) {
        $url = $_W['siteroot'] . 'web/' . substr($url, 2);
    }
    return $url;
}
function cmurl($segment, $params = array(), $addhost = false)
{
	global $_W;
	list($ctrl, $ac, $op, $ta) = explode('/', $segment);
	$basic = array('ctrl' => $ctrl, 'ac' => $ac, 'op' => $op, 'ta' => $ta, 'do' => 'mobile', 'm' => 'evzg_express');
	$params = array_merge($basic, $params);
	$url = murl('entry', $params);

	if ($addhost) {
		$url = $_W['siteroot'] . 'app/' . substr($url, 2);
	}

	return $url;
}
function build_order_no()
{
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);
    $order_no = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    $orderno = substr($order_no,3,2);
    return $orderno;
}
function getEvgShop($expressn){
    $setting = getSetting();
    $kd = new Kd($setting['uid'], $setting['apikey']);
    $logisticResult = $kd->getOrderTracesByJson($expressn);
    $logisticResult =json_decode($logisticResult,true);
    $data = ['shippercode'=>$logisticResult['Shippers'][0]['ShipperCode'],'shippername'=>$logisticResult['Shippers'][0]['ShipperName']];
    //die($data);
    if($logisticResult['Success']){
        return $data;
    }else{
        return false;
    }
}
/***
 * 获取快递接口
 *
 * */
function getEvgLink($expressn,$exprescode){
    $setting = getSetting();
    $kd = new Kd($setting['uid'], $setting['apikey']);
    $data = $kd->getTracesByJson($exprescode, $expressn);
    $data = json_decode($data,true);
    if($data['Success']){
        return $data['Traces'];
    }else{
        return false;
    }
}
function getmedia($access_token,$media_id,$foldername){
    $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
    if (!file_exists("../attachment/images/".$foldername)) {
        mkdir("../attachment/images/".$foldername, 0777, true);
    }
    $targetName = '../attachment/images/'.$foldername.'/'.date('YmdHis').rand(1000,9999).'.jpg';
    $ch = curl_init($url); // 初始化
    $fp = fopen($targetName, 'wb'); // 打开写入
    curl_setopt($ch, CURLOPT_FILE, $fp); // 设置输出文件的位置，值是一个资源类型
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    $targetName = str_replace("../attachment/","",$targetName);
    return $targetName;
}

function get_shopname($sid)
{
    global $_W;
    $data = pdo_fetch("SELECT * FROM " . tablename('evzg_express_shop') . ' WHERE uniacid = :uniacid AND id = :id', array(
        ':uniacid' => $_W['uniacid'],
        ':id' => $sid,
    ));
    if(empty($data)){
        $data['name'] ="暂无绑定服务商店";
    }
    return $data['name'];
}

function get_community($cid)
{
    global $_W;
    $data = pdo_fetch("SELECT * FROM " . tablename('evzg_express_community') . ' WHERE uniacid = :uniacid AND id= :id ', array(
        ':uniacid' => $_W['uniacid'],
        ':id' => $cid,
    ));
    if(empty($data)){
        $data['title'] ="暂无绑定小区";
    }
    return $data['title'];
}
/**
* 创建永久二维码
* @date: 2017年12月16日 下午11:36:49
* @author: Administrator
* @param: qrid 二维码参数
* @return: false OR 二维码ticket
*/
function create_ticket($qrid){
    global $_W;
   load()->model('account');
   $uniacccount = WeAccount::create($_W['uniacid']);
   $barcode['action_info']['scene']['scene_str'] = $qrid;
   $barcode['action_name'] = 'QR_LIMIT_STR_SCENE';
   $result = $uniacccount->barCodeCreateFixed($barcode);
   if($result){
       return $result;
   }else {
       return false;
   }
}
/**
* 发送信息
* @date: 2017年12月17日 上午2:59:01
* @author: Administrator
* @param: $GLOBALS
* @return:
*/
function sendMsg($data){
     global $_W, $_GPC;
//      $data = json_decode($data,true);
//      if(empty($data['openid'])){
//          return  false;
//      }else{
//          $data = json_encode($data);
//      }
     load()->classs('weixin.account');
     $account_api = WeAccount::create();
     $account_api->clearAccessToken();
     $access_token = $account_api->getAccessToken();
     load()->func('communication');
     $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
     $response = ihttp_request($url, $data);
     if (is_error($response)) {
    	message("访问公众平台接口失败, 错误: {$response['message']}",referer(),"error");
     }
     $result = json_decode($response['content'], true);
     if (empty($result)) {
    	message("接口调用失败, 元数据: {$response['meta']}",referer(),"error");
     } elseif (!empty($result['errcode'])) {
    	message( "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']},信息详情：{$this->error_code($result['errcode'])}",referer(),"error");
     }
	 return true;
}
/**
 * 获取参数设置
 * */
function getSetting(){
    global $_W;
    $settings = pdo_fetch("SELECT * FROM ".tablename('uni_account_modules')." WHERE module = :module AND uniacid = :uniacid", array(':module' => 'evzg_express', ':uniacid' => $_W['uniacid']));

    $setting = iunserializer($settings['settings']);
   // exit(json_encode($settings));
    return $setting;
}
/**
* 发送订单消息通知
* @date: 2018年1月14日 上午1:04:52
* @author: 闵晓天 QQ416883181
* @param: $GLOBALS
* @return: true or false
*/
function sendOrderMsg($openid,$data,$templateid){
    global $_W, $_GPC;
    if(!empty($openid)){
       return false;
    }
    $template = array(
        "touser" => $openid,
        "template_id" => $templateid,
        "url" => $_W['siteroot'] . 'app/' . $this->createMobileUrl('express'),
        "topcolor" => "#FF0000",
        "data" => array(
            'first' => array(
                'value' => urlencode("您好，你的快递{$data['expresssn']}已经到达{$data['name']}门店" . "\\n"),
                'color' => "#743A3A"
                    ),
                    'keyword1' => array(
                        'value' => urlencode($data['orderno']),
                        'color' => '#000000'
                    ),
                    'keyword2' => array(
                        'value' => urlencode($data['expresssn']),
                        'color' => '#EF4F4F'
                    ),
                    'keyword3' => array(
                        'value' => urlencode($data['name']),
                        'color' => '#EF4F4F'
                    ),
                    'keyword4' => array(
                        'value' => urlencode($data['mobile']),
                        'color' => '#EF4F4F'
                    ),
                    'remark' => array(
                        'value' => urlencode("\\n感谢您的使用"),
                        'color' => "#01579b"
                    )
        )
    );
   $result = sendMsg(urldecode(json_encode($template)));
   return $result;
}
function sendSms($mobile,$TemplateCode,$TemplateParam,$settings) {
        $params = array ();

        // *** 需用户填写部分 ***

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = $settings['dayu']['dayu_appkey'];
        $accessKeySecret = $settings['dayu']['dayu_secretkey'];

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $mobile;

        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = $settings['dayu']['dayu_sign'];

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $TemplateCode;

        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = $TemplateParam;

        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"]);
        }
        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
        );

       return $content;
}
/**
* 聚合短信发送
* @date: 2018年1月20日 下午8:31:22
* @author: Administrator
* @param: $GLOBALS
* @return:
*/
function juHeSms($key,$mobile,$tpl_id,$tpl_value){
    $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL

    $smsConf = array(
        'key'   => $key, //您申请的APPKEY
        'mobile'    => $mobile, //接受短信的用户手机号码
        'tpl_id'    => $tpl_id, //您申请的短信模板ID，根据实际情况修改
        'tpl_value' =>$tpl_value //您设置的模板变量，根据实际情况修改
    );

    $content = juhecurl($sendUrl,$smsConf,1); //请求发送短信
    if($content){
        $result = json_decode($content,true);
        $error_code = $result['error_code'];
        if($error_code == 0){
            //状态为0，说明短信发送成功
           return true;
        }else{
            //状态非0，说明失败
            return false;
//             $msg = $result['reason'];
//             echo "短信发送失败(".$error_code.")：".$msg;
        }
    }else{
        //返回内容异常，以下可根据业务逻辑自行修改
        return false;
    }
}
/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juhecurl($url,$params=false,$ispost=0){
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    if( $ispost )
    {
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
    }
    else
    {
        if($params){
            curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
        }else{
            curl_setopt( $ch , CURLOPT_URL , $url);
        }
    }
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
}
/**
* 新版阿里短信接口
* @date: 2018年1月20日 下午8:29:06
* @author: MIn晓天 QQ416883181
* @param: 阿里短信
* @return:
*/
class SignatureHelper {

    /**
     * 生成签名并发起请求
     *
     * @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)
     * @param $accessKeySecret string AccessKeySecret
     * @param $domain string API接口所在域名
     * @param $params array API具体参数
     * @return bool|\stdClass 返回API接口调用结果，当发生错误时返回false
     */
    public function request($accessKeyId, $accessKeySecret, $domain, $params) {
        $apiParams = array_merge(array (
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0,0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
        }

        $stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true));

        $signature = $this->encode($sign);

        $url = "http://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";

        try {
            $content = $this->fetchContent($url);
            return json_decode($content);
        } catch( \Exception $e) {
            return false;
        }
    }

    private function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

    private function fetchContent($url) {
        if(function_exists("curl_init")) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "x-sdk-client" => "php/2.0.0"
            ));
            $rtn = curl_exec($ch);

            if($rtn === false) {
                trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
            }
            curl_close($ch);

            return $rtn;
        }

        $context = stream_context_create(array(
            "http" => array(
                "method" => "GET",
                "header" => array("x-sdk-client: php/2.0.0"),
            )
        ));

        return file_get_contents($url, false, $context);
    }
}
