<?php
class Api_ServiceForProduct {

 	protected $_customerId = null;
    
    protected $_customer = null;

    protected $_token = null;

    protected $_key = null;

    protected $_auth = false;

    protected $_error = null;    

    protected $_date = null;

    protected $_paramterArr = array();//将传递过来的对象转为数组存储

    protected $_version;
    protected $_errorCodeMsg = array();
    protected $_operation;
    protected $_ask = 0;
    protected $_msg = '';
    protected $_skuNo;
    protected $_inventory;
    protected $_product;
    

    private function _init ($headerRequest) {
        $this->_customerCode = (string) $headerRequest['customerCode'];
        $this->_operationCustomerCode = (string) $headerRequest['operationCustomerCode'];
        $this->_token = (string) $headerRequest['appToken'];
        $this->_key = (string) $headerRequest['appKey'];
        $this->_version = (string) $headerRequest['version'];
    }
    protected function setOperation( $op ) {
        $this->_operation = $op;
    }
    protected function setMsg( $msg = '' ) {
        $this->_msg = $msg;
    }
    protected function addErrorCodeMsg( $code = '', $msg = '' ) {
        $this->_errorCodeMsg[] = array( 'code' => $code, 'msg' => $msg );
    }
    protected function addError( $error = '' ) {
        $this->_error[] = $error;
    }
    /**
     * @author william-fan
     * @todo Authenticate
     */
	private function authenticate(){
        $customer = Service_Customer::getByField($this->_customerCode, 'customer_code');
        if (! $customer || $customer['customer_status'] != 2) {
            $this->setMsg('No Authority For ' . $this->_customerCode . '.');
            $this->addError('No Authority For ' . $this->_customerCode . '.');
            $this->addErrorCodeMsg( 'CAL001', '用户授权认证失败' );
            return false;
        }
        $this->_customer = $customer;

        $customerAuth = Service_CustomerApi::getByField($this->_customerCode, 'customer_code');

        if ( $customerAuth && $customerAuth['ca_token'] == $this->_token && $customerAuth['ca_key'] == $this->_key) {
            if(!empty($this->_operationCustomerCode)){
                $opCustomer=Service_Customer::getByField($this->_operationCustomerCode, 'customer_code');
                if(empty($opCustomer)){
                    $this->setMsg( 'Customer [' . $this->_operationCustomerCode . '] does not exist .');
                    $this->addError('Customer [' . $this->_operationCustomerCode . '] does not exist .');
                    $this->addErrorCodeMsg( 'CAL003', 'operationCustomerCode不存在' );
                    return false;
                }
                if(Service_CustomerRegister::getByCondition(array('regis_customer_code' => $this->_customerCode, 'customer_code' => $this->_operationCustomerCode)) == false){
                    $this->setMsg( 'No authorization operation ' . $this->_operationCustomerCode . '.');
                    $this->addError( 'No authorization operation ' . $this->_operationCustomerCode . '.' );
                    $this->addErrorCodeMsg( 'CAL004', 'operationCustomerCode不是你的下属客户' );
                    return false;
                }
            }

            //当前客户代码改为操作客户代码
            if(!empty($this->_operationCustomerCode)){
                $this->_customerCode = $this->_operationCustomerCode;
                $this->_customer=$opCustomer;
            }

            $this->_auth = true;
            return true;

        } else {
            $this->setMsg( 'App Token/App Key Not match for ' . $this->_customerCode . '.');
            $this->addError( 'App Token/App Key Not match for ' . $this->_customerCode . '.' );
            $this->addErrorCodeMsg( 'CAL002', 'Key/Token不正确' );
            return false;

        }
    }
	/**
	 * @todo 写日志
	 */
    private function logError ($error) {
        $logger = new Zend_Log();
        $uploadDir = APPLICATION_PATH . "/../data/log/";
        $writer = new Zend_Log_Writer_Stream($uploadDir . 'api-product.log');
        $logger->addWriter($writer);
        $logger->info(date('Y-m-d H:i:s') . ': ' . $error . " \n");
    }

