<?php
namespace wstshop\admin\model;
use think\Db;
use think\Loader;
/**
 * ============================================================================
 * WSTShop网上商店
 * 版权所有 2016-2066 广州商淘信息科技有限公司，并保留所有权利。
 * 官网地址:http://www.wstshop.net
 * 交流社区:http://bbs.shangtao.net
 * 联系QQ:153289970
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 订单业务处理类
 */
class Orders extends Base{
	/**
	 * 管理员取消订单
	 */
	public function cancel(){
		$orderId = (int)input('post.id');
		hook('beforeCancelOrder',['orderId'=>$orderId]);
		$reason = (int)input('post.reason');
		$content = input('post.content');
		$order = $this->where(['orderId'=>$orderId,'orderStatus'=>['in',[-2,0]]])
		              ->field('userId,orderId,orderNo,realTotalMoney,orderStatus,payType,isPay,useScore')->find();
		$reasonData = WSTDatas('ORDER_CANCEL',$reason);
		if(empty($reasonData))return WSTReturn("无效的取消原因");
		if(!empty($order)){
			Db::startTrans();
		    try{
				$data = ['orderStatus'=>-1,'cancelReason'=>$reason];
				//如果是货到付款的话，则把实付金额设置为0
				if($order['payType']==0 || ($order['orderStatus']==-2 && $order['payType']==1))$data['realTotalMoney'] = 0;
			    $result = $this->where('orderId',$order['orderId'])->update($data);
				if(false != $result){
					$userId = $order['userId'];
                   
                    //未付款状态则直接退回积分
                    if($order['orderStatus'] == -2 && $order['payType']==1 && $order['useScore']>0){
                    	$score = [];
						$score['userId'] = $userId;
						$score['score'] = $order['useScore'];
						$score['dataSrc'] = 1;
						$score['dataId'] = $orderId;
						$score['dataRemarks'] = "取消交易订单【".$order['orderNo']."】，退回积分".$order['useScore']."个";
						$score['scoreType'] = 1;
						model('common/UserScores')->add($score);
                    }
                    //货到付款取消订单
                    if($order['orderStatus'] == 0 && $order['payType']==0 && $order['useScore']>0){
                    	$score = [];
						$score['userId'] = $userId;
						$score['score'] = $order['useScore'];
						$score['dataSrc'] = 1;
						$score['dataId'] = $orderId;
						$score['dataRemarks'] = "取消交易订单【".$order['orderNo']."】，退回积分".$order['useScore']."个";
						$score['scoreType'] = 1;
						model('common/UserScores')->add($score);
                    }
					//返还商品库存
					$goods = Db::name('order_goods')->alias('og')->join('__GOODS__ g','og.goodsId=g.goodsId','inner')
					           ->where('orderId',$orderId)->field('og.*,g.isSpec')->select();
					foreach ($goods as $key => $v){
						//修改库存
						if($v['isSpec']>0){
					        Db::name('goods_specs')->where('id',$v['goodsSpecId'])->setInc('specStock',$v['goodsNum']);
						}
						Db::name('goods')->where('goodsId',$v['goodsId'])->setInc('goodsStock',$v['goodsNum']);
					}
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = -1;
					$logOrder['logContent'] = "管理员取消订单，取消原因：".$reasonData['dataName'];

					if($reason==10000)$logOrder['logContent'] .= ":$content";

					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_orders')->insert($logOrder);
					//如果是在线支付并且已经支付了的订单还要生成退款单
					if($order['orderStatus'] == 0 && $order['payType']==1 && $order['isPay']==1){
						$data = [];
					    $data['orderId'] = $orderId;	
		                $data['refundTo'] = 0;
		                $data['refundReson'] = 10000;
		                $data['refundOtherReson'] = '【管理员取消订单】：'.$reasonData['dataName'];
		                if($reason==10000)$data['refundOtherReson'] = $content;
		                $data['backMoney'] = $order['realTotalMoney'];
		                $data['backScore'] = $order['useScore'];
		                $data['createTime'] = date('Y-m-d H:i:s');
		                $data['refundRemark'] = $reasonData['dataName'].(($reason==10000)?"-".$data['refundOtherReson']:'');
		                $data['refundStatus'] = 0;
		                Db::name('order_refunds')->insert($data);
	                }
					Db::commit();
					return WSTReturn('订单取消成功',1);
				}
			}catch (\Exception $e) {
		        Db::rollback();
	            return WSTReturn('操作失败',-1);
	        }
		}
		return WSTReturn('操作失败，请检查订单状态是否已改变');
	}
	/**
	 * 获取订单
	 */
	public function pageQuery($orderStatus,$payType = 0){
		$orderNo = input('orderNo');
		$userId = (int)input('userId');
		$payType = $payType>0?$payType:(int)input('payType',-1);
		$deliverType = (int)input('deliverType',-1);
		$sort = input('sort');
		$where = ['o.dataFlag'=>1];
		if($orderStatus!=-1000){
			if(is_array($orderStatus)){
				$where['orderStatus'] = ['in',$orderStatus];
			}else{
				$where['orderStatus'] = $orderStatus;
			}
		}else{
			$orderStatus = input('post.orderStatus');
			if(isset($orderStatus) && $orderStatus!=-1000){
				$where['orderStatus'] = $orderStatus;
			}
		}
		if($orderNo!=''){
			$where['orderNo'] = ['like',"%$orderNo%"];
		}
		if($userId>0){
			$where['o.userId'] = $userId;
		}
		if($payType > -1){
			$where['payType'] =  $payType;
		}
		if($deliverType > -1){
			$where['deliverType'] =  $deliverType;
		}
		$order = 'o.createTime desc';
		if($sort){
			$sort =  str_replace('.',' ',$sort);
			$order = $sort;
		}
		$page = $this->alias('o')->where($where)
			  ->join("__USERS__ u",'u.userId=o.userId','left')
		      ->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId and refundStatus=0','left')
		      ->field('u.loginName,o.orderRemarks,o.noticeDeliver,o.orderId,orderNo,goodsMoney,totalMoney,realTotalMoney,orderStatus,deliverType,deliverMoney,isAppraise
		              ,payType,payFrom,userAddress,orderStatus,useScore,isPay,isAppraise,o.userName,orderSrc,o.createTime,orf.id refundId,o.isRefund')
			  ->order($order)
			  ->paginate(input('limit/d'))->toArray();
	    if(count($page['Rows'])>0){ 
	    	 foreach ($page['Rows'] as $key => $v){
	    	 	 $allowDel = true;
		    	 if($v['orderStatus']!=2){
		    	 	//如果是货到付款的，只要有涉及到积分且没有退款的都不允许删除
		    	 	if($v['isRefund']==0 && $v['payType']==0 && $v['useScore']>0)$allowDel = false;
		    	 	//如果是在线支付的，只要没有退款且涉及到（积分或者已经支付了的）都不允许删除
		    	 	if($v['isRefund']==0 && ($v['useScore']>0 || $v['isPay']==1))$allowDel = false;
	    	 	 }
	    	 	 $page['Rows'][$key]['userName'] = "【".$v['loginName']."】".$v['userName'];
	    	 	 $page['Rows'][$key]['allowDel'] = $allowDel;
	    	 	 $page['Rows'][$key]['payTypeName'] = WSTLangPayType($v['payType']);
	    	 	 $page['Rows'][$key]['deliverTypeName'] = WSTLangDeliverType($v['deliverType']==1);
	    	 	 $page['Rows'][$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
	    	 }
	    }
	    return $page;
	}	
    /**
	 * 获取用户退款订单列表
	 */
	public function refundPageQuery(){
		$where = ['o.dataFlag'=>1];
		$where['orderStatus'] = ['in',[-1,-4]];
		$where['o.payType'] = 1;
		$orderNo = input('orderNo');
		$shopName = input('shopName');
		$deliverType = (int)input('deliverType',-1);
		$areaId1 = (int)input('areaId1');
		$areaId2 = (int)input('areaId2');
		$areaId3 = (int)input('areaId3');
		$isRefund = (int)input('isRefund',-1);
		if($orderNo!='')$where['orderNo'] = ['like','%'.$orderNo.'%'];
		if($shopName!='')$where['shopName|shopSn'] = ['like','%'.$shopName.'%'];
		if($areaId1>0)$where['s.areaId1'] = $areaId1;
		if($areaId2>0)$where['s.areaId2'] = $areaId2;
		if($areaId3>0)$where['s.areaId3'] = $areaId3;
		if($deliverType!=-1)$where['o.deliverType'] = $deliverType;
		if($isRefund!=-1)$where['o.isRefund'] = $isRefund;
		$page = $this->alias('o')
			 ->join("__USERS__ u",'u.userId=o.userId','left')
			 ->join('__SHOPS__ s','o.shopId=s.shopId','left')
		     ->join('__ORDER_REFUNDS__ orf ','o.orderId=orf.orderId','left') 
		     ->where($where)
		     ->field('u.loginName,o.orderId,o.orderNo,s.shopName,s.shopId,s.shopQQ,s.shopWangWang,o.goodsMoney,o.totalMoney,o.realTotalMoney,
		              o.orderStatus,o.userName,o.deliverType,payType,payFrom,o.orderStatus,orderSrc,orf.refundRemark,isRefund,o.createTime')
			 ->order('o.createTime', 'desc')
			 ->paginate(input('limit/d'))->toArray();
	    if(count($page['Rows'])>0){
	    	 foreach ($page['Rows'] as $key => $v){
	    	 	 $page['Rows'][$key]['userName'] = "【".$v['loginName']."】".$v['userName'];
	    	 	 $page['Rows'][$key]['payType'] = WSTLangPayType($v['payType']);
	    	 	 $page['Rows'][$key]['deliverType'] = WSTLangDeliverType($v['deliverType']==1);
	    	 	 $page['Rows'][$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
	    	 }
	    }
	    return $page;
	}
	/**
	 * 获取退款资料
	 */
	public function getInfoByRefund(){
		return $this->where(['orderId'=>(int)input('get.id'),'isRefund'=>0,'orderStatus'=>['in',[-1,-4]]])
		         ->field('orderNo,orderId,goodsMoney,totalMoney,realTotalMoney,deliverMoney,payType,payFrom,tradeNo')
		         ->find();
	}
	
	
	/**
	 * 获取订单详情
	 */
	public function getByView($orderId){
		$orders = $this->alias('o')->join('__EXPRESS__ e','o.expressId=e.expressId','left')
		               ->join('__ORDER_REFUNDS__ orf ','o.orderId=orf.orderId','left')
		               ->where('o.dataFlag=1 and o.orderId='.$orderId)
		               ->field('o.*,e.expressName,orf.refundRemark,orf.refundTime')->find();
		if(empty($orders))return WSTReturn("无效的订单信息");
		$orders = $orders->toArray();
		//获取订单信息
		$orders['log'] = Db::name('log_orders')->where('orderId',$orderId)->order('logId asc')->select();
		//获取订单商品
		$orders['goods'] = Db::name('order_goods')->where('orderId',$orderId)->order('id asc')->select();
		//如果是虚拟商品
		if($orders['orderType']==1){
			foreach ($orders['goods'] as $key => $v) {
				$orders['goods'][$key]['extraJson'] = json_decode($v['extraJson'],true);
			}
		}
		hook('beforeViewOrderDetail',['order'=>&$orders]);
		return $orders;
	}

	/**
	 * 删除订单
	 */
	public function del(){
		$id = (int)input('id');
		$orders = $this->get($id);
		$allowDel = true;
		if($orders->orderStatus!=2){
		    //如果是货到付款的，只要有涉及到积分且没有退款的都不允许删除
		    if($orders->isRefund==0 && $orders->payType==0 && $orders->useScore>0)$allowDel = false;
		    //如果是在线支付的，只要没有退款且涉及到（积分或者已经支付了的）都不允许删除
		    if($orders->isRefund==0 && ($orders->useScore>0 || $orders->isPay==1))$allowDel = false;
	    }
	    if(!$allowDel)return WSTReturn('不允许删除该订单');
		if(!empty($orders)){
			$orders->dataFlag = -1;
			$orders->save();
			return WSTReturn('操作成功',1);
		}
		return WSTReturn('操作失败，无效的订单ID');
	}

    /**
	 * 发货
	 */
	public function deliver(){
		$orderId = (int)input('post.id');
		$expressId = (int)input('post.expressId');
		$expressNo = input('post.expressNo');
		if($expressId>0)$expressName = Db::name('express')->where(['expressId'=>$expressId,'dataFlag'=>1])->field('expressName')->find();
		$order = $this->where(['orderId'=>$orderId,'orderStatus'=>0])->field('orderId,orderNo,userId')->find();
		if(!empty($order)){
			Db::startTrans();
		    try{
				$data = ['orderStatus'=>1,'expressId'=>$expressId,'expressNo'=>$expressNo,'deliveryTime'=>date('Y-m-d H:i:s')];
			    $result = $this->where('orderId',$order['orderId'])->update($data);
				if(false != $result){
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = 1;
					$logOrder['logContent'] = "商家已发货".(($expressNo!='')?"，快递号为：".$expressNo:"");
					$logOrder['logUserId'] = $order['userId'];
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_orders')->insert($logOrder);
					//发送一条用户信息
					$tpl = WSTMsgTemplates('ORDER_DELIVERY');
	                if($tpl['tplContent']!='' && $tpl['status']=='1'){
	                    $find = ['${ORDER_NO}','${EXPRESS_NO}'];
	                    $replace = [$order['orderNo'],($expressNo=='')?'无':$expressNo];
	                    WSTSendMsg($order['userId'],str_replace($find,$replace,$tpl['tplContent']),['from'=>1,'dataId'=>$orderId]);
	                }
	                //微信消息
		            if((int)WSTConf('CONF.wxenabled')==1){
		            	$params = [];
		            	if($expressId>0){
		            		$express = model('express')->get($expressId);
		            		$params['EXPRESS'] = $express->expressName;          
		                    $params['EXPRESS_NO'] = $expressNo;       
		            	}else{
		            		$params['EXPRESS'] = '无';
		            		$params['EXPRESS_NO'] = '无';
		            	}
		                $params['ORDER_NO'] = $order['orderNo'];  
		                
	                    WSTWxMessage(['CODE'=>'WX_ORDER_DELIVERY','userId'=>$order['userId'],'URL'=>Url('wechat/orders/index',['type'=>'waitReceive'],true,true),'params'=>$params]);
		            } 
					Db::commit();
					//发货打印小票
					hook("afterShopDeliver",['orderId'=>$order['orderId'],'uerSystem'=>[0,1],'printCatId'=>2]);
					return WSTReturn('操作成功',1);
				}
			}catch (\Exception $e) {
	            Db::rollback();
	            return WSTReturn('操作失败',-1);
	        }
		}
		return WSTReturn('操作失败，请检查订单状态是否已改变');
	}

	/**
	 * 获取订单价格
	 */
	public function getMoneyByOrder($orderId = 0){
		$orderId = ($orderId>0)?$orderId:(int)input('post.id');
		return $this->where('orderId',$orderId)->field('orderId,goodsMoney,deliverMoney,totalMoney,realTotalMoney')->find();
	}


	/**
	 * 修改订单价格
	 */
	public function editOrderMoney(){
		$orderId = input('post.id');
		$orderMoney = (float)input('post.orderMoney');
		if($orderMoney<0.01)return WSTReturn("订单价格必须大于0.01");
		Db::startTrans();
		try{

			$orders = $this->get($orderId);
			if($orders->orderStatus==-2){
				//修改订单价格前执行勾子
				hook('beforeEditOrderMoney',['orderId'=>$orderId,"orderMoney"=>$orderMoney]);
				$orders->realTotalMoney = $orderMoney;
				$orders->needPay = $orderMoney;
				$orders->payRand = array("exp","payRand+1");
				$result = $orders->save();
				if(false !== $result){
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = -2;
					$logOrder['logContent'] = "商家修改订单价格为：".$orderMoney;
					$logOrder['logUserId'] = $orders['userId'];
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_orders')->insert($logOrder);
					Db::commit();
					return WSTReturn('操作成功',1);
				}
			}	
		}catch (\Exception $e) {
		    Db::rollback();
	        return WSTReturn('操作失败',-1);
	    }
	}
	
	/**
	 * 导出订单
	 */
	public function toExport(){
		$name='订单表';
		$orderNo = input('orderNo');
		$userId = (int)input('userId');
		$type = (int)input('type',-1);
		$payType = $type>0?$type:(int)input('payType',-1);
		$deliverType = (int)input('deliverType',-1);
		$orderStatus = (int)input('orderStatus',0);
		if($orderStatus==0){
			$name='待发货订单表';
		}else if($orderStatus==-2){
			$name='待付款订单表';
		}else if($orderStatus==1){
			$name='已发货订单表';
		}else if($orderStatus==10000){
			$name='取消/拒收订单表';
		}else if($orderStatus==2){
			$name='已收货订单表';
		}
		if($orderStatus == 10000)$orderStatus = [-1,-3];
		$where = ['dataFlag'=>1];
		if($orderStatus!=-1000){
			if(is_array($orderStatus)){
				$where['o.orderStatus'] = ['in',$orderStatus];
			}else{
				$where['o.orderStatus'] = $orderStatus;
			}
		}
		if($orderNo!=''){
			$where['orderNo'] = ['like',"%$orderNo%"];
		}
		if($userId>0){
			$where['o.userId'] = $userId;
			$user = Db::name('users')->where('userId',$userId)->field('userName')->find();
			$name = $user['userName'].'的订单表';
		}
		if($payType > -1){
			$where['payType'] =  $payType;
		}
		if($deliverType > -1){
			$where['deliverType'] =  $deliverType;
		}
		$page = $this->alias('o')->where($where)
		->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId and refundStatus=0','left')
		->join('__LOG_ORDERS__ lo','lo.orderId=o.orderId and lo.orderStatus in (-1,-3) ','left')
		->field('o.orderId,orderNo,goodsMoney,totalMoney,realTotalMoney,o.orderStatus,deliverType,deliverMoney,isAppraise,lo.logContent
		              ,payType,payFrom,userAddress,isPay,isAppraise,userName,userPhone,orderRemarks,invoiceClient,orderSrc,o.receiveTime,o.deliveryTime,o.createTime,orf.id refundId,o.isMakeInvoice')
				              ->order('o.createTime', 'desc')
				              ->select();
		if(count($page)>0){
			foreach ($page as $key => $v){
				$page[$key]['payTypeName'] = WSTLangPayType($v['payType']);
				$page[$key]['deliverType'] = WSTLangDeliverType($v['deliverType']==1);
				$page[$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
				$page[$key]['isMakeInvoice'] = ($v['isMakeInvoice']==1)?'已开':'未开';
			}
		}
		Loader::import('phpexcel.PHPExcel.IOFactory');
		$objPHPExcel = new \PHPExcel();
		// 设置excel文档的属性
		$objPHPExcel->getProperties()->setCreator("WSTShop")//创建人
		->setLastModifiedBy("WSTShop")//最后修改人
		->setTitle($name)//标题
		->setSubject($name)//题目
		->setDescription($name)//描述
		->setKeywords("订单")//关键字
		->setCategory("Test result file");//种类
		
		// 开始操作excel表
		$objPHPExcel->setActiveSheetIndex(0);
		// 设置工作薄名称
		$objPHPExcel->getActiveSheet()->setTitle(iconv('gbk', 'utf-8', 'Sheet'));
		// 设置默认字体和大小
		$objPHPExcel->getDefaultStyle()->getFont()->setName(iconv('gbk', 'utf-8', ''));
		$objPHPExcel->getDefaultStyle()->getFont()->setSize(11);
		$styleArray = array(
				'font' => array(
						'bold' => true,
						'color'=>array(
								'argb' => 'ffffffff',
						)
				),
				'borders' => array (
						'outline' => array (
								'style' => \PHPExcel_Style_Border::BORDER_THIN,  //设置border样式
								'color' => array ('argb' => 'FF000000'),     //设置border颜色
						)
				)
		);
		//设置宽
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(50);
		$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(50);
		$objPHPExcel->getActiveSheet()->getStyle('A1:Q1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle('A1:Q1')->getFill()->getStartColor()->setARGB('333399');
		
		$objPHPExcel->getActiveSheet()->setCellValue('A1', '订单编号')->setCellValue('B1', '订单状态')->setCellValue('C1', '收货人')->setCellValue('D1', '收货地址')->setCellValue('E1', '联系方式')
		->setCellValue('F1', '支付方式')->setCellValue('G1', '配送方式')->setCellValue('H1', '发票状态')->setCellValue('Q1', '买家留言')->setCellValue('I1', '发票信息')->setCellValue('J1', '订单总金额')->setCellValue('K1', '运费')
		->setCellValue('L1', '实付金额')->setCellValue('M1', '下单时间')->setCellValue('N1', '发货时间')->setCellValue('O1', '收货时间')->setCellValue('P1', '取消/拒收原因');
		$objPHPExcel->getActiveSheet()->getStyle('A1:P1')->applyFromArray($styleArray);
		
		for ($row = 0; $row < count($page); $row++){
			$i = $row+2;
			$objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $page[$row]['orderNo'])->setCellValue('B'.$i, $page[$row]['status'])->setCellValue('C'.$i, $page[$row]['userName'])->setCellValue('D'.$i, $page[$row]['userAddress'])
			->setCellValue('E'.$i, $page[$row]['userPhone'])->setCellValue('F'.$i, $page[$row]['payTypeName'])->setCellValue('G'.$i, $page[$row]['deliverType'])->setCellValue('H'.$i, $page[$row]['isMakeInvoice'])->setCellValue('I'.$i, $page[$row]['invoiceClient'])
			->setCellValue('J'.$i, $page[$row]['totalMoney'])->setCellValue('K'.$i, $page[$row]['deliverMoney'])->setCellValue('L'.$i, $page[$row]['realTotalMoney'])->setCellValue('M'.$i, $page[$row]['createTime'])->setCellValue('N'.$i, $page[$row]['deliveryTime'])
			->setCellValue('O'.$i, $page[$row]['receiveTime'])->setCellValue('P'.$i, $page[$row]['logContent'])->setCellValue('Q'.$i, $page[$row]['orderRemarks']);
		}
		
		//输出EXCEL格式
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		// 从浏览器直接输出$filename
		header('Content-Type:application/csv;charset=UTF-8');
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type:application/vnd.ms-excel;");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");
		header('Content-Disposition: attachment;filename="'.$name.'.xls"');
		header("Content-Transfer-Encoding:binary");
		$objWriter->save('php://output');
	}
}
