<?php
/**
 * 新达达开放平台接口调用工具类
 * 详情：签名，接口调用
 * 版本：1.0
 * 日期：2017-08-30
 * Author:汉潮
 * 说明：
 * 以下代码只是为了方便对接商户测试而提供的样例代码，对接商户可以根据自己的需求，按照技术文档编写，代码仅供参考。
 */
namespace Common\Vendor\Distribute;
class Dada{
    private $config;
    private $url='';//api url地址
    private $status;//请求响应返回的数据状态
    private $code;//请求响应返回的code
    private $msg;//请求响应返回的信息
    private $result;//请求响应返回的结果
    private $isExcepet = false;//判断求是否异常
    private $excepetMsg;//异常信息    
    private $is_sandbox=false;//是否为测试
    /**
     * 构造函数
     * @param array $config = array();
     */
    public function __construct($config){
        $this->config = !empty($this->config) && !empty($config)? array_merge($this->config, $config):!empty($config)?$config:$this->config;
        if($this->is_sandbox){
            $this->config['source_id']=73753;
            $this->url="http://newopen.qa.imdada.cn";
        }else{
            $this->url="http://newopen.imdada.cn";
        }
    }
    /**
     * 新增订单
     * @param array(
     *      [shop_no]=>门店编号不能为空,
     *      [origin_id]=>第三方订单ID不能为空,
     *      [city_code]=>订单所在城市的code不能为空,
     *      [cargo_price]=>订单金额不能为空, 
     *      [expected_fetch_time]=>期望取货时间不能为空, 
     *      [receiver_name]=>收货人姓名不能为空, 
     *      [receiver_address]=>收货人地址不能为空, 
     *      [receiver_lat]=>收货人地址维度不能为空, 
     *      [receiver_lng]=>收货人地址经度不能为空, 
     *      )
     *
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return return    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function add_order($data){
        $data=$data[0];
        $return = array('status'=>0,'msg'=>'');if(empty($data)){return $return;}
        $save_data['distribute'] = 'Dada';
        M('OrderInfo')->where(array('id'=>$data['order_id']))->save($save_data);
        
        if($this->is_sandbox){$distris='11047059';}//测试环境
        else{
            $shop_id = $data["shop_id"];
            $distris = M('Shops')->where(array('id'=>$shop_id))->getField('origin_id');
            if(empty($distris)){
                $return['msg'] = "第三方门店未注册";
                return $return;
            }
        }
        //获取城市code
        $city_list = $this->city_list();
        $cityname = idtoname($data['city'],'Area','name');
        if(!$cityname){
            $citycode=0311;
        }else{
            foreach($city_list as $k=>$v){
                if(str_exists($cityname,$v['cityName']))$citycode=$v['cityCode'];
            }           
        }
        $location=$this->bd_decrypt($data['xpoint'],$data['ypoint']);
        $data['xpoint']=$location['gg_lon'];
        $data['ypoint']=$location['gg_lat'];
        
        $notify_url=U('Home/Distribute/notify',array('apitype'=>'Dada'),true,true);
        $notify_url=str_replace('index.php?s=/','',$notify_url);
        if(empty($data['tips']))$data['tips']=0.0;
        $datas = array(
            'shop_no'=> $distris,
            'origin_id'=> $data['order_sn'],
            'city_code'=> $citycode,
            'cargo_price'=> $data['goods_allmoney'],//订单金额
            'is_prepay'=> 0,//是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
            //'pay_for_supplier_fee'=> $data['goods_allmoney'],
            //'fetch_from_receiver_fee'=> $data['fetch_from_receiver_fee'],
            //'deliver_fee'=> $data['deliver_fee'],
            'tips'=> $data['tips'],//小费（单位：元，精确小数点后一位）
            'info'=> $data['temp'],//订单备注
            'cargo_type'=> $data['cargo_type'],//订单商品类型：食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29, 其他-5
            'cargo_weight'=> format_decimal($data['cargo_weight'],3),//订单重量（单位：Kg）
            'cargo_num'=> $data['cargo_num'],//订单商品数量
            'invoice_title'=> $data['invoice_title'],//发票抬头
            'receiver_name'=> $data['consignee'],//收货人姓名
            'receiver_address'=> $data['province'].$data['city'].$data['district'].$data['address'],//收货人地址
            'receiver_phone'=> $data['mobile'],//	收货人手机号（手机号和座机号必填一项）
            'receiver_tel'=> $data['receiver_tel'],//	收货人座机号（手机号和座机号必填一项）
            'receiver_lat'=> $data['ypoint'],//收货人地址维度（高德坐标系）
            'receiver_lng'=> $data['xpoint'],//收货人地址经度（高德坐标系）
            'callback'=>$notify_url//回调URL
        );
        if(empty($datas['shop_no'])){$return['msg'] = '门店编号不能为空!';}
        if(empty($datas['origin_id'])){$return['msg'] = '第三方订单ID不能为空!';}
        if(empty($citycode)){$return['msg'] = '订单所在城市的code不能为空!';}
        if(empty($datas['cargo_price'])){$return['msg'] = '订单金额不能为空!';}
        if(empty($datas['receiver_name'])){$return['msg'] = '收货人姓名不能为空!';}
        if(empty($datas['receiver_address'])){$return['msg'] = '收货人地址不能为空!';}
        if(empty($datas['receiver_lat'])){$return['msg'] = '收货人地址纬度不能为空!';}
        if(empty($datas['receiver_lng'])){$return['msg'] = '收货人地址经度不能为空!';}
        if(empty($datas['receiver_phone']) && empty($datas['receiver_tel'])){$return['msg'] = '收货人联系方式不能为空!';}
        if($return['msg'])return $return;
        //请求接口
        $reqStatus = $this->makeRequest($datas,'/api/order/addOrder');//print_r($reqStatus);exit;
        if(!$reqStatus['errorCode']){
            $return['status'] = 1;
        }else{
            $return['msg'] = $reqStatus["msg"];
        }
        return $return;
    }
    /**
     * 重发订单
     * @param array(
     *      [shop_no]=>门店编号不能为空,
     *      [origin_id]=>第三方订单ID不能为空,
     *      [city_code]=>订单所在城市的code不能为空,
     *      [cargo_price]=>订单金额不能为空, 
     *      [expected_fetch_time]=>期望取货时间不能为空, 
     *      [receiver_name]=>收货人姓名不能为空, 
     *      [receiver_address]=>收货人地址不能为空, 
     *      [receiver_lat]=>收货人地址维度不能为空, 
     *      [receiver_lng]=>收货人地址经度不能为空, 
     *      )
     *
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return return    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function readd_order($data){
        $data=$data[0];
        $return = array('status'=>0,'msg'=>'');
        if(empty($data)){return $return;}
        //获取城市code
        $city_list = $this->city_list();
        $cityname = idtoname($data['city'],'Area','name');
        if(!$cityname){
            $citycode=0311;
        }else{
            foreach($city_list as $k=>$v){
                if(str_exists($cityname,$v['cityName']))$citycode=$v['cityCode'];
            }           
        } 
        $notify_url=U('Home/Distribute/notify',array('apitype'=>'Dada'),true,true);
        $notify_url=str_replace('index.php?s=/','',$notify_url);
        if(empty($data['tips']))$data['tips']=0.0;
        
        $location=$this->bd_decrypt($data['xpoint'],$data['ypoint']);
        $data['xpoint']=$location['gg_lon'];
        $data['ypoint']=$location['gg_lat'];
        
        $param = array(
            'shop_no'=> idtoname($data['shop_id'],'Shops','origin_id'),
            'origin_id'=> $data["order_sn"],
            'city_code'=> $citycode,
            'cargo_price'=> $data['goods_allmoney'],
            //'pay_for_supplier_fee'=> $data['pay_for_supplier_fee'],
            //'fetch_from_receiver_fee'=> $data['fetch_from_receiver_fee'],
            //'deliver_fee'=> $data['deliver_fee'],
            'is_prepay'=> 0,
            'receiver_name'=> $data['receiver_name'],
            'receiver_address'=> $data['province'].$data['city'].$data['district'].$data['address'],
            'receiver_phone'=> $data['receiver_phone'],
            'receiver_tel'=> $data['receiver_tel'],
            'receiver_lat'=> $data['ypoint'],
            'receiver_lng'=> $data['xpoint'],
            'info'=> $data['info'],
            'cargo_type'=> $data['cargo_type'],
            'cargo_weight'=> format_decimal($data['cargo_weight'],3),            
            'tips'=> $data['tips'],
            'cargo_num'=> $data['cargo_num'],            
            //'expected_fetch_time'=> $data['expected_fetch_time'],
            //'expected_finish_time'=> $data['expected_finish_time'],
            'invoice_title'=> $data['invoice_title']?$data['invoice_title']:$data['receiver_name'],            
            'callback'=>$notify_url
        );
        if(!$param['shop_no']){$return['msg'] = '门店编号不能为空!';}
        if(!$param['origin_id']){$return['msg'] = '第三方订单ID不能为空!';}
        if(!$citycode){$return['msg'] = '订单所在城市的code不能为空!';}
        if(!$param['cargo_price']){$return['msg'] = '订单金额不能为空!';}
        if(!$param['expected_fetch_time']){$return['msg'] = '期望取货时间不能为空!';}
        if(!$param['receiver_name']){$return['msg'] = '收货人姓名不能为空!';}
        if(!$param['receiver_address']){$return['msg'] = '收货人地址不能为空!';}
        if(!$param['receiver_lat']){$return['msg'] = '收货人地址维度不能为空!';}
        if(!$param['receiver_lng']){$return['msg'] = '收货人地址经度不能为空!';}
        if(empty($param['receiver_phone']) && empty($param['receiver_tel'])){$return['msg'] = '收货人联系方式不能为空!';}
        if($return['msg'])return $return;
        //请求接口
        $reqStatus = $this->makeRequest($param,'/api/order/reAddOrder');
        if(!$reqStatus['errorCode']){
            $return['status'] = 1;
        }else{
            $return['msg'] = $reqStatus["result"]["failedList"][0]["msg"];
        }
        return $return;
    }
    /**
     * 第三方回调
     */
    public function notify_order($data){
        $data=$data[0];
        if(!is_array($data)){$data = json_decode($data,true);}
        if(empty($data['order_id'])){$this->https(400);return;}
        C('TOKEN_ON',false);
        $adds=D('TakeawayOrder')->create($data);
        $adds['client_id'] = $data['client_id'];
        $adds['order_code'] = $data['order_id'];
        $adds['delivery_fee'] = idtoname($data['order_id'],'OrderInfo','delivery_fee','id',false);
        if(!empty($adds['update_time']))$adds['accept_time'] = $adds['update_time'];
        $adds['marking'] = 'Dada';
        $count = D('TakeawayOrder')->where('order_id='.$data['order_id'])->find();
        if(!$count){
            D('TakeawayOrder')->add($adds);
        }else{
            if($data['order_status'] == 3)$adds['fetch_time'] = $adds['update_time'];//配送中时间
            if($data['order_status'] == 4){//已完成时间
                $adds['finish_time'] = $adds['update_time'];
                $save_data['shipping_status'] = 4;
                $save_data['status'] = 3;
                $save_data['finish_time'] = time();
                M('OrderInfo')->where('order_sn='.$data['order_id'])->save($save_data);
            };
            if($data['order_status'] == 5)$adds['cancel_time'] = $adds['update_time'];//已取消时间
            if($data['order_status'] == 7)$adds['expire_time'] = $adds['update_time'];//已过期时间
            D('TakeawayOrder')->where('order_id='.$data['order_id'])->save($adds);
        }$this->https(200);return;
    }
    /**
     * 订单详情查询
     * @param $order_id:第三方订单号
     *
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return return    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function details_order($orderid){
        $return = array('status'=>0,'msg'=>'','info'=>array());
        $orderid = $orderid[0];
        $data = array('order_id'=> $orderid);
        //请求接口
        $reqStatus = $this->makeRequest($data,'/api/order/status/query');
        if($reqStatus['errorCode']){
            $return['msg'] = $reqStatus['msg'];
            $return['info']['statusMsg'] = $reqStatus['msg'];
            $return['info']['errorCode'] = $reqStatus['result'];
        }else{
            if($reqStatus['result']['transporterLng'] && $reqStatus['result']['transporterLat']){
                $location=$this->bd_encrypt($reqStatus['result']['transporterLng'],$reqStatus['result']['transporterLat']);
                $reqStatus['result']['transporterLng']=$location['bd_lon'];
                $reqStatus['result']['transporterLat']=$location['bd_lat'];
            }
            
            $return['status'] = 1;
            $return['info'] = $reqStatus['result'];
        }
        return $return;
    }
    /**
     * 模拟订单状态
     * @param $order_id:第三方订单号
     */
    public function status_order($data){
        $data = $data['0'];
        $datas = array(
            'order_id'=> $data["order_id"]
        );
        //请求接口
        $reqStatus = $this->makeRequest($datas,'/api/order/'.$data["status"]);
        return $reqStatus;
    }
    /**
     * 获取取消原因
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return result    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function cancel_reasons_order(){
        //请求接口
        $reqStatus = $this->makeRequest($datas,'/api/order/cancel/reasons');
        return $reqStatus;
    }
    /**
     * 取消订单
     * @param $order_id:第三方订单号,取消原有id
     * @param $cancel_reason_id:取消缘由id
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return result    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function cancel_order($data){
        $data = $data['0'];
        $datas = array(
            'order_id'=> $data["order_id"],
            'cancel_reason_id'=> $data["cancel_reason_id"]
        );
        //请求接口
        $reqStatus = $this->makeRequest($datas,'/api/order/formalCancel');
        return $reqStatus;
    }
    /**
     * 获取城市信息
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return result    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function city_list(){
        $dir = ROOT_PATH."/Public/data/distribute.json";
        if(!file_exists($dir)){
            $reqStatus = $this->makeRequest($datas,'/api/cityCode/list');
            file_put_contents($dir,json_encode($reqStatus['result']));
            return $reqStatus['result'];
        }
        $data = file_get_contents($dir);  
        $return = json_decode($data,1);
        return $return;
    }
    /**
     * 注册商户
     * @param $mobile:注册商户手机号,用于登陆商户后台
     * @param $city_name:商户城市名称(如,上海)
     * @param $enterprise_name:企业全称
     * @param $enterprise_address: 企业地址
     * @param $contact_name:联系人姓名
     * @param $contact_phone:联系人电话
     * @param $email:邮箱地址
     *
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return return    响应结果，JSON对象，详见具体的接口描述
     * @return errorCode 错误编码，与code一致
     */
    public function merchant_add($postdata){
        $return = array('status'=>0,'msg'=>'');
        $postdata = $postdata[0];
        $shop = M('Shops')->where(array('id'=>$postdata['id']))->find();
        $city = idtoname($shop['city_id'],'Area','name');
        
        if(!$city){
            $city='石家庄市';
        }else{
            $city_list = $this->city_list();
            foreach($city_list as $k=>$v){
                if(str_exists($city,$v['cityName']))$city=$v['cityName'];
            }           
        }
        $datas = array(
            'mobile'=> $shop['phone'],
            'city_name'=> $city,
            'enterprise_name'=> $shop['name'],
            'enterprise_address'=> $shop['address'],
            'contact_name'=> $shop['contacts'],
            'contact_phone'=> $shop["phone"],
            'email'=> $postdata['password'],
        );
        // print_r($datas);
        //请求接口
        $reqStatus = $this->makeRequest($datas,'/merchantApi/merchant/add');
        if($reqStatus['code']==0){
            $save_data['source_id'] = $reqStatus["result"];
            $res = M('Shops')->where(array('id'=>$postdata['id']))->save($save_data);
            $res = M('Distribute')->where(array('code'=>'Dada'))->save($save_data);
            if($res){
                $return['status'] = 1;$return['msg']='注册商户成功';
            }else{
                $return['msg']="商户第三方物流标识更新失败。";
            }          
        }else{
            $return['msg']=$reqStatus["msg"];
        }
        return $return;
    }
    /**
     * 新增门店
     * @param array $data=array(
     *      $station_name:门店名称
     *      $business:业务类型(食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 
     * 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29, 其他-5)
     *      $city_name:城市名称(如,上海
     *      $area_name:区域名称(如,浦东新区)
     *      $station_address:门店地址
     *      $lng:门店经度
     *      $lat:门店纬度
     *      $contact_name:联系人姓名
     *      $phone:联系人电话
     *      $origin_shop_id:门店编码,可自定义,但必须唯一;若不填写,则系统自动生成
     *      $id_card:联系人身份证
     *      $username:达达商家app账号(若不需要登陆app,则不用设置)
     *      $password:达达商家app密码(若不需要登陆app,则不用设置)
     *      )
     *
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return result array(
     *          success     成功导入门店的数量
     *          successList 成功导入的门店
     *          failedList  导入失败门店编号以及原因
     *         )   
     * @return errorCode 错误编码，与code一致
     */
    public function shop_add($postdata){print_r($postdata);exit;
        $return = array('status'=>0,'msg'=>'');
        $postdata = $postdata[0];
        $shops_location = M('Shops')->where(array('status'=>1,'id'=>$postdata['id']))->find();
        if($shops_location['origin_id'] != '0'){
            $return['status'] = 1;
            return $return;
        }
        if(!$shops_location){
            $reqStatus['msg'] = '该门店不存在';
            return $reqStatus;
        }
        // 城市信息
        $city = idtoname($shops_location['city_id'],'Area','name');
        
        if(!$city){
            $city='石家庄市';
        }else{$city_list = $this->city_list();
            foreach($city_list as $k=>$v){
                if(str_exists($city,$v['cityName']))$city=$v['cityName'];
            }           
        }
        $location=$this->bd_decrypt($shops_location['xpoint'],$shops_location['ypoint']);
        $shops_location['xpoint']=$location['gg_lon'];
        $shops_location['ypoint']=$location['gg_lat'];
        $business=$postdata['business'];
        if(empty($business))$business=8;
        $data = array(
            'station_name'=> $shops_location["name"],
            'business'=> $business,
            'city_name'=> $city,
            'area_name'=> idtoname($shops_location["district"],'Area','name'),
            'station_address'=> $shops_location["address"],
            'lng'=> $shops_location["xpoint"],
            'lat'=> $shops_location["ypoint"],
            'contact_name'=> $shops_location["phone"],
            'phone'=> $shops_location["contacts_phone"],
        );
        $datas[] = $data;
        //请求接口
        $reqStatus = $this->makeRequest($datas,'/api/shop/add');
        if($reqStatus['code']==0){
            $sav["origin_id"] = $reqStatus["result"]["successList"][0]["originShopId"];
            $res = M('Shops')->where(array('id'=>$postdata['id']))->save($sav);
            if($business){
                $save_data=array();
                $save_data['param1']=$business;
                $res = M('Distribute')->where(array('code'=>'Dada'))->save($save_data);
            }            
            
            if($res){
                $return['status'] = 1;
                $return['msg'] = "添加成功";
            }
        }else{
            $return['msg'] =$reqStatus["msg"].$reqStatus["result"]["failedList"][0]["msg"];
        }
        return $return;
    }
    /**
     * 编辑门店
     * @param array $data=array(
     *      $origin_shop_id:门店编码
     *      $new_shop_id:新的门店编码
     *      $station_name:门店名称
     *      $business:业务类型(食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 
     * 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29, 其他-5)
     *      $city_name:城市名称(如,上海)
     *      $area_name:区域名称(如,浦东新区)
     *      $station_address:门店地址
     *      $lng:门店经度
     *      $lat:门店纬度
     *      $contact_name:联系人姓名
     *      $phone:联系人电话
     *      $status:门店状态（1-门店激活，0-门店下线）
     *      )
     *
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return result array(
     *          success     成功导入门店的数量
     *          successList 成功导入的门店
     *          failedList  导入失败门店编号以及原因
     *         )   
     * @return errorCode 错误编码，与code一致
     */
    public function shop_update($postdata){
        $return = array('status'=>0,'msg'=>'');
        $postdata = $postdata['0'];$shops_location='';
        if($postdata['id'])$shops_location = M('Shops')->where(array('id'=>$postdata['id'],'status'=>1))->find();
        if(empty($shops_location)){
            $result['msg'] = "该门店未通过审核或已闭店";
            return $result;
        }        
        $location=$this->bd_decrypt($shops_location['xpoint'],$shops_location['ypoint']);
        $shops_location['xpoint']=$location['gg_lon'];
        $shops_location['ypoint']=$location['gg_lat'];
        
        $business=$postdata['business'];
        if(empty($business))$business=8;
        $datas = array(
            'origin_shop_id'=> $shops_location['origin_id'],
            'station_name'=> $shops_location["name"],
            'business'=> $business,
            'city_name'=> $citycode,
            'area_name'=> idtoname($shops_location["district"],'Area','name'),
            'station_address'=> $shops_location["address"],
            'lng'=> $shops_location["xpoint"],
            'lat'=> $shops_location["ypoint"],
            'contact_name'=> $shops_location["contact"],
            'phone'=> $shops_location["tel"],
            'status'=> $postdata['status']
        );
        //请求接口
        $reqStatus = $this->makeRequest($datas,'/api/shop/update');
        if($reqStatus['code']==0){
            $return['status'] = 1;
            if($business){
                $save_data=array();
                $save_data['param1']=$business;
                $res = M('Distribute')->where(array('code'=>'Dada'))->save($save_data);
            }
        }else{
            $return['msg'] =$reqStatus["msg"].$reqStatus["result"]["failedList"][0]["msg"];
        }
        return $return;
    }
    /**
     * 门店详情
     * @param $origin_shop_id:门店编码
     *
     * @return status    响应状态，成功为"success"，失败为"fail"
     * @return code      响应返回吗，参考接口返回码
     * @return msg       响应描述
     * @return result    响应返回
     * @return errorCode 错误编码，与code一致
     */
    public function shop_detail($data){
        $data = $data['0'];
        $datas = array('origin_shop_id'=> $data["origin_shop_id"]);
        //请求接口
        $reqStatus = $this->makeRequest($datas,'/api/shop/detail');
        return $reqStatus;
    }
    /**
     * 请求调用api
     * data:业务数据
     * @return bool
     */
    private function makeRequest($data,$url){
        $reqParams = $this->bulidRequestParams(json_encode($data));
        $resp = $this->getHttpRequestWithPost($this->url.$url, json_encode($reqParams));
        $this->parseResponseData($resp);
        return $this->isExcepet;
    }
    /**
     * 构造请求数据
     * data:业务参数，json字符串
     */
    private function bulidRequestParams($body){
        $requestParams = array();
        $requestParams['app_key'] = $this->config['app_key'];
        $requestParams['body'] = $body;
        $requestParams['format'] = 'json';
        $requestParams['v'] = '1.0';
        $requestParams['source_id'] = $this->config['source_id'];
        $requestParams['timestamp'] = time();
        $requestParams['signature'] = $this->_sign($requestParams);
        return $requestParams;
    }
    /**
     * 签名生成signature
     */
    private function _sign($data){
        ksort($data);//1.升序排序
        $args = "";//2.字符串拼接
        foreach ($data as $key => $value) {$args.=$key.$value;}
        $args = $this->config["app_secret"].$args.$this->config["app_secret"];
        $sign = strtoupper(md5($args));//3.MD5签名,转为大写
        return $sign;
    }
    /**
     * 发送请求,POST
     * @param $url 指定URL完整路径地址
     * @param $data 请求的数据
     */
    private function getHttpRequestWithPost($url, $data){
        // json
        $headers = array('Content-Type: application/json',);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 3);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $resp = curl_exec($curl);
       // var_dump( curl_error($curl) );//如果在执行curl的过程中出现异常，可以打开此开关查看异常内容。
        $info = curl_getinfo($curl);
        curl_close($curl);
        if (isset($info['http_code']) && $info['http_code'] == 200) {
            return $resp;
        }
        return '';
    }
    /**
     * 解析响应数据
     * @param $arr返回的数据
     * 响应数据格式：{"status":"success","result":{},"code":0,"msg":"成功"}
     */
    private function parseResponseData($arr){
        if (empty($arr)) {
            $this->isExcepet = true;
            $this->excepetMsg = "接口请求失败";
        }else{
            $data = json_decode($arr, true);
            $data['status'] = 1;
            $this->isExcepet = $data;
        }
        return $this->isExcepet;
    }
    /**
     * BD-09(百度)坐标转换成GCJ-02(火星，高德)坐标
     * @param bd_lon 百度经度
     * @param bd_lat 百度纬度
     */
    private function bd_decrypt($bd_lon,$bd_lat){
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $x = $bd_lon - 0.0065;
        $y = $bd_lat - 0.006;
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
        $gg_lon = $z * cos($theta);
        $gg_lat = $z * sin($theta);
        // 保留小数点后六位
        $data['gg_lon'] = round($gg_lon, 6);
        $data['gg_lat'] = round($gg_lat, 6);
        return $data;
    }
    /**
     * GCJ-02(火星，高德)坐标转换成BD-09(百度)坐标
     * @param bd_lon 百度经度
     * @param bd_lat 百度纬度
     */
    private function bd_encrypt($gg_lon,$gg_lat){
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $x = $gg_lon;
        $y = $gg_lat;
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
        $bd_lon = $z * cos($theta) + 0.0065;
        $bd_lat = $z * sin($theta) + 0.006;
        // 保留小数点后六位
        $data['bd_lon'] = round($bd_lon, 6);
        $data['bd_lat'] = round($bd_lat, 6);
        return $data;
    }
    /** 
     * HTTP Protocol defined status codes
     * HTTP协议状态码,调用函数时候只需要将$num赋予一个下表中的已知值就直接会返回状态了。
     * @param int $num
     */ 
    function https($num) { 
        $http = array ( 
            200 => "HTTP/1.1 200 OK",
            400 => "HTTP/1.1 400 Bad Request", 
            401 => "HTTP/1.1 401 Unauthorized", 
            402 => "HTTP/1.1 402 Payment Required", 
            403 => "HTTP/1.1 403 Forbidden", 
            404 => "HTTP/1.1 404 Not Found", 
            500 => "HTTP/1.1 500 Internal Server Error",
        ); 
        header($http[$num]); 
    }
}
?>