    protected function getResult() {
        $result = array('ask'=>'0','message'=>'Failure','error'=>'');
        if ( $this->_error || $this->_errorCodeMsg ) {
            $result['message'] = $this->_msg;
            if( $this->_version === '1.01') {
                $result['message'] = 'Failure';
                $result['errorCodeMsg'] = $this->_errorCodeMsg;
            } else {
                //谁写的接口，error的定义跟其他的不一样！！！！！！！！！！！！
                if( $this->_operation == 'getBatchStock' ) {
                    $result['error'] = $this->_error;
                } else {
                    $result['error'] = Common_TransError::Transerror( $this->_error );
                }
            }
        }
        if( $this->_ask == 1 ) {
            $result['ask'] = 1;
            $result['message'] = $this->_msg;
            switch( $this->_operation ) {
                case 'createProduct':
                    $result['skuNo'] = $this->_skuNo;
                    break;
                case 'getStock':
                    $result['data'] = $this->_inventory;
                    break;
                case 'getProduct':
                    $result['data'] = $this->_product;
                    break;
                case 'getBatchStock':
                    $result['data'] = $this->_inventory;
                    break;
                default:
                    break;
            }
        }
        //$result['message'] = var_export( $this->_error,true).''.var_export( $this->_errorCodeMsg, true);
        return $result;
    }
    
	/**
	 * @author william-fan
	 * @todo 对wsdl 自动将多维数组转为一维数组的处理
	 */
    private function multiArr ($arr) {
        $return = array();
        if(is_array($arr)){
            $isMulti = true;
            foreach($arr as $k=>$v){
                if(!is_int($k)){
                    $isMulti = false;
                }
            }
            if(!$isMulti){
                $return[] = $arr;
            }else{
                $return = $arr;
            }             
        }else if(is_string($arr)){
            $return[] = $arr;
        }
        return $return;
    }
    
    /**
     * @author william-fam
     * @todo 公共方法
     */ 
    private function common($paramter) {
		// var_dump($paramter);exit;
        // 对象转数组		
        $this->_paramterArr = Common_Common::objectToArray($paramter);//对象转数组		 
        $headRequest = $this->_paramterArr['HeaderRequest'];
        $this->_init($headRequest);
        //print_r($this->_paramterArr);
        //$this->_token = $this->_paramterArr['appToken'];
        //file_put_contents('error002.txt', '00000221'.$this->_token.var_export($this->_paramterArr,true));
        $this->_date = date('Y-m-d H:i:s');
        //file_put_contents('common.txt', '00000221'.$this->_token.var_export($this->_paramterArr,true));
        
        return $this->authenticate();
        /* exit;
        file_put_contents('error003.txt', '0000020000555'.var_export($this->_paramterArr,true));return; */
    }
	
	
	
