<?php
namespace Common\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");

/**
 * 饿了么-蜂鸟配送
 */

class EleController extends Controller
{	
	private $ele_config = array();// 全局配置参数
	private $salt = 2345;// 1000~9999随机数

	// 接口请求地址
	private $open_url = 'https://open-anubis.ele.me/anubis-webapi';// 正式http请求URL
	private $exam_url = 'https://exam-anubis.ele.me/anubis-webapi';// 联调http请求URL
	// 统一请求接口
	private  $commen_url;
	// 统一回调地址
	private $notify_url;

	// 获取token的接口
	private $access_token_url = '/get_access_token';

	// 蜂鸟配送推单接口
	private $order_url = '/v2/order';
	// 订单取消接口
	private $cancle_url = '/v2/order/cancel';
	// 订单查询接口
	private $query_url = '/v2/order/query';
	// 订单投诉接口
	private $complaint_url = '/v2/order/complaint';

	// 添加门店信息接口，添加的门店需审核
	private $chain_store_url = '/v2/chain_store';
	// 查询门店信息接口
	private $query_chain_store_url = '/v2/chain_store/query';
	// 更新门店信息接口，更新的门店需重新审核
	private $update_chain_store_url = '/v2/chain_store/update';
	// 查询配送服务接口
	private $query_delivery_url = '/v2/chain_store/delivery/query';

	// 查询骑手位置接口
	private $query_carrier_url = '/v2/order/carrier';

	public function __construct()
	{
		parent::__construct();
		$config = M('ele_config')->find();

		if (empty($config)) {
			$this->ajaxReturn(['status' => -1, 'msg' => '蜂鸟配送参数错误！']);die;
		}

		$this->ele_config = $config;
		$this->salt = mt_rand(1000, 9999);

		// 注：正式上线需将$exam_url联调接口换成正式接口$open_url
		$this->commen_url = $this->exam_url;
		// 统一回调地址
		$ele_url = substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'], '/')-1);
		$this->notify_url = 'https://'.$_SERVER['HTTP_HOST'].substr($ele_url,0,strrpos($ele_url, '/')+1).'Ele/notify_url';
	}

	/**
	 * [getToken 获取token]
	 * @AuthorHTL
	 * @DateTime  2018-03-09T16:24:18+0800
	 * @return    [type]                   [description]
	 */
	private function getToken()
	{	
		$access_token = S('ele_access_token');
		if (!$access_token) {
			$param_json = json_encode(array('app_id' => $this->ele_config['app_id'], 'secret_key' => $this->ele_config['secret_key'], 'salt' => $this->salt, 'signature' => $this->getSignature()));
			$access_token = self::get_curl($param_json, $this->commen_url.$this->access_token_url);
			// {"code":"200","msg":"success","data":{"app_id":"34d16bf0-1111-1111-bece-564bca85e357","access_token":"0388ed83-1111-1111-1111-b03189d5d214","expire_time":1521451125489}}
			$access_token = json_decode($access_token, true)['data'];
			S('ele_access_token', $access_token, 24*60*60);
		}
		return $access_token;
	}

