<?php
namespace Common\Controller;

use Think\Controller;

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

/**
 * 达达配送，注：具体请求参数请参考达达开放平台-API开发文档
 */

class DadaController extends Controller
{
	private $dadaConfig = array();// 达达全局配置参数
	private $timestamp;// 默认时间戳
	private $format = 'json';// 请求格式，暂时只支持json
	private $v = '1.0';// API版本
	
	private $test_sourse_id = 73753;// 默认商户id，测试环境使用
	private $common_source_id;// 统一商户id
	public $shop_no = 11047059;// 默认门店编号，测试环境使用

	// 请求返回码
	public $errCode = 0;
	// 请求错误信息
	public $errMsg = '';
	// 请求状态
	public $errStatus = '';

	// 请求域名
	public $testUrl = 'newopen.qa.imdada.cn';// 测试域名
	public $url = 'newopen.imdada.cn';// 线上域名
	public $commonUrl;// 统一访问域名

	//请求接口
	
	/** 订单管理 */
	// 添加订单接口
	private $addOrderUrl = '/api/order/addOrder';
	// 订单重发接口
	private $reAddOrderUrl = '/api/order/reAddOrder';
	// 订单欲发布接口
	private $queryDeliverFeeUrl = '/api/order/queryDeliverFee';// 查询订单运费接口
	private $addAfterQueryUrl = '/api/order/addAfterQuery';// 查询运费后发单接口
	// 添加小费接口
	private $addTipUrl = '/api/order/addTip';
	// 订单回调接口
	public $notifyUrl;// 回调地址
	private $acceptUrl = '/api/order/accept';// 接受订单(仅在测试环境供调试使用)
	private $fetchUrl = '/api/order/fetch';// 完成取货(仅在测试环境供调试使用)
	private $finishUrl = '/api/order/finish';// 完成订单(仅在测试环境供调试使用)
	private $cancleUrl = '/api/order/cancel';// 取消订单(仅在测试环境供调试使用)
	private $expireUrl = '/api/order/expire';// 订单过期(仅在测试环境供调试使用)
	// 订单详情查询接口
	private $queryUrl = '/api/order/status/query';
	// 订单取消接口
	private $formalCancelUrl = '/api/order/formalCancel';
	// 订单取消原因接口
	private $cancelReasonsUrl = '/api/order/cancel/reasons';
	// 追加订单接口
	private $appointExistUrl = '/api/order/appoint/exist';
	// 取消追加订单接口
	private $appointCancleUrl = '/api/order/appoint/cancel';
	// 查询追加配送员接口
	private $appointListTransporterUrl = '/api/order/appoint/list/transporter';
	
	/** 商户管理 */
	//城市信息接口
	private $cityCodeListUrl = '/api/cityCode/list';
	//注册商户接口
	private $merchantAddUrl = '/merchantApi/merchant/add';
	//门店创建接口
	private $shopAddUrl = '/api/shop/add';
	//门店更新接口
	private $shopUpdateUrl = '/api/shop/update';
	//门店详情接口
	private $shopDetailUrl = '/api/shop/detail';

	/** 订单投诉 */
	// 商家投诉接口
	private $complaintDadaUrl = '/api/complaint/dada';
	// 投诉达达原因
	private $complaintReasonsUrl = '/api/complaint/reasons';
	
	/** 充值管理 */
	// 生成充值链接
	private $rechargeUrl = '/api/recharge';
	// 账户余额查询
	private $balanceQueryUrl = '/api/balance/query';

	public function __construct($business_id)
	{
		parent::__construct();

		$this->dadaConfig = M('dada_business')->where(array('admin_id' => $business_id))->field('app_key, app_secret, source_id')->find();

		if (empty($this->dadaConfig)) {
			$this->ajaxReturn(['status' => -1, 'msg' => '达达配置参数错误']);
		}

		$this->timestamp = time();
		
		// 注：正式环境需要将测试域名$this->testUrl换成正式域名$this->url
		$this->commonUrl = $this->testUrl;
		// 注：正式环境需要将测试商户id$this->test_sourse_id换成正式商户id  $this->dadaConfig['source_id']
		$this->common_source_id = $this->test_sourse_id;
	}