   public  function createProduct(object $parameter) {
        $this->setOperation('createProduct');
		//print_r($parameter);exit;	
		//$parameter['HeaderRequest'] = (array)$parameter['HeaderRequest'];
		//$parameter['ProductInfo'] = (array)$parameter['ProductInfo'];
		//$this->_paramterArr = Common_Common::objectToArray($paramter);//对象转数组

 		if ( false == $this->common($parameter) ) {
            return $this->getResult();
        }	
		
		//$uploadDir = APPLICATION_PATH . "/../data/log/test.log";
		//file_put_contents($uploadDir ,print_r($this->_paramterArr,1));
         $filePath = APPLICATION_PATH.'/../data/log/'.'soap-CreateProduct-Response.txt';
         if(!file_exists($filePath)){
             $fp= fopen($filePath,"w");
             fclose($fp);
         }
         file_put_contents($filePath,var_export($this->_paramterArr,true));
					 
		 $ProductInfo = $this->_paramterArr['ProductInfo'];
		 if(!in_array($ProductInfo['hasInvoice'],array('1','2'))){
		 	$ProductInfo['hasInvoice'] = '2';		 
		 }
         if(!isset($ProductInfo['UOM'])||$ProductInfo['UOM']==""){
             $ProductInfo['UOM'] = "007";
         }

		 $row = array();
		 $time = date('Y-m-d H:i:s');
		 $row['product_sku'] = $ProductInfo['skuNo'];//sku编码
		 $row['product_title'] = $ProductInfo['skuName'];//中文名称
         $row['product_title_en'] = $ProductInfo['productTtitleEn'];
		 $row['pu_code'] = $ProductInfo['UOM'];//产品单位
		 $row['product_barcode_type'] = $ProductInfo['barcodeType'];//条码类型
		 $row['product_barcode'] = $ProductInfo['barcodeDefine'];//自定义条码
		 $row['product_weight'] = $ProductInfo['weight'];//重量
		 $row['has_invoice'] = $ProductInfo['hasInvoice'];//是否有发票
		 $row['currency_code'] = 'USD';//币种
		 $row['hs_goods_name'] = $ProductInfo['hsGoodsName'];
		 $row['hs_code'] = $ProductInfo['hsCode'];
		 $row['product_declared_value'] = $ProductInfo['productDeclaredValue'];	
		 $row['is_accessories'] = $ProductInfo['is_accessories'];
		 if($row['is_accessories']!='1'){
		 	$row['is_accessories'] = 0;
		 }	 
		 $row['customer_id'] = $this->_customer['customer_id'];;
		 $row['customer_code'] = $this->_customer['customer_code'];;		 
		 $row['product_add_time'] = $time;
         $row['product_update_time'] = $time;
         $row['with_battery'] = isset($ProductInfo['with_battery'])?$ProductInfo['with_battery']:0;
         $row['battery_type'] = isset($ProductInfo['battery_type'])?$ProductInfo['battery_type']:'';
		 $row['battery_detail'] = isset($ProductInfo['battery_detail'])?$ProductInfo['battery_detail']:'';
         //接口加入长宽高的信息，为了搞光亚项目，光亚提前传商品信息，并附带长宽高重量信息，以便为计算运费
         if(isset($ProductInfo['length'])){
             $row['product_length'] = $ProductInfo['length'];
         }
         if(isset($ProductInfo['width'])){
             $row['product_width'] = $ProductInfo['width'];
         }
         if(isset($ProductInfo['height'])){
             $row['product_height'] = $ProductInfo['height'];
         }


         //$row['isRecord'] = $ProductInfo['isRecord'];
         //$row['recordInfo'] = $ProductInfo['recordInfo'];
		 
		 $result = Service_Product::createProductForSoap($row,$row['customer_code']);

         $this->setMsg( $result['message'] );
		 if($result['ask'] == 1 ){
             $this->_ask = 1;
             $this->_skuNo = $row['product_sku'];
		 }else{
             if( isset( $result['error']['error'] ) && !empty( $result['error']['error'] ) ) {
                foreach( $result['error']['error'] as $value ) {
                    $this->addError( $value );
                }
             }
             if( isset( $result['error']['errorCodeMsg'] ) && !empty( $result['error']['errorCodeMsg'] ) ) {
                 foreach( $result['error']['errorCodeMsg'] as $value ) {
                     $this->addErrorCodeMsg( $value['code'], $value['msg'] );
                 }
             }
		 }
		 //file_put_contents($uploadDir ,print_r($resultArray,1));
		return $this->getResult();
		 //parent::checkRow($row);
		 
		// return $name;
    }			
 
    

	 /**
     * queryStock
     * @param string $productSku
       @return array 
		查询库存API  colin-yang
		
    */
	
