<?php
class Receiving_RecordedSingleController extends Ec_Controller_Action{
	public function preDispatch()
	{
		$this->tplDirectory = "receiving/views/recordsingle/";
		$this->serviceClass = new Service_Receiving();
		$userAuth = new Zend_Session_Namespace('userAuthorization');
		$this->warehouse_id = $userAuth->warehouseId;
		$this->user_id = $userAuth->userId;
	}
	/**
	 * @author william-fan
	 * @todo 用于录单操作
	 */
	public function recordedSingleAction(){
		$canScan = '0';
		$order_code = $this->_request->getParam('order_code','');
		$orderClass = new Service_Orders();
		$order = $orderClass->getByField($order_code, "order_code", "*");
		$message = '';
		$allowShipBase = Service_RecordSingleProcess::getBaseDhlSmCodes();
		$allowShipOneWorldExpress = Service_RecordSingleProcess::getOneWorldExpressSmCodes();
		$shiMeng = Service_RecordSingleProcess::getZheMengDhlSmCodes();

        $allowShip = array_merge($allowShipBase, $allowShipOneWorldExpress, $shiMeng );
		if(!in_array($order['sm_code'],$allowShip)){
			$message = "<p class='messageFail'>必须是".implode(',',$allowShip)."的运输方式才能录单</p>";
		}else{
		if(empty($order)){
			$message = "<p class='messageFail'>输入订单不存在</p>";
		}elseif($order['order_status']!='7'){
			$message = "<p class='messageFail'>订单不是已打包状态,不能录单</p>";
		}else{
			if ( in_array($order['sm_code'],$allowShipOneWorldExpress) || in_array($order['sm_code'],$shiMeng)) {
				$isOneWorldExpress = true;
			}
			$canScan = '1';
			$addressList=Service_OrderAddressBook::getByCondition(array('order_code'=>$order_code),'*');
			$orderAddress = array(); //收件人
			$orderSendAddress = array(); //发件人
			foreach($addressList as $addressRow) {
				$country_name = "";
				if($addressRow['oab_country_id']>0){
					$country = Service_Country::getByField($addressRow['oab_country_id']);
					if(!empty($country)){
						$country_name = $country['country_name'];
					}
				}
				$addressRow['country_name'] = $country_name;
				if($addressRow['oab_type']=='0') $orderAddress = $addressRow;
				else if($addressRow['oab_type']=='1') $orderSendAddress = $addressRow;
			}
                        $purpose_totalDeclare= Service_OrderProduct::sumPurposeDeclaredValue($order['order_code']);
                         $invoceContry=Service_ShippingMethodConfig::getInvoiceContry();
                        if (in_array($orderAddress['oab_country_id'],$invoceContry)) {
                              if($orderAddress['oab_country_id']!='251'){
                                 $order['invoiceTip']= '该订单需提供正本发票';
                              }else{
                                  if($purpose_totalDeclare>Service_ShippingMethodConfig::$purPusDecalar){
                                      $order['invoiceTip']= '该订单需提供正本发票';
                                  }
                              }
                        }
            //哲盟的需要提示打发票
            $countryNeedInvoice = Service_DHLTHApiProcess::getNeedInvoiceCountry();
            if( $order['sm_code'] == 'DHL-TH' && in_array( $orderAddress['oab_country_id'], $countryNeedInvoice ) ) {
                $order['invoiceTip']= '该订单需提供正本发票';
            }
			$orderProduct = Service_OrderProduct::getByCondition(array('order_code' => $order_code), "*");
			$showBatteryType = array();
            $withBattery = 0;
			foreach($orderProduct as $opRow){
			    $pRow = Service_Product::getByField($opRow['product_id']);
			    if($pRow['with_battery'] == '1'){
			        $showBatteryType[] = Service_Product::$_batteryTypeArray[$pRow['battery_type']];
                    $withBattery = 1;
			    }
			}
			$orderAddress['show_battery'] = implode("/", array_unique($showBatteryType));
            if($withBattery) $orderAddress['withBattery'] = 1;
			$countProduct = count($orderProduct);
			$shipMethod = Service_ShippingMethod::getByField($order['sm_code'],'sm_code');
			//print_r($orderProduct);
			if($this->_request->isPost()){
				$orderInfo['order'] = $order;
				$orderInfo['receiveAddress'] = $addressRow;
				$orderInfo['sendAddress'] = $orderSendAddress;
				$orderInfo['orderProduct'] = $orderProduct;
				$pices = $this->_request->getParam('pices');
				$ename = array();
                $orderVilumeWeight = Service_OrdersVolumeWeight::getByCondition(array('order_code'=>$order_code),"*");
				if($pices>$countProduct){
					//pices数大于产品数 最后一个产品做一直填充
					for($i=0;$i<$pices;$i++){
						if($i<$countProduct-1){
							$title_en = $orderProduct[$i]['product_title_en'];
							$op_id = $orderProduct[$i]['op_id'];
                            $length = isset($orderVilumeWeight[$i]['vow_length'])?$orderVilumeWeight[$i]['vow_length']:"";
                            $width = isset($orderVilumeWeight[$i]['vow_width'])?$orderVilumeWeight[$i]['vow_width']:"";
                            $height = isset($orderVilumeWeight[$i]['vow_height'])?$orderVilumeWeight[$i]['vow_height']:"";
                            $weight = isset($orderVilumeWeight[$i]['vow_weight'])?$orderVilumeWeight[$i]['vow_weight']:"";
						}else{
							$title_en = $orderProduct[$countProduct-1]['product_title_en'];
							$op_id = $orderProduct[$countProduct-1]['op_id'];
                            $length = isset($orderVilumeWeight[$countProduct-1]['vow_length'])?$orderVilumeWeight[$countProduct-1]['vow_length']:"";
                            $width = isset($orderVilumeWeight[$countProduct-1]['vow_width'])?$orderVilumeWeight[$countProduct-1]['vow_width']:"";
                            $height = isset($orderVilumeWeight[$countProduct-1]['vow_height'])?$orderVilumeWeight[$countProduct-1]['vow_height']:"";
                            $weight = isset($orderVilumeWeight[$countProduct-1]['vow_weight'])?$orderVilumeWeight[$countProduct-1]['vow_weight']:"";
						}
						$productArr = array(
							'title_en'=>$title_en,
							'op_id'=>$op_id,
                            'vow_length'=>$length,
                            'vow_width'=>$width,
                            'vow_height'=>$height,
                            'vow_weight'=>$weight,
						);
						$ename[$i] = $productArr;
					}
				}elseif ($pices<=$countProduct){
					for($i=0;$i<$pices;$i++){
						$title_en = $orderProduct[$i]['product_title_en'];
						$op_id = $orderProduct[$i]['op_id'];
                        $length = isset($orderVilumeWeight[$i]['vow_length'])?$orderVilumeWeight[$i]['vow_length']:"";
                        $width = isset($orderVilumeWeight[$i]['vow_width'])?$orderVilumeWeight[$i]['vow_width']:"";
                        $height = isset($orderVilumeWeight[$i]['vow_height'])?$orderVilumeWeight[$i]['vow_height']:"";
                        $weight = isset($orderVilumeWeight[$i]['vow_weight'])?$orderVilumeWeight[$i]['vow_weight']:"";
						$productArr = array(
								'title_en'=>$title_en,
								'op_id'=>$op_id,
                                'vow_length'=>$length,
                                'vow_width'=>$width,
                                'vow_height'=>$height,
                                'vow_weight'=>$weight,
						);
						$ename[$i] = $productArr;
					}
				}
				$orderInfo['ename'] = $ename;
				die(json_encode($orderInfo));
			}
		}
	}
		if($order_code){
			$this->view->message = $message;
			$this->view->order_code = $order_code;
			$this->view->order = $order;
		}
		if($canScan=='1'){
			$this->view->orderReceive = $orderAddress;
			$this->view->orderSendAddress = $orderSendAddress;
			$this->view->shipMethod=$shipMethod;
			$this->view->isOneWorldExpress = $isOneWorldExpress;
		}
                $this->view->url = 'http://'.$_SERVER['HTTP_HOST'].'/pdf-plugin/web/viewer.html?file=http://'.$_SERVER['HTTP_HOST'].'/shipment/print/get-pdf-label/orderCode/';
		$this->view->canScan = $canScan;
		echo Ec::renderTpl($this->tplDirectory . "recorded-single.tpl", 'layout');
	}
	/**
	 * @author william-fan
	 * @todo 提交录单
	 */
	public function submitSingleAction(){
		if($this->_request->isPost()){
			$order_code = $this->_request->getParam('order_code','');
			$lengthData = $this->_request->getParam('length',array());
			$widthData = $this->_request->getParam('width',array());
			$heightData = $this->_request->getParam('height',array());
			$weightData = $this->_request->getParam('weight',array());
			$opIdData = $this->_request->getParam('op_id',array());
			$totalpiecs = $this->_request->getParam('totalpiecs','');
			$enameData	= $this->_request->getParam('ename','');		
			$result = array(
				'state'=>'0'
			);
                        
                        $netWeight  =   array_sum($weightData);
                        $orderProduct  =    Service_OrderProduct::getByCondition(array(
                            'order_code'=>$order_code
                        ) , array('product_id' , 'op_quantity'));
                        
                        $productNetWeight =   0;
                        foreach ($orderProduct as $key => $value) {
                            $product    =   Service_Product::getByField($value['product_id'],'product_id' , array('product_weight'));
                            if(isset($product['product_weight']) && $product['product_weight'])
                                $productNetWeight += $product['product_weight'] * $value['op_quantity'];
                        }
                                        
                        if($netWeight < $productNetWeight){
                            die(json_encode(array(
				'state' => 0,
				'error' => array(array(
                                    'errorCode' => '50000',
                                    'errorMsg'=>'包裹总重量不能小于产品总净重！'
                                    )),
				'message' => '录单失败'
                            )));
                        }
			$params= $this->_request->getParams();
			$piecesDetail = array();
			foreach($lengthData as $key=>$length){
				 $detail = array(
                                                'length'=>$length,
                                                'width'=>$widthData[$key],
                                                'height'=>$heightData[$key],
                                                'weight'=>$weightData[$key],
                                                'op_description'=>$enameData[$key],
                                                'op_id'=>$opIdData[$key]
							);
				 $piecesDetail[] = $detail;
			}
			$params['piecesDetail'] = $piecesDetail;
            $params['totalpiecs'] = $totalpiecs;
			$recordSingleObj = new Service_RecordSingleProcess2();
			$result = $recordSingleObj->recordSingle($params);
			die(json_encode($result));
		}
	}
	/**
	 * @author william-fan
	 * @todo 用于获取订单信息
	 */
	public function getOrderInfoAction(){
		//file_get_contents('');
		echo '<div><img src="/images/header/icon_nav03.png"></div>';
	}
	/**
	 * @author william-fan
	 * @todo 计算体积重
	 */
	public function countVolAction(){
		if($this->_request->isPost()){
			
		}
	}
	/**
	 * @author william-fan
	 * @todo 打开pdf
	 */
	public function printAction(){
		/* echo 'nm';
		exit;
		echo file_get_contents('file:///E:/wamp/www/pdfprint/pdf.js-master/pdf.js-master/examples/helloworld/index.html');
		exit */;
		/* echo Ec::renderTpl($this->tplDirectory . "print.tpl", 'layout');
		
		exit; */
		echo Ec::renderTpl("receiving/views/recordsingle/print.tpl", 'layout');
		exit;
		$path = $this->_request->getParam('path','');
		$decodePath = base64_decode($path);
		$decodePath = "E:/wamp/www/chukouwms/public/images/PDF_SOE01240000008.pdf";
		if($decodePath){
			if(file_exists($decodePath)){
				header('Content-type: application/pdf');
				$fname = 'aaa';
				header('filename='.$fname);
				readfile($decodePath);
				exit();
			}
		}
		exit('file not exist');
		//$pfname = "E:/wamp/www/chukouwms/public/images/PDF_SOE01240000008.pdf";
		/* echo file_get_contents($pfname);
		exit; */
                             //file的相对地址
	}
	
}