	/**
	 * [order 蜂鸟推单]
	 * @param  [array]  $data  [推单参数---详细参数参考蜂鸟API文档]
	 * @return [type] [description]
	 */
	public function order($data)
	{
		$data['data']['notify_url'] = $this->notify_url;// 回调地址
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['app_id'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$requestData = json_encode($data);
		$order_result = self::post_curl($requestData, $this->commen_url.$this->order_url);

		return $order_result;
	}

	/**
	 * [cancel_order 同步订单取消]
	 * @param  [array]  $data  [取消订单参数---详细参数参考蜂鸟API文档]
	 * @return [type] [description]
	 */
	public function cancel_order($data)
	{	
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['appid'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$cancle_result = self::post_curl($requestData, $this->commen_url.$this->cancle_url);
		return $cancle_result;
	}

	/**
	 * [query 订单查询接口]
	 * @param  [array]  $data  [查询参数---详细参数参考蜂鸟API文档]
	 * @return [type] [description]
	 */
	public function query_order($data)
	{
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['appid'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$query_result = self::post_curl($requestData, $this->commen_url.$this->query_url);
		return $query_result;
	}

	/**
	 * [complaint_order 订单投诉接口]
	 * @param  [array]  $data  [投诉参数---详细参数参考蜂鸟API文档]
	 * @return [type] [description]
	 */
	public function complaint_order($data)
	{
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['appid'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$complaint_result = self::post_curl($requestData, $this->commen_url.$this->complaint_url);
		return $complaint_result;
	}

	/**
	 * [notify_url 回调地址（自定义）----订单状态变更时会调用此接口传递状态信息（详细信息参考蜂鸟API文档）]
	 * @return [array] [description]
	 */
	public function notify_url()
	{
		$data = I('post.');
		$data = json_decode($data, true);
		$data['data'] = urldecode(json_decode($data['data'], true));
		return $data['data'];
	}

	/**
	 * [chain_store 添加门店接口]
	 * @param  [array] $data [添加参数---详细参数参考蜂鸟API文档]
	 * @return [type]       [description]
	 */
	public function chain_store($data)
	{
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['appid'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$chain_store_result = self::post_curl($requestData, $this->commen_url.$this->chain_store_url);
		return $chain_store_result;
	}

	/**
	 * [query_chain_store 查询门店接口]
	 * @param  [array] $data [查询参数---详细参数参考蜂鸟API文档]
	 * @return [type]       [description]
	 */
	public function query_chain_store($data)
	{
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['appid'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$query_chain_store_result = self::post_curl($requestData, $this->commen_url.$this->query_chain_store_url);
		return $query_chain_store_result;
	}

	/**
	 * [update_chain_store 更新门店接口]
	 * @param  [array] $data [更新参数---详细参数参考蜂鸟API文档]
	 * @return [type]       [description]
	 */
	public function update_chain_store($data)
	{
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['appid'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$update_chain_store_result = self::post_curl($requestData, $this->commen_url.$this->update_chain_store_url);
		return $update_chain_store_result;
	}

	/**
	 * [query_delivery 查询配送服务接口]
	 * @param  [array] $data [查询参数---详细参数参考蜂鸟API文档]
	 * @return [type]       [description]
	 */
	public function query_delivery($data)
	{
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['appid'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$query_delivery_result = self::post_curl($requestData, $this->commen_url.$this->query_delivery_url);
		return $query_delivery_result;
	}

	/**
	 * [query_delivery 查询骑手位置接口]
	 * @param  [array] $data [查询参数---详细参数参考蜂鸟API文档]
	 * @return [type]       [description]
	 */
	public function query_carrier($data)
	{
		$data['data'] = urlencode(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
		$data['app_id'] = $this->ele_config['appid'];
		$data['salt'] = $this->salt;
		$data['signature'] = $this->getSignature($data['data']);// 获取签名
		$query_carrier_result = self::post_curl($requestData, $this->commen_url.$this->query_carrier_url);
		return $query_carrier_result;
	}

	/**
	 * [getSignature 获取参数签名]
	 * @AuthorHTL
	 * @DateTime  2018-03-09T16:52:18+0800
	 * @param     $urlencodeData		   [UTF8]
	 * @return    [type]                   [description]
	 */
	private function getSignature($urlencodeData)
	{
		$signature = md5('app_id='.$this->ele_config['app_id'].'&access_token='.$this->getToken().'&data='.$urlencodeData.'&salt='.$this->salt);
		return $signature;
	}

	    /**
     * [get_curl description]
     * @param  [type] $json   [传递的数据]
     * @param  [type] $url    [访问的接口地址]
     * @param  [type] $second [超时时间]
     * @return [type]         [正常返回结果错误返回false]
     */
    public static function get_curl($json,$url,$second=30)
    {
        $type = 'get';
        $arr = json_decode($json, true);

        //拼接字符串
        $url .= '?';
        foreach ($arr as $key => $value) {
            $url .= '&'.$key.'='.$value;
        }
        // dump($url);die;
        //执行并返回数据
        $ch = self::curl('', $url,$second,$type);
        $ret = curl_exec($ch);
        if ($ret) {
            curl_close($ch);
            return $ret;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return FALSE;
        }
    }

    /**
     * POST方式
     * @param  [type]  $json   [传递的数据]
     * @param  [type]  $url    [访问的接口地址]
     * @param  integer $second [超时时间]
     * @return [type]          [正常返回结果错误返回false]
     */
    public static function post_curl($json,$url,$second=30)
    {
        //执行并返回数据
        $ch = self::curl($json,$url,$second);
        $ret = curl_exec($ch);
        if ($ret) {
            curl_close($ch);
            return $ret;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return FALSE;
        }
    }

    /**
     * curl
     * @param  string  $json   [传递的数据]
     * @param  [type]  $url    [访问的接口地址]
     * @param  integer $second [超时时间]
     * @param  string  $type   [调用类型-post/get]
     * @return [type]          [curl权柄]
     */
    public static function curl($json='',$url,$second=30,$type='post')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置超时
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, array('Content-Type' => 'application/json'));
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        if ($type==='post') {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        }

        return $ch;
    }
}