    public  function getStock($parameter) {
        $this->setOperation('getStock');

		$uploadDir = APPLICATION_PATH . "/../data/log/test.log";
		//	file_put_contents($uploadDir ,print_r($parameter,1));
		//file_put_contents($uploadDir ,print_r($this->_paramterArr,1));
        if ( false == $this->common($parameter) ) {
            return $this->getResult();
        }

		$productSku = $this->_paramterArr['skuNo'];
		//file_put_contents($uploadDir ,print_r($this->_customer['customer_id'],1));
		$customer_id = $this->_customer['customer_id'];
		$condition_array = array();	
		$condition_array['product_sku'] = $productSku;
		$condition_array['customer_id'] = $customer_id;			
		$product_array = Service_Product::getByCondition($condition_array);
		
		if( empty( $product_array ) ){
			$this->setMsg('非法的产品SKU');
            $this->addError('非法的产品SKU');
            $this->addErrorCodeMsg('PRO013','SKU不存在');
			return $this->getResult();
		}	
		
		$condition_array = array();	
		$condition_array['product_id'] =  $product_array[0]['product_id'];
		$condition_array['customer_id'] = $customer_id;				
		$ProductInventoryArray =  Service_ProductInventory::getByCondition($condition_array);
		if(empty($ProductInventoryArray)){
            $this->setMsg('没找到库存数据');
            $this->addError('没找到库存数据');
            $this->addErrorCodeMsg('PRO014','没找到库存数据');
			return $this->getResult();
		}
		
		$return_data_array = array();

		$productRow = Service_Product::getByCondition($condition_array,"*");
        foreach($ProductInventoryArray as $k =>$row){
			$warehouse_id = $row['warehouse_id'];
			$warehouse_array = Service_Warehouse::getByField($warehouse_id,'warehouse_id');
			if(empty($warehouse_array)){continue;}
			
			$return_data_array[] = array(
				'skuNo'=>$productSku,
				'warehouseCode'=>$warehouse_array['warehouse_code'],
				'onwayQty'=>$row['pi_onway'],//在途数
				'pendingQty'=>$row['pi_pending'],//到货（未上架数量）
				'sellableQty'=>$row['pi_sellable'],//可用
				'unsellableQty'=>$row['pi_unsellable'],//不可用
				'reservedQty'=>$row['pi_reserved'],//冻结数量
				'shippedQty'=>$row['pi_shipped'],//已出库数量
			);		
		}//foreach

        $this->setMsg('获取库存信息成功');
        $this->_ask = 1;
        $this->_inventory = $return_data_array;
		return $this->getResult();
    }

    public function getProduct($parameter){
        $this->setOperation('getProduct');

        $uploadDir = APPLICATION_PATH . "/../data/log/test.log";
        //	file_put_contents($uploadDir ,print_r($parameter,1));
        //file_put_contents($uploadDir ,print_r($this->_paramterArr,1));
        if ( false == $this->common($parameter) ) {
            return $this->getResult();
        }

        $productSku = $this->_paramterArr['skuNo'];
        $customer_id = $this->_customer['customer_id'];
        $condition = array(
            'product_sku'=>$productSku,
            'customer_id'=>$customer_id
        );
        $productList = Service_Product::getByCondition($condition,"*");
        if(!empty($productList)){
            $goodsModel = array();
            $product = $productList[0];
            $product['model_serial'] = '';
            //防止全部查出来了
            if($product['product_id']!='' && $product['product_id']>0 ){
                $hsCondition = array(
                    'product_id'=>$product['product_id']
                );
                $hsMaps=Service_HsElementMap::getByCondition($hsCondition,'*');
                //file_put_contents($uploadDir,var_export($hsMaps,true));
                if(!empty($hsMaps)){
                    $model_serial2 ='';
                    foreach($hsMaps as $key=>$map){
                        $heElementInfo = Service_HsElement::getByField($map['he_id'],'he_id');
                        if ('' != trim($map['hem_detail'])) {
                            $goodsModel[] = $map['hem_detail'];
                        }
                        $model_serial2.=$heElementInfo['he_name'].":".$map['hem_detail']."|";
                    }
                    $product['model_serial'] = implode('|', $goodsModel);
                    $product['model_serial2'] = $model_serial2;
                }
            }
            $this->setMsg('获取产品信息成功');
            $this->_ask = 1;
            $this->_product = $product;
        }else{
            $this->setMsg('不存在sku['.$productSku.']的产品');
            $this->addError('不存在sku['.$productSku.']的产品');
            $this->addErrorCodeMsg('PRO013','SKU不存在');
        }
        return $this->getResult();
    }