	/**
	 * [add_order 添加订单接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T16:39:28+0800
	 * @param     array                   $body [业务参数]
	 */
	public function addOrder($body)
	{	
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->addOrderUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [reAddOrder 订单重发接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T17:55:34+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function reAddOrder($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->reAddOrderUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [addTip 添加小费接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:20:38+0800
	 * @param     [array]                   $body [业务参数]
	 */
	public function addTip($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->addTipUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [accept 接受订单接口(仅在测试环境供调试使用)]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:22:53+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function accept($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->acceptUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [fetch 完成取货接口(仅在测试环境供调试使用)]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:24:02+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function fetch($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->fetchUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [finish 完成订单接口(仅在测试环境供调试使用)]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:25:18+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function finish($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->finishUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [cancel 取消订单接口(仅在测试环境供调试使用)]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:26:14+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function cancel($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->cancleUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [expire 订单过期接口(仅在测试环境供调试使用)]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:27:38+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function expire($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->expireUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [query 订单详情查询接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:29:09+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function query($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->queryUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [formalCancel 取消订单接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:30:55+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function formalCancel($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->formalCancelUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [cancelReasons 获取取消原因接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:32:06+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function cancelReasons($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->cancelReasonsUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [appointExist 追加订单接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:33:21+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function appointExist($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->appointExistUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [queryDeliverFee 订单预发布]
	 * @AuthorHTL
	 * @DateTime  2018-03-30T15:46:56+0800
	 * @param     [type]                   $body [description]
	 * @return    [type]                         [description]
	 */
	public function queryDeliverFee($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->queryDeliverFeeUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [addAfterQuery 查询运费后发单接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-30T15:47:23+0800
	 * @param     [type]                   $body [description]
	 */
	public function addAfterQuery($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->addAfterQueryUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [appointCancle 取消追加订单接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:35:22+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function appointCancle($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->appointCancleUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [appointListTransporter 查询追加配送员接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:37:05+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function appointListTransporter($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->appointListTransporterUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [cityCodeList 获取城市信息接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:39:53+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function cityCodeList($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->cityCodeListUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [merchantAdd 注册商户接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:42:13+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function merchantAdd($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->merchantAddUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [shopAdd 新增门店接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:43:20+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function shopAdd($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->shopAddUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [shopUpdate 编辑门店接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:44:58+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function shopUpdate($body)
	{	
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->shopUpdateUrl);
		return $this->getResponseInfo($result);
	}	

	/**
	 * [shopDetail 门店详情接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:46:10+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function shopDetail($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->shopDetailUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [complaintDada 商家投诉达达接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:47:31+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function complaintDada($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->complaintDadaUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [complaintReasons 获取商家投诉达达原因]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:49:29+0800
	 * @param     string                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	public function complaintReasons($body = '')
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->complaintReasonsUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [recharge 获取充值链接]
	 * @AuthorHTL
	 * @DateTime  2018-03-22T14:35:05+0800
	 * @param     [array]                   $body      [业务参数]
	 * @param     [type]                   $source_id [商户id]
	 * @return    [type]                              [description]
	 */
	public function recharge($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->rechargeUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [balanceQuery 查询账户余额]
	 * @AuthorHTL
	 * @DateTime  2018-03-22T14:36:38+0800
	 * @param     [type]                   $body      [description]
	 * @param     string                   $source_id [description]
	 * @return    [type]                              [description]
	 */
	public function balanceQuery($body)
	{
		$data = $this->getCommonRequestData($body);
		$result = self::post_curl(json_encode($data), $this->commonUrl.$this->balanceQueryUrl);
		return $this->getResponseInfo($result);
	}

	/**
	 * [notify_url 订单状态回调接口]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T16:00:55+0800
	 * @return    [type]                   [description]
	 */
	public function notifyUrl()
	{
		$data = file_get_contents('php://input');
		return json_decode($data, true);
	}

	/**
	 * [getResponseInfo 获取接口返回信息]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T18:02:44+0800
	 * @param     [type]                   $data [返回结果]
	 * @return    [type]                         [description]
	 */
	private function getResponseInfo($data)
	{
		$data = json_decode($data, true);
		$this->errCode = $data['code'];
		$this->errStatus = $data['status'];
		$this->errMsg = $data['msg'];
		return $data['result'];
	}

	/**
	 * [getCommonRequestData 获取统一请求参数]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T16:48:25+0800
	 * @param     array                   $body [业务参数]
	 * @return    [type]                         [description]
	 */
	private function getCommonRequestData($body = '')
	{
		$data = array(
				'app_key' => $this->dadaConfig['app_key'],
				'timestamp' => $this->timestamp,
				'signature' => $this->getSignature($body),
				'format' => $this->format,
				'v' => $this->v,
				'source_id' => $this->common_source_id,
				'body' => json_encode($body)
			);
		return $data;
	}

	/**
	 * [getSignature 获取签名]
	 * @AuthorHTL
	 * @DateTime  2018-03-21T15:17:59+0800
	 * @param     [array]                   $body [业务参数]
	 * @return    [type]                              [description]
	 */
	private function getSignature($body)
	{
		// app_key、body、format、source_id、timestamp、v
		$sigString = $this->dadaConfig['app_secret'].'app_key'.$this->dadaConfig['app_key'].'body'.json_encode($body).'format'.$this->format.'source_id'.$this->common_source_id.'timestamp'.$this->timestamp.'v'.$this->v.$this->dadaConfig['app_secret'];
		$sigString = strtoupper(MD5($sigString));
		return $sigString;
	}

    /**
     * curl
     * @param  string  $json   [传递的数据]
     * @param  [type]  $url    [访问的接口地址]
     * @param  integer $second [超时时间]
     * @param  string  $type   [调用类型-post/get]
     * @return [type]          [curl权柄]
     */
    public static function post_curl($data='',$url)
    {
        // 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 '';
    }
}