<?php
/**
 * 京东到家订单管理
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Common\Vendor\Threeorder;
class Jddj extends \Common\Vendor\Threeorder{
    private $config=array(
        'appkey'=>'34210bc3955e4d34af212b7bb604f57e',
        'appsecret'=>'d85d31e1872641d3bfa2b45cb13158a7',
    );
    private $is_sandbox= true;//是否为测试
    private $connectUrl="https://openo2o.jd.com/djapi";//平台的正式接口地址;
    public function __construct($config=array()) {
        if($config){
            $this->config=array_merge($this->config,$config);
        }
        if( $this->is_sandbox){
             $this->connectUrl="https://openo2o.jd.com/mockapi";//平台的测试接口地址;
        }
        $this->class_name='jddj';
    }
    public function setConfig($venderId=''){
        if(is_array($venderId)){
            $this->config=array_merge($this->config,$venderId);
        }else{
            $config=$this->orderconfig($venderId);
            $this->config=array_merge($this->config,$config);
        }
    }
    //授权网址
    public function get_auth_url(){return false;}
    //调取商家信息
    public function getshopinfo(){
        $return=array('status'=>0,'info'=>'');
        $param=array(
           'pageNo'=>"1",
           'pageSize'=>"10",
        );
        $path='/privilege/searchUser';
        $result=$this->execute($path,$param);
        if($result['code']==0 && $result['data']['result']){
            foreach($result['data']['result'] as $v){
                if($v['orgCode']==$this->config['venderId']){
                    $v['shopname']=$v['extFields']['orgName'];
                    $return['info']=$v;
                }
            }
            if($return['info']){
                $return['status']=1;
            }else{
                $return['info']='没有获取到商家信息';
            }
        }else{
            $return['info']=$result['msg'];
        }
        return $return;
    }
    /**
     * 订单已送达
     * @param $request array (ordersn =>订单号 operator 操作人姓名)
     */
    public function orderend($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        if(empty($request['operator'])){$return['info']='请填写操作人姓名';return $return;}
        $param=array(
           'orderId'=>$request['ordersn'],
           'operPin'=>$request['operator'],
           'operTime'=>time_format(NOW_TIME),
        );
        $path='/ocs/deliveryEndOrder';
        $result=$this->execute($path,$param);
        $return['info']=$result['msg'];
        if($result['code']==0 && $result['data']['result']){
            $return['info']=$result['data']['result'];
            $return['status']=1;
        }
        return $return;
    }
    /**
     * 订单第三方配送转商家自送
     * @param $request array (ordersn =>订单号 operator 操作人姓名)
     */
    public function orderdeliverytoself($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        if(empty($request['operator'])){$return['info']='请填写操作人姓名';return $return;}
        $param=array(
           'orderId'=>$request['ordersn'],
           'updatePin'=>$request['operator'],
        );
        $path='/order/modifySellerDelivery';
        $result=$this->execute($path,$param);
        $return['info']=$result['msg'];
        if($result['code']==0 && $result['data']['code']==0){
            $return['info']=$result['data']['msg'];
            $return['status']=1;
        }
        return $return;
    }
    /**
     * 商家订单发货
     * @param $request array (ordersn =>订单号 status=>2第三方 1众包 0自有配送 operator 操作人姓名)
     */
    public function orderdelivery($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        if(empty($request['operator'])){$return['info']='请填写操作人姓名';return $return;}
        $param=array(
           'orderId'=>$request['ordersn'],
           'operator'=>$request['operator'],
        );
        if($request['status']==1){
            $path='/bm/open/api/order/OrderJDZBDelivery';//众包
        }else if($request['status']==2){
            $path='/bm/open/api/order/OrderDDTCDelivery';//达达同城配送
        }else{
            $path='/bm/open/api/order/OrderSerllerDelivery';//自有配送
        }        
        $result=$this->execute($path,$param);
        $return['info']=$result['msg'];
        if($result['code']==0 && $result['data']['code']==0){
            $return['info']=$result['data']['msg'];
            $return['status']=1;
        }
        return $return;
    }
    /**
     * 确认退款
     * @param $request array (ordersn =>订单号 operator 操作人姓名 reason 确认退款详情)
     */
    public function orderrefund($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        $param=array(
           'orderId'=>$request['ordersn'],
           'operateTime'=>time_format(NOW_TIME),
        );
        $path='/order/confirmReceiveGoods';
        $result=$this->execute($path,$param);
        $return['info']=$result['msg'];
        if($result['code']==0 && $result['data']['code']==0){
            $return['info']=$result['data']['msg'];
            $return['status']=1;
        }
        return $return;
    }
    /**
     * 	商家审核用户取消申请接口
     * @param $request array (ordersn =>订单号 status=> 1接单 0 不接单 operator 操作人姓名 remark 备注)
     */
    public function orderCancelConfirm($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        if(empty($request['operator'])){$return['info']='请填写操作人姓名';return $return;}
        $isAgreed=$request['status']?true:false;
        if(empty($request['remark']))$request['remark']=$request['status']?'同意':'驳回';
        if($isAgreed)$this->querymoney($request);
        $param=array(
           'orderId'=>$request['ordersn'],
           'isAgreed'=>$isAgreed,
           'operator'=>$request['operator'],
           'remark'=>$request['remark'],
        );
        $path='/ocs/orderCancelOperate';
        $result=$this->execute($path,$param);
        $return['info']=$result['msg'];
        if($result['code']==0 && $result['data']['code']==0){
            $return['info']=$result['data']['msg'];
            $return['status']=1;
        }
        return $return;
    }
    /**
     * 确认接单/不接单
     * @param $request array (ordersn =>订单号 status=> 1接单 0 不接单 operator 操作人姓名)
     */
    public function orderconfirm($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        if(empty($request['operator'])){$return['info']='请填写操作人姓名';return $return;}
        $isAgreed=$request['status']?true:false;
        if($isAgreed)$this->querymoney($request);
        $param=array(
           'orderId'=>$request['ordersn'],
           'isAgreed'=>$isAgreed,
           'operator'=>$request['operator'],
        );
        $path='/ocs/orderAcceptOperate';
        $result=$this->execute($path,$param);
        $return['info']=$result['msg'];
        if($result['code']==0 && $result['data']['code']==0){
            $return['info']=$result['data']['msg'];
            $return['status']=1;
        }
        return $return;
    }
    /**
     * 新版订单金额拆分接口
     * @param $request array (ordersn =>订单号)
     */
    public function querymoney($request){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        $param=array(
           'orderId'=>$request['ordersn'],
        );
        $path='/oassBussService/queryOassBussMoney';
        $result=$this->execute($path,$param);
        $return['info']=$result['msg'];
        if($result['code']==0 && $result['data']['code']==0){
            $return['info']=$result['data']['msg'];
            $return['status']=1;
        }
        return $return;
    }
    /**
     * 订单列表
     * @param $request array (ordersn =>订单号)
     */
    public function orderlist($request=''){
        $return=array('status'=>0,'info'=>'');
        $param=array(
           'pageNo'=>"1",
           'pageSize'=>"10",
           'businessType_list'=>array(),
        );
        if($request['ordersn']){
            $param['orderId']=$request['ordersn'];
        }
        $path='/order/es/query';
        $result=$this->execute($path,$param);
        if($result['code']==0 && $result['data']['result']){
            if($result['data']['result']['resultList'])$return['info']=$result['data']['result'];
            if($return['info']){
                $return['status']=1;
            }else{
                $return['info']='没有获取到商家信息';
            }
        }else{
            $return['info']=$result['msg'];
        }
        $return['token']=$this->config['token'];
        return $return;
    }
    /**
     * 查看订单详情
     * @param $orderNo 订单号
     */
    public function orderdetail($orderNo){
        $return=array('status'=>0,'info'=>'');
        if(empty($orderNo)){$return['info']='请填写订单号';return $return;}
        $param=array(
           'orderNo'=>$orderNo,
        );
        $path='/orderTrace/getByOrderNoForOaos';
        $result=$this->execute($path,$param);
        if($result['code']==0 && $result['data']['orderTrackList']){
            if($result['data']['orderTrackList']){
                if(!is_array($result['data']['orderTrackList']))$result['data']['orderTrackList']=json_decode($result['data']['orderTrackList'],1);
                $return['info']=$result['data']['orderTrackList'];
            }
            if($return['info']){
                $return['status']=1;
            }else{
                $return['info']='没有获取到商家信息';
            }
        }else{
            $return['info']=$result['msg'];
        }
        return $return;
    }
    /**
     * 响应回调入口文件
     */
    public function notify($postdata=''){
        if(empty($postdata))$postdata=I('post.');
        $get=I('get.');
        $request=$this->format_param($postdata);
        $log=var_export($request,1);
        $log.=var_export($get,1);
        //file_put_contents('uploads/'.$this->class_name.$get['djsw'].NOW_TIME.'.txt',$log);
        
        if($get['djsw']){//订单状态回调
           return $this->change_order_status($get['djsw'],$request);
        }        
        $this->saveconfig($request);
        echo 'success';
    }
    /**
     * 订单自提码核验接口
     * @param $request array (ordersn =>订单号 code=> 自提码 operator 操作人姓名)
     */
    public function checkcode($request){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        if(empty($request['code'])){$return['info']='自提码';return $return;}
        if(empty($request['operator'])){$return['info']='请填写操作人姓名';return $return;}
        $isAgreed=$request['status']?true:false;
        if($isAgreed)$this->querymoney($request);
        $param=array(
           'orderId'=>$request['ordersn'],
           'selfPickCode'=>$request['code'],
           'operPin'=>$request['operator'],
        );
        $path='/ocs/checkSelfPickCode';
        $result=$this->execute($path,$param);
        $return['info']=$result['msg'];
        if($result['code']==0 && $result['data']['code']==0){
            $return['info']=$result['data']['msg'];
            $return['status']=1;
        }
        return $return;
    } 
    /**
     * 返回code
     */
    private function change_order_status($type,$request){
        if(empty($type))return false;
        $return=array('code'=>'0','msg'=>'success','data'=>'');        
        $status=array(
            'newOrder'=>'创建新订单消息',
            'orderAdjust'=>'订单调整消息',
            'applyCancelOrder'=>'用户取消申请消息',
            'orderWaitOutStore'=>'订单等待出库消息',
            'deliveryOrder'=>'订单开始配送消息',
            'pickFinishOrder'=>'订单拣货完成消息',
            'endOrderFinance'=>'订单金额拆分完成消息',
            'finishOrder'=>'订单妥投消息',
            'lockOrder'=>'订单锁定消息',
            'unlockOrder'=>'订单解锁消息',
            'userCancelOrder'=>'用户取消消息',
            'pushDeliveryStatus'=>'运单状态消息',
            'orderInfoChange'=>'订单信息变更消息',
            'orderAddTips'=>'订单商家小费消息',
            'orderAccounting'=>'订单应结消息',
            'deliveryCarrierModify'=>'订单转自送消息',
        );
        if(!array_key_exists($type,$status)){$return['code']='10018';$return['msg']=$this->errcode($return['code']);$this->ajaxReturn($return);}
        $param=$request;
        $param['jd_param_json']=json_encode($param['jd_param_json']);
        if(in_array($type,array('applyCancelOrder','pushDeliveryStatus')))$param['jd_param_json']=urlencode($param['jd_param_json']);        
        if(!in_array($type,array('applyCancelOrder','pushDeliveryStatus')) && !$this->verifySign($param)){$return['code']='10014';$return['msg']=$this->errcode($return['code']);$this->ajaxReturn($return);}
        
        
        $param_json=$request['jd_param_json'];
        $orderid=$param_json['billId']?$param_json['billId']:$param_json['orderId'];
        if($param['token']){
            $taken=array('token'=>$param['token']);
            $this->setConfig($taken); 
        }
        
        if(strlen($param_json['statusId'])>2){
            $order_status='';$statusId=intval($param_json['statusId']);
            //('20010'=>'锁定','20020'=>'订单取消','20030'=>'订单取消申请','20040'=>'超时未支付系统取消','20050'=>'订单解锁','20060'=>'系统撤销订单','20050'=>'暂停','31000'=>'等待付款','31020'=>'已付款','41000'=>'待处理','32000'=>'等待出库','33040'=>'配送中','33060'=>'已妥投','34000'=>'京东已收款','90000'=>'订单完成');
        //待接单＝1 待取货＝2 配送中＝3 已完成＝4 已取消＝5 已过期＝7 申请取消==6
            switch($statusId){
                case 20010:$order_status=7; break;
                case 20020:$order_status=6; break;
                case 20030:$order_status=6; break;
                case 20040:$order_status=5; break;
                case 20050:$order_status=1; break;
                case 20060:$order_status=5; break;
                case 31000:$order_status=1; break;
                case 31020:$order_status=1; break;
                case 41000:$order_status=1; break;
                case 32000:$order_status=2; break;
                case 33040:$order_status=3; break;
                case 33060:$order_status=4; break;
                case 34000:$order_status=4; break;
                case 90000:$order_status=4; break;
            }
        }
        $mod=M('ThreeOrder');
        $map=array();
        $map['ordersn']=$orderid;
        $check=$mod->where($map)->count('id');
        if(empty($check)){
            $adddata=array();
            $adddata['ordersn']=$orderid;
            $adddata['code']=$this->class_name;
            $adddata['addtime']=$adddata['updatetime']=NOW_TIME;
            $adddata['delivery_status']=2;

            $order_sn=array('ordersn'=>$orderid); 
            $result=$this->orderlist($order_sn); 
            if($result['status']==1){
                $result['info']=$this->format_param($result['info']);
                $order_info=$result['info']['resultList'][0];

                $adddata['consignee']=$order_info['buyerFullName'];
                $adddata['mobile']=$order_info['buyerMobile'];
                $adddata['address']=$order_info['buyerFullAddress'];
                $adddata['seller_id']=$order_info['orgCode'];
                $this->setConfig($order_info['orgCode']);
                $adddata['xpoint']=$order_info['buyerLng'];
                $adddata['ypoint']=$order_info['buyerLat'];
                $adddata['goods_amount']=$order_info['orderTotalMoney']/100;
                $adddata['goods_allmoney']=$order_info['orderTotalMoney']/100;
                $adddata['order_money']=$order_info['orderBuyerPayableMoney']/100;
                $adddata['order_amount']=$order_info['orderBuyerPayableMoney']/100;
                $adddata['delivery_fee']=$order_info['orderReceivableFreight']/100;
                $adddata['lunch_box_price']=$order_info['packagingMoney']/100;
                if($order_info['product']){
                    $goods_info=array();
                    foreach ($order_info['product'] as $key => $value) {
                        $total+=$value['total'];  
                        $goods_info[$key]['goodssn']=$value['skuId'];
                        $goods_info[$key]['goods_name']=$value['skuName'];  
                        $goods_info[$key]['goods_number']=$value['skuCount']; 
                        $goods_info[$key]['count']=$value['skuCount'];
                        $goods_info[$key]['shop_price']=$value['skuJdPrice']/100; 
                        $goods_info[$key]['org_parce']=($value['skuCount']*$value['skuJdPrice'])/100;              
                    }                    
                }
                if($goods_info)$adddata['goods_info']=serialize($goods_info);
                if($info['orderInvoice'])$adddata['invoice_info']=serialize($order_info['orderInvoice']);
                if($order_info['orderStartTime'])$adddata['creattime']=strtotime($order_info['orderStartTime']);
            }
            $adddata['shop_id']=$this->config['shop_id'];
            $adddata['invoice_info']=serialize($param);
            $adddata['temp']=$param['token'];
            if($order_status)$adddata['order_status']=$order_status;
            $mod->add($adddata);
            $map=array();
            $map['order_status']=array('elt',2);
            $map['shop_id']=$this->config['shop_id'];
            $count=M('ThreeOrder')->where($map)->count();
            //极光推送（app/pad）
            $content="您有京东到家新订单请尽快处理";
            $paramdata=array('type'=>99,'txt'=>$count);
            $ids=getpushids(3,$this->config['shop_id']);
            if(!empty($ids[1]))$result = pushSend($ids[1],$content,'app',1,$paramdata);
            if(!empty($ids[2]))$result = pushSend($ids[2],$content,'app',2,$paramdata);   
        }
        $timestamp=empty($param_json['timestamp'])?NOW_TIME:strtotime($param_json['timestamp']);
        $savedata=array();
        switch($type){
            case 'newOrder':break;
            case 'orderAdjust':break;
            case 'applyCancelOrder':
            $savedata['order_canceltime']=$timestamp;
            $savedata['delivery_mark']=$param_json['remark'];
            break;
            case 'orderWaitOutStore':break;
            case 'deliveryOrder':            
            $savedata['order_deliverytime']=$timestamp;
            break;
            case 'pickFinishOrder':break;
            case 'finishOrder':
            $savedata['order_canceltime']=$timestamp;
            break;
            case 'lockOrder':break;
            case 'unlockOrder':break;
            case 'userCancelOrder':
            $savedata['order_canceltime']=$timestamp;
            break;
            case 'pushDeliveryStatus':
            
            $savedata['delivery_name']=$param_json['deliveryManName'];
            $savedata['delivery_mobile']=$param_json['deliveryManPhone'];
            $savedata['delivery_shop']=$param_json['deliveryCarrierName'];
            if($param_json['deliveryCarrierNo'])$savedata['delivery_shop'].='('.$param_json['deliveryCarrierNo'].')';
            $savedata['delivery_mark']=$param_json['remark'];
            if($param_json['failType'])$savedata['delivery_mark'].='('.$$param_json['failType'].')';
            $savedata['delivery_status']=$param_json['deliveryStatus'];            
            break;
            case 'orderInfoChange':break;
            case 'orderAddTips':break;
            case 'orderAccounting':break;
            case 'deliveryCarrierModify':
            $savedata['type']=0;
            break;
        }
        if($order_status)$savedata['order_status']=$order_status;
        $savedata['updatetime']=NOW_TIME;       
        $mod->where($map)->save($savedata);
        $id=idtoname($orderid,'ThreeOrder','id','ordersn',false);
        D('Pad/ThreeOrder')->change_goods_num($id);
        $this->ajaxReturn($return);
    }
    private function errcode($code='0'){
        $codearr=array('0'=>'操作成功',
                    '-1'=>'操作失败',
                    '-10000'=>'业务重试',
                    '10005'=>'必填项参数未填',
                    '10013'=>'无效Token令牌',
                    '10014'=>'无效Sign签名',
                    '10015'=>'API参数异常',
                    '10018'=>'不存在的方法名'
        );
        return $codearr[$code];
    }
    public function orderstatus($code='0'){
        $codearr=array('20010'=>'锁定','20020'=>'订单取消','20030'=>'订单取消申请','20040'=>'超时未支付系统取消','20050'=>'订单解锁','20060'=>'系统撤销订单','20050'=>'暂停','31000'=>'等待付款','31020'=>'已付款','41000'=>'待处理','32000'=>'等待出库','33040'=>'配送中','33060'=>'已妥投','34000'=>'京东已收款','90000'=>'订单完成');
        return $codearr[$code];
    }
    //请求服务端
    public function execute($path,$request) {
		$apiParams = array();		
        $requestjson=!empty($request)?json_encode($request):'{}';
		$apiParams['jd_param_json'] = $requestjson;//应用级参数
		//系统级别参数
		$apiParams['token'] 	  = $this->config['token'];
		$apiParams['app_key']     = $this->config['appkey'];
		$apiParams['timestamp']   = date('Y-m-d H:i:s');
		$apiParams['v']           = "2.0";
		$apiParams['format']      = 'json';
		$apiParams["sign"] 		  = $this->generateSign($apiParams);
		$requestUrl = $this->connectUrl.$path;
		$resp = curlget($requestUrl,$apiParams,'POST');
        $result= json_decode($resp, true);
        if($result['data'] && !is_array($result['data']))$result['data']= json_decode($result['data'], true);
        return $result;
	}
    //生成签名
    protected function generateSign($params){
        $stringToBeSigned = $this->paramsToString($params);
		return strtoupper(md5($stringToBeSigned));
	}
    //验签
	protected function verifySign($params){
        $stringToBeSigned = $this->paramsToString($params);
        $sign = $params["sign"];
        if(!empty($sign)){return $sign == strtoupper(md5($stringToBeSigned));}
        return false;
	}
    //组合待签名字符
    protected function paramsToString($params){
		ksort($params);
		$sortedString = $this->config['appsecret'];
		foreach ($params as $k => $v){
            $v = (string)$v;
			if("sign" !== $k){$sortedString .= "$k$v";}
		}
		$sortedString .= $this->config['appsecret'];
        return $sortedString;
    }
    //保存配置文件
	private function saveconfig($param){
		if(empty($param) || (empty($param['token']['venderId']) && empty($param['code']['venderId'])))return false;
        $venderId=$param['token']['venderId']?$param['token']['venderId']:$param['code']['venderId'];
        if($param['token'] && $param['code'])$value=array_merge($param['token'],$param['code']);
        else $value=$param['token']?$param['token']:$param['code'];
        $appid=C('appid');
        if($appid && $venderId){
            $base=array($appid=>$venderId);
            $this->orderconfig('base',$base);
        }
        return $this->orderconfig($venderId,$value);
	}
}
?>