    public function getBatchStock($parameter){
        $this->setOperation('getBatchStock');

        if ( false == $this->common($parameter) ) {
            return $this->getResult();
        }

        $return_data_array = array();
        $skuArr = $this->_paramterArr['skuNoArr'];

        if (!is_array($skuArr)) {
            $skuArr = array($skuArr);
        }

        $customer_id = $this->_customer['customer_id'];

        if(count($skuArr)=="1"&&$skuArr[0]=="ALLStock"){
            $condition_array['customer_id'] = $customer_id;
            $ProductInventoryArray =  Service_ProductInventory::getByCondition($condition_array);

            if(empty($ProductInventoryArray)){

                $this->setMsg('没找到库存数据');
                $this->addError('没找到库存数据');
                $this->addErrorCodeMsg('PRO014','没找到库存数据');
            }else{
                foreach($ProductInventoryArray as $pik =>$row){
                    $warehouse_id = $row['warehouse_id'];
                    $warehouse_array = Service_Warehouse::getByField($warehouse_id,'warehouse_id');
                    if(empty($warehouse_array)){continue;}
                    $product = Service_Product::getByField($row['product_id'],'product_id',"*");

                    $return_data_array[] = array(
                        'skuNo'=>$product['product_sku'],
                        'warehouseCode'=>$warehouse_array['warehouse_code'],
                        'onwayQty'=>$row['pi_onway'],//在途数
                        'pendingQty'=>$row['pi_pending'],//到货（未上架数量）
                        'sellableQty'=>$row['pi_sellable'],//可用
                        'unsellableQty'=>$row['pi_unsellable'],//不可用
                        'reservedQty'=>$row['pi_reserved'],//冻结数量
                        'shippedQty'=>$row['pi_shipped'],//已出库数量
                        'expireQty'=>$row['pi_expired'],//过期数
                    );
                }//foreach
            }
        }else{
            foreach($skuArr as $key=>$val){

                $condition_array = array();
                $condition_array['product_sku'] = $val;
                $condition_array['customer_id'] = $customer_id;
                $product_array = Service_Product::getByCondition($condition_array);

                if(empty($product_array)){
                    $this->addError('不存在sku['.$val.']的产品');
                    $this->addErrorCodeMsg('PRO013',$val.'SKU不存在');
                    continue;
                }

                $condition_array = array();
                $condition_array['product_id'] =  $product_array[0]['product_id'];
                $condition_array['customer_id'] = $customer_id;
                $ProductInventoryArray =  Service_ProductInventory::getByCondition($condition_array);
                if(empty($ProductInventoryArray)){
                    $this->addError($val.'没找到库存数据');
                    $this->addErrorCodeMsg('PRO014',$val."没找到库存数据.");
                    continue;
                }
                foreach($ProductInventoryArray as $pik =>$row){
                    $warehouse_id = $row['warehouse_id'];
                    $warehouse_array = Service_Warehouse::getByField($warehouse_id,'warehouse_id');
                    if(empty($warehouse_array)){continue;}

                    $return_data_array[] = array(
                        'skuNo'=>$val,
                        'warehouseCode'=>$warehouse_array['warehouse_code'],
                        'onwayQty'=>$row['pi_onway'],//在途数
                        'pendingQty'=>$row['pi_pending'],//到货（未上架数量）
                        'sellableQty'=>$row['pi_sellable'],//可用
                        'unsellableQty'=>$row['pi_unsellable'],//不可用
                        'reservedQty'=>$row['pi_reserved'],//冻结数量
                        'shippedQty'=>$row['pi_shipped'],//已出库数量
                        'expireQty'=>$row['pi_expired'],//过期数
                    );
                }//foreach

            }
        }
        if( $return_data_array ) {
            $this->_ask = 1;
            $this->setMsg('获取库存信息成功');
        } else {
            $this->setMsg('获取库存信息失败');
        }
        $this->_inventory = $return_data_array;
        return $this->getResult();
    }
    
}