<?php
class Service_Product
{
    /**
     * @var null
     */
    public static $_modelClass = null;

    public static $productType = array(
    		0=>'普通产品',
    		1=>'组合产品',
    );

    /**
     * @return Table_Product|null
     */
    public static function getModelInstance()
    {
        if (is_null(self::$_modelClass)) {
            self::$_modelClass = new Table_Product();
        }
        return self::$_modelClass;
    }

    /**
     * @param $row
     * @return mixed
     */
    public static function add($row)
    {
        $model = self::getModelInstance();
        return $model->add($row);
    }


    /**
     * @param $row
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function update($row, $value, $field = "product_id")
    {
        $model = self::getModelInstance();
        return $model->update($row, $value, $field);
    }

    public static function customUpdate($data, $condition, $value = '')
    {
    	$model = self::getModelInstance();
    	return $model->customUpdate($data, $condition, $value);
    }

    /**
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function delete($value, $field = "product_id")
    {
        $model = self::getModelInstance();
        return $model->delete($value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @param string $colums
     * @return mixed
     */
    public static function getByField($value, $field = 'product_id', $colums = "*")
    {
        $model = self::getModelInstance();
        return $model->getByField($value, $field, $colums);
    }

    public static function getByWhere($where, $colums = "*") {
    	$model = self::getModelInstance();
    	return $model->getByWhere($where, $colums);
    }

    /**
     * @return mixed
     */
    public static function getAll()
    {
        $model = self::getModelInstance();
        return $model->getAll();
    }
    //获取产品封面图片链接
    public static function getProductSingleImageUrl($productId){
    	return "http://".$_SERVER['HTTP_HOST']."/merchant/product/view-image/id/".$productId;
    }
    //获取attach图片链接
    public static function getAttachUrlByAid($aid){
    	return "http://".$_SERVER['HTTP_HOST']."/merchant/product/view-attach/aid/".$aid;
    }
    //获取上传时的图片链接
    public static function getUploadUrlByName($fileName){
    	return "http://".$_SERVER['HTTP_HOST']."/merchant/product/view-upload-image/fileName/".$fileName;
    }
    /**
     * @author william-fan
     * @todo 用于得到订单信息
     */
	public static function getProductAllInfo($productId,$customerId){
        $product = Service_Product::getByField($productId, 'product_id');
        if ($product&&$product['customer_id']==$customerId) {
            if ($product['product_type'] == 1) {
                $combines = Service_ProductCombineRelation::getByCondition(array(
                        'product_id' => $productId
                ), "*");
                $subs = array();
                foreach ($combines as $v) {
                    $sub = Service_Product::getByField($v['pcr_product_id'], 'product_id');
                    $v['pcr_product_sku'] = $sub['product_sku'];
                    $subs[] = $v;
                }
                $product['subs'] = $subs;
            }
            if ($product['product_type'] == 0) {
                $con = array(
                        'product_id' => $productId
                );
                $attaches = Service_ProductAttached::getByCondition($con);
                foreach ($attaches as $key => $attach) {
                    if ($attach['pa_file_type'] == 'img') {
                        $attaches[$key]['url'] = self::getAttachUrlByAid($attach['pa_id']);
                    } else {
                        $attaches[$key]['url'] = $attach['pa_path'];
                    }
                }
                $product['attach'] = $attaches;
                if($product['pc_id']){
                    $category = Common_DataCache::getCategory($product['pc_id']);
                }

                //获取hs_element_map
                $conHs = array(
                	'product_id'=>$productId
                );

                $hsElementMaps = Service_HsElementMap::getByCondition($con);
                if(!empty($hsElementMaps)){
                	foreach ($hsElementMaps as $hsm=>$valuehsm){
                		$hselement = Service_HsElement::getByField($valuehsm['he_id']);
                		//print_r($hselement);
                		$hsElementMaps[$hsm]['hs_code'] = $hselement['hs_code'];
                		$hsElementMaps[$hsm]['he_name'] = $hselement['he_name'];
                	}
                }
                $product['hs_element_maps'] = $hsElementMaps;

                //获取hs_uom_map
                $conditonUomMap = array(
                	'product_id'=>$productId
                );
                $hsUomMaps = Service_HsUomMap::getByCondition($conditonUomMap);

                $hsUomMap = '';
                if(!empty($hsUomMaps)){
                	$hsUomMap = $hsUomMaps[0];
                	$hsUom = Service_HsUom::getByField($hsUomMap['hu_id']);
                	if($hsUom['pu_code_law']){
                        $puLaw = Service_ProductUom::getByField($hsUom['pu_code_law'],'pu_code');
                        if($hsUom['pu_code_second']!=''){
                            $puSecond = Service_ProductUom::getByField($hsUom['pu_code_second'],'pu_code');
                            $hsUomMap['pu_name_second'] = $puSecond['pu_name'];
                        }
                    }
                	$hsUomMap['pu_name_law'] = $puLaw['pu_name'];

                }
                $product['hs_uom_map'] = $hsUomMap;

            }
            $product['category_name'] = empty($category) ? "--" : $category['pc_name'];
            if ($product['product_type'] == 2) {
                $attrRow = Service_ProductAttribute::getByField($productId, 'product_id');
                // print_r($attrRow);exit;
                $product['ext'] = unserialize($attrRow['pa_value']);
            }
            $product['product_status_cn'] = $product['product_status'] == 1 ? "可用" : "不可用";
            $product['product_type_title'] = self::$productType[$product['product_type']];

            return $product;
        }
        return false;
    }

    /**
     * 关联获取跟PRODUCT有关的所有表信息
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getAllByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getAllByCondition($condition, $type, $pageSize, $page, $order);
    }

    /**
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getByCondition($condition = array(), $field = '*', $order = '', $pageSize = 20, $page = 0)
    {
        $model = self::getModelInstance();
        return $model->getByCondition($condition, $field, $order, $pageSize, $page);
    }

    /**
     * @param $val
     * @return array
     */
    public static function validator($val)
    {
        $validateArr = $error = array();

        return  Common_Validator::formValidator($validateArr);
    }

    /**
     * 获取自定义SQL语句查询结果
     *
     * @access	public
     * @param   string	($field		待返回的字段，默认为所有)
     * @param   string	($condition	查询条件)
     * @param	mixed	($value		待转换查询字段值)
     * @return	mixed
     */
    public static function getCustomQuery($field = '*', $condition = '', $value = '')
    {
    	$model = self::getModelInstance();
    	return $model->getCustomQuery($field, $condition, $value);
    }
    /**
     * @author william-fan
     * @todo检查普通产品提交字段有效性
     */
    public static function validate($row,$customer_code){
    	$error = array();
    	if("" == $row['product_sku']){
    		$error[] = Ec_Lang::getInstance()->getTranslate('ProductSKU').Ec_Lang::getInstance()->getTranslate('require');//"产品sku必填";
    	}elseif (1 !== (int) $row['product_barcode_type'] && !preg_match('/^[0-9a-zA-Z\-]{1,20}$/', $row['product_sku'])){
        // 自定义条码不收此限制
    		$error[] = Ec_Lang::getInstance()->getTranslate('ProductSkuRequiredMustBeAlphanumericCharactersAndUnderscores');//"产品sku必填必须是字母数字下划线";
    	}
    	if($row['product_title']==''){
    		$error[] = Ec_Lang::getInstance()->getTranslate('ChineseDescription').Ec_Lang::getInstance()->getTranslate('require');//'产品名称必须填写';
    	}
        if($row['product_title_en']==''){
            $error[] = Ec_Lang::getInstance()->getTranslate('productTitle').Ec_Lang::getInstance()->getTranslate('require');//'产品名称必须填写';
        }else{
//            if (!preg_match("/^[0-9a-zA-Z\- ]+$/", $row['product_title_en'])){
//                $error[] = "英文名称[".$row['product_title_en']."] 只能包含英文字母、数字、空格和 - ";
//            }
        }
    	if($row['pu_code']==''){
    		$error[] = Ec_Lang::getInstance()->getTranslate('p_unit').Ec_Lang::getInstance()->getTranslate('require');//'产品单位必须填写';
    	}
		/*
    	if($row['pc_id']==''){
    		$error[] = Ec_Lang::getInstance()->getTranslate('ProductCategory').Ec_Lang::getInstance()->getTranslate('require');//'产品目录必须填写';
    	}
		*/

      // 供应商代码有效性验证
      if (!empty($row['distributor_code']) && 0 == $row['distributor_id']) {
        $error[] = '无效的供应商代码【' . $row['distributor_code'] . '】';
      }

    	if($row['hs_goods_name']==''){
    		$error[] = Ec_Lang::getInstance()->getTranslate('CustomsGoodsName').Ec_Lang::getInstance()->getTranslate('require');//'海关品名必须填写';
    	}
      elseif (!Service_GB18030::isValid($row['hs_goods_name'])) {
        $error[] = '海关品名含有非GB18030字符集字符';
      }elseif(preg_match('/^[a-zA-Z\s]+$/',$row['hs_goods_name'])){
            $error[] = '海关品名不能全是字母';
      }elseif(preg_match('/^(((?=[\x21-\x7e]+)[^A-Za-z0-9])|\s)*$/',$row['hs_goods_name'])){
            $error[] = '海关品名不能全是字符';
      }

    	if($row['hs_code']==''){
    		$error[] = Ec_Lang::getInstance()->getTranslate('CustomsCode').Ec_Lang::getInstance()->getTranslate('require');//'海关编码必须填写';
    	}else{
			$hs_code_array = Service_Hscodes::getByField($row['hs_code'],'hs_code');
			if(empty($hs_code_array)){
					$error[] =  '非法的海关编码.';
			}
		}
		/*
        if(empty($row['product_length']) || !is_numeric($row['product_length']) || $row['product_length']<=0 ){
	            $error[] = "产品长度必须填写并且必须为正数.";
	    }

        if(empty($row['product_width']) || !is_numeric($row['product_width']) || $row['product_width']<=0 ){
	             $error[] = "产品宽度必须填写并且必须为正数.";
	    }

        if(empty($row['product_height']) || !is_numeric($row['product_height']) || $row['product_height']<=0 ){
	            $error[]="产品高度必须填写并且必须为正数.";
	    }
		*/
        if(empty($row['product_declared_value']) || !is_numeric($row['product_declared_value']) || $row['product_declared_value']<=0 ){
	           $error[]=Ec::_("申报价值必须为正的金额.");
	    }

        if(empty($row['product_weight']) || !is_numeric($row['product_weight']) || $row['product_weight']<=0 ){
	            $error[] = "重量必须填写并且必须为正数.";
	    }
    	if(isset($row['hs_element'])){
    		foreach ($row['hs_element'] as $hs=>$vahs){
    			$hscheck=Service_HsElement::getByField($vahs['he_id']);
    			if($vahs['hem_detail']==''&&
                    $hscheck['he_name']!="其他" &&
                    $hscheck['he_name']!="GTIN" &&
                    $hscheck['he_name']!="CAS"
                ){
    				$error[] = "{$hscheck['he_name']}".Ec_Lang::getInstance()->getTranslate('require');
    			}
                //申报要素不允许包含的特殊字符
                $specialCharsPattern    = "/[\\\'\";?~`!@#$^&=)({}\[\]]/";
                $specialCharsCheck      = preg_match($specialCharsPattern, $vahs['hem_detail']);
                if($specialCharsCheck){
                    $error[] = '海关申报要素：'.$vahs['hem_detail'].' 包含特殊字符';
                }
                //中文特殊字符
                $specialCharsPattern_cn = array(
                    "！",
                    "￥",
                    "（",
                    "）",
                    "【",
                    "】",
                    "、",
                    "；",
                    "“",
                    "”",
                    "‘",
                    "’",
                    "？",
                    "《",
                    "》",
                    "…",
                    );
                if(!empty($vahs['hem_detail'])){
                    foreach($specialCharsPattern_cn as $cn_val){
                        $specialCharsCheck_cn   = mb_strstr($vahs['hem_detail'],$cn_val);
                        if($specialCharsCheck_cn){
                            $error[] = '海关申报要素：'.$vahs['hem_detail'].' 包含特殊字符';
                        }
                    }
                    if (!Service_GB18030::isValid($vahs['hem_detail'])) {
                      //$error[] = '海关申报要素含有非GB18030字符集字符';
                    }
                    if( preg_match("/(\xC2\xA0)/u",$vahs['hem_detail']) ){
                        $error[] = '海关申报要素含有网页空白符,请把标识位([?])的空白删除或者改成半角空格: '.preg_replace("/(\xC2\xA0)/u", "[?]",$vahs['hem_detail']);
                    }
                }
    		}
    	}
		if($row['product_barcode_type']==1){
			 if(empty($row['product_barcode'])){
			 	$error[] = "自定义条码必填.";
			 } else{			// 自定义类型条码不受此限制
			 	/*if(!preg_match('/^[0-9a-zA-Z\-]{1,18}$/', $row['product_barcode'])){
			    	$error[] = "自定义条码仅限能输入字母、数字和横杠,最大长度为18位.";
			 	}*/
                 //检查条码是否存在
                 $product = Service_Product::getByCondition( array( 'customer_code'=> $customer_code, 'product_barcode' => $row['product_barcode'] ) );
                 if( $product ) {
                     $error[] = "自定义条码已存在.";
                 }
			 }
		}

		if(!function_exists('mb_strlen')){
			$error[] = "系统必须安装mb模块.";
		}

		if($row['hs_element'] && is_array($row['hs_element'])){
					$elementValueLength = 0;
			    	foreach($row['hs_element'] as $elementValue){
    						//$elementValueLength+= mb_strlen($elementValue['hem_detail'],"utf-8");
                            //IT说汉字按2字符算
                            $elementValueLength+= strlen(mb_convert_encoding($elementValue['hem_detail'],'GB2312','UTF-8'));
    				}
					if($elementValueLength>200){
						$error[] = "各申报元素的内容总长度不超过200个字符。";
					}

		}

    	if($row['pu_code_law']=='' || $row['pu_code_law']<=0 || !is_numeric($row['pu_code_law']) ){
    		$error[] = Ec_Lang::getInstance()->getTranslate('LegalUnitMustBeGreaterThan0');//'法定单位必须是大于0的数字';
    	}

    	if(!in_array($row['has_invoice'], array('1','2'))) {
    		$error[] = "有无发票必须是1或者2";
    	}
      if($row['with_battery']=="1"&&$row['battery_type']==""){
          $error[] = "电池类型必选";
      }
      if($row['battery_type']=="6"&&$row['battery_detail']==""){
          $error[] = "电池类型为其他，时电池类型补充必填";
      }

    	return $error;
    }
    /**
     * @param array $params
     * @return array
     */
    public  function getFields()
    {
        $row = array(

              'E0'=>'product_id',
              'E1'=>'product_sku',
              'E2'=>'product_barcode',
              'E3'=>'customer_code',
              'E4'=>'customer_id',
              'E5'=>'product_title_en',
              'E6'=>'product_title',
              'E7'=>'product_status',
              'E8'=>'product_receive_status',
              'E9'=>'pu_code',
              'E10'=>'product_length',
              'E11'=>'product_width',
              'E12'=>'product_height',
              'E13'=>'product_net_weight',
              'E14'=>'product_weight',
              'E15'=>'product_sales_value',
              'E16'=>'product_purchase_value',
              'E17'=>'product_declared_value',
              'E18'=>'product_is_qc',
              'E19'=>'product_barcode_type',
              'E20'=>'product_type',
              'E21'=>'pc_id',
              'E22'=>'pce_id',
              'E23'=>'product_add_time',
              'E24'=>'product_update_time',
        );
        return $row;
    }
    /* 去除空格 */
    public static function fomatRow($row){
    	foreach($row as $k=>$v){
    		if(!is_array($v)){
    			$row[$k] = trim($v);
    		}else{
    			$row[$k] = ($v);
    		}
    	}
    	return $row;
    }
	/**
	 * @createDate 2013-06-08
	 * @author william
	 * @todo 创建普通产品
	 *
	 */
	public static function createProductTransaction($row,$customer_code,$picUrlArr=array(),$picLinkArr=array()){
	    $result = array("ask"=>0,"message"=>Ec_Lang::getInstance()->getTranslate('ProductCreationFailed'),'actionType'=>'create');
	    $row = self::fomatRow($row);
	    //print_r($row);
	    $error = self::validate($row,$customer_code);
	    if(!empty($error)){
	        $result['error'] = $error;
	        return $result;
	    }

	    $db = Common_Common::getAdapter();
	    $db->beginTransaction();
	    try{
	        $con = array('product_sku'=>$row['product_sku'],'customer_code'=>$customer_code);
	        $products = Service_Product::getByCondition($con,"*",0,0,'',0);
	        if(!empty($products)){
	            throw new Exception("sku已存在");
	        }
	        //条形码
	        $row['product_barcode'] = $row['product_barcode_type']==1?$row['product_barcode']:($customer_code.'-'.$row['product_sku']);

	        if(empty($row['product_barcode'])){
	            throw new Exception("产品条码为空");
	        }
	        /*$con = array('product_barcode'=>$row['product_barcode']);
	        $product = Service_Product::getByCondition($con,"*");
	        if(!empty($product)){
	            throw new Exception("产品条码已存在");
	        }*/

	        $row['product_add_time'] = date("Y-m-d H:i:s");
	        $row['product_update_time'] = date("Y-m-d H:i:s");
	        //$row['product_type']=0;

	        $productRow = array(
	        	'product_sku' => $row['product_sku'],
	        	'customer_code'=>$row['customer_code'],
	        	'customer_id' => $row['customer_id'],
	        	'product_title_en' =>$row['product_title_en'],
	        	'product_title' => $row['product_title'],
	        	'pu_code' => $row['pu_code'],
				'currency_code' => $row['currency_code'],
	        	//'product_length' =>$row['product_length'],
	        	//'product_width' =>$row['product_width'],
	        	//'product_height' =>$row['product_height'],
	        	'product_weight' => $row['product_weight'],
	        	'product_declared_value' =>$row['product_declared_value'],
	        	'product_barcode_type' =>$row['product_barcode_type'],
	        	'product_type' =>$row['product_type'],
                'model_serial'=>$row['model_serial'],
	        	//'pc_id' =>$row['pc_id'],
				'product_status' =>1,
	        	'product_add_time' =>$row['product_add_time'],
				'product_update_time' =>$row['product_update_time'],
	        	'product_barcode' =>$row['product_barcode'],
	        	'hs_goods_name' => strtoupper($row['hs_goods_name']),
	        	'hs_code'		  =>$row['hs_code'],
	        	'is_accessories'  =>$row['is_accessories'],
	        	'has_invoice'  =>$row['has_invoice'],
            'distributor_id' => $row['distributor_id'], // 供应商ID
                'with_battery' =>$row['with_battery'],
                'battery_type' =>$row['battery_type'],
                'battery_detail' =>$row['battery_detail'],
	        );


	        if(!$productId = Service_Product::add($productRow)){
	            throw new Exception("插入产品出错");
	        }
	        $row['product_id'] = $productId;
	        //添加hs_element_map
	        if(isset($row['hs_element'])){
	        	$hs_elements=$row['hs_element'];
	        	if(!empty($hs_elements)){

					//$hs_codes = Service_Hscodes::getByCondition(array('hs_code'=>$hs_code,'hs_code_status'=>'1'))
	        		$checkElement = array();
                    foreach($hs_elements as $hsk=>$hs_element){
                        $hd=  preg_replace('/\x{a0}/u',' ', $hs_element['hem_detail']);
                        $hd=  trim(strtoupper($hd));
                        if( $hd !== "" && !is_null( $hd ) ){
                            $checkElement[$hs_element['he_id']] = $hd;
                        }
                    }
                    if($productRow['customer_code']=="E0728"){
                        $existProduct = Service_Product::getByCondition(array('hs_code'=>$productRow['hs_code'],'hs_goods_name'=>$productRow['hs_goods_name'],'customer_id'=>$productRow['customer_id']),"*");
                        if(!empty($existProduct)){
                            foreach($existProduct as $ep){
                                if($ep['product_id']==$productId) continue;
                                $he = Service_HsElementMap::getByCondition(array('product_id'=>$ep['product_id'],'not_empty_hem_detail'=>1),"*");
                                $pass = 1;
                                if(count($checkElement)!=count($he)) continue;
                                if(!empty($he)){
                                    foreach($he as $e){
                                        if(!isset($checkElement[$e['he_id']])||$checkElement[$e['he_id']]!=$e['hem_detail']){
                                            $pass = 0;
                                            continue;
                                        }
                                    }
                                }
                                if($pass) throw new Exception($productRow['product_sku']."上传申报要素与".$ep['product_sku']."的一样,申报要素上传失败");
                            }
                        }
                    }
                    foreach($hs_elements as $hsk=>$hs_element){
	        			$hscheck=Service_HsElement::getByField($hs_element['he_id']);
	        			if(!empty($hscheck) && $hscheck['hs_code']==$row['hs_code']){
                                            $hsDetail=  preg_replace('/\x{a0}/u',' ', $hs_element['hem_detail']);
                                           $hsDetail=  trim(strtoupper($hsDetail));

                            //只有申报要素：其他 为空的申报要素不在写进表里，其他申报要素不能为空
                            if( $hsDetail === '' || is_null( $hsDetail ) ) {
                                if( $hscheck['he_code'] == '其他' || $hscheck['he_code'] == 'GTIN' || $hscheck['he_code'] == 'CAS') {

                                } else {
                                    throw new Exception('申报要素【'.$hscheck['he_code'].'】不能为空');
                                }
                            }
	        				$hsElementMapRow = array(
	        					'he_id'=>$hs_element['he_id'],
	        					'product_id'=>$productId,
	        					'hem_detail'=>$hsDetail,
								'element_id'=>$hscheck['element_id'],
	        					'hem_add_time'=>date('Y-m-d H:i:s',time())
	        				);
	        				if(!Service_HsElementMap::add($hsElementMapRow)){
	        					throw new Exception("插入海关编码与产品关系出错");
	        				}
	        			}else{
	        				throw new Exception("海关编码不存在或者错误--{$hs_element['he_id']}");
	        			}
	        		}
	        	}
	        }
	        //添加hs_uom_map
	        if(isset($row['hu_id'])){
	        	$huCheck = Service_HsUom::getByField($row['hu_id']);
	        	if(!empty($huCheck) && $huCheck['hs_code']==$row['hs_code']){
	        		if($row['pu_code_law']) {
                        $productUomRow = Service_ProductUom::getByField($huCheck['pu_code_law'],'pu_code',array('pu_int_request'));
                        if( (1==$productUomRow['pu_int_request']) && !ctype_digit(strval($row['pu_code_law']))){
                            throw new Exception("第一法定单位必须是大于0的正整数，您的不正确输入为：".$row['pu_code_law']);
                        }
	        			$row['pu_code_law'] = floor($row['pu_code_law']*10000)/10000;
                        if($row['pu_code_law'] <= 0){
                            throw new Exception('第一法定单位必须大于0！请不要输入小于0.001的小数！');
                        }
	        		}
	        		if($row['pu_code_second']) {
                        $productUomRow = Service_ProductUom::getByField($huCheck['pu_code_second'],'pu_code',array('pu_int_request'));
                        if( (1==$productUomRow['pu_int_request']) && !ctype_digit(strval($row['pu_code_second']))){
                            throw new Exception("第二法定单位必须是大于0的正整数，您的不正确输入为：".$row['pu_code_second']);
                        }
	        			$row['pu_code_second'] = floor($row['pu_code_second']*10000)/10000;
                        if($row['pu_code_second'] <= 0){
                            throw new Exception('第二法定单位必须大于0！请不要输入小于0.001的小数！');
                        }
	        		}
	        		$hsUomMapLawRow = array(
	        			'hu_id'=>$row['hu_id'],
	        			'product_id'=>$productId,
	        			'hum_quantity_law'=>$row['pu_code_law'],
	        			'hum_quantity_second'=>$row['pu_code_second'],
	        			'hum_add_time'=>date('Y-m-d H:i:s',time())
	        		);

	        		if(!Service_HsUomMap::add($hsUomMapLawRow)){
	        			throw new Exception("添加海关申报单位和产品关系出错");
	        		}
	        	}else{
	        		throw new Exception("海关申报单位不存在或者出错");
	        	}
	        }


	        $customer = Service_Customer::getByField($customer_code,'customer_code');
	        $customerId = $customer['customer_id'];
	        /* var_dump($customer);
	        var_dump($customer_code);
	         $db->rollback();
	        exit; */
	        Service_ProductAttached::addLink($picLinkArr, $productId);
	        Service_ProductAttached::copyImages($picUrlArr, $customerId, $productId);

	        //料件号
	      	/*$uProduct['goods_id'] = 'BH'.str_pad($productId, 8, '0', STR_PAD_LEFT);
	        Service_Product::update($uProduct, $productId);*/

	        $logRow = array(
	                'product_id' => $productId,
	                'pl_type'=>'0',
	                'customer_id'=>$customerId,
	                'pl_add_time'=>date("Y-m-d H:i:s"),
	        		'pl_statu_pre'=>'1',
	        		'pl_statu_now'=>'1',
	                'pl_note'=>'ProductSku:['.$row['product_sku'].'] Create',
	                'pl_ip'=>Common_Common::getIP(),
                  'user_id' => -1,
                  'account_id' => Service_Login::getUserId()
	        );
	        //print_r($logRow);exit;
	        //self::writeOrderLog($logRow);

	        if(!Service_ProductLog::add($logRow)){
	        	throw new Exception("添加日志错误");
	        }

	        //处理产品备案
	        self::handleRecord($productId);

	        /*  $row['c_app_type'] = 0;
	        $row['c_code'] = $row['product_barcode']; */
	        //self::dataToWarehouse($row);
	        $result['productId'] = $productId;
			$result['product_sku'] = $row['product_sku'];
	        $db->commit();
	        //$db->rollback();
	        $result['ask'] = 1;
	        $result['message'] = "产品创建成功";
	    }catch(Exception $e){
	        $db->rollback();
	        //echo $e->__toString();
	        $result['errorCode'] = $e->getCode();
	        $result['message'] = $e->getMessage();
	        $result['error'] = array();
	    }
	    return $result;
	}

	/**
	 * 处理产品备案
	 * @author solar
	 * @param int $product_id
	 */
	public static function handleRecord($product_id) {
		$aProduct = Service_Product::getByField($product_id);
        $goodsKeyArr = self::getGoodsKeyArr($aProduct);
		//$goods_key = self::generateGoodsKey($aProduct);
        $goods_key = "";
        $aGoods = array();
        $customerRow = Service_Customer::getByField($aProduct['customer_id'],'customer_id',"*");
        foreach($goodsKeyArr as $k=>$v){
            $tmpKey = $v;
            $condition = array(
                'goods_key'=>$tmpKey,
                'not_goods_code'=>array('CSC000001','CSC000010','CSC000011'),
            );

            $goods_key = $tmpKey;

            $pgList = Service_ProductGoods::getByCondition($condition,'*',1,1);
            //只有分销的才进去查
            if( empty( $pgList ) && $customerRow['customer_platform'] == 'FX') {
                //截取最后一个字符，因为上传申报要素时，【其他】为空时是不会写进hs_element_map表的，但是旧产品已经把空的【其它】写进hs_element_map表，
                //所以如果旧产品的【其他】为空时，product_goods表goods_key的最后一个字符应该是+号，请看getGoodsKeyArr()方法，goods_key的生成规则
                $lastChar = mb_substr($tmpKey, -1, 1 );
                if( $lastChar != '+' ) {
                    $tmpKey .= '+';
                    $condition = array(
                        'goods_key'=>$tmpKey,
                        'not_goods_code'=>array('CSC000001','CSC000010','CSC000011'),
                    );
                    $pgList = Service_ProductGoods::getByCondition($condition,'*',1,1);
                }
            }
            if(!empty($pgList)){
                foreach($pgList as $pg){
                    $aGoods = $pg;
                    break;
                }
            }
        }
		//$aGoods = Service_ProductGoods::getByField($goods_key, 'goods_key');
		if(empty($aGoods)) {
			$goodsRow['goods_code'] = Service_CustomerProcess::generateGoodsId($aProduct['customer_id'], $aProduct['has_invoice']);
			$goodsRow['goods_key'] = $goods_key;
			$product_model = self::getGModel($product_id);
			$hs_key = self::generateHsKey($aProduct['hs_code'], $aProduct['hs_goods_name'], $product_model);
			$goodsRow['hs_key'] = $hs_key;
			/* $hsGoods = Service_ProductGoods::getByField($hs_key, 'hs_key');
			if($hsGoods) {
				$goodsRow['pg_status'] = $hsGoods['pg_status'];
				$uProduct['product_status'] = $hsGoods['pg_status']==1 ? 1 : 0;
			} else {
				$goodsRow['pg_status'] = 0;
				$uProduct['product_status'] = 0;
			} */
			$aApiGoodsResult = Service_ApiGoodsResult::getByField($hs_key, 'agr_hs_key');
			if(empty($aApiGoodsResult)) {
				$goodsRow['pg_status'] = 0;
				$uProduct['product_status'] = 0;
			} else if($aApiGoodsResult['STATUS']==4) {
				$goodsRow['pg_status'] = 3;
				$uProduct['product_status'] = 0;
			} else if($aApiGoodsResult['STATUS']==2) {
				$goodsRow['pg_status'] = 4;
				$uProduct['product_status'] = 0;
			}
			$goodsRow['product_id'] = $product_id;
			$aGoods['pg_id'] = Service_ProductGoods::add($goodsRow);
			$uProduct['goods_id'] = $goodsRow['goods_code'];
		} else if($aGoods['pg_status'] == 1) {
			$uProduct['goods_id'] = $aGoods['goods_code'];
			$uProduct['product_status'] = 1;
		} else {
			$uProduct['goods_id'] = $aGoods['goods_code'];
			$uProduct['product_status'] = 0;
		}
		if($aProduct['is_accessories']=='1') {
			Service_ProductGoods::update(array('is_accessories'=>'1'), $aGoods['pg_id']);
		}
		//$uProduct['product_status'] = 1;	//测试阶段为1
		Service_Product::update($uProduct, $product_id);

		//日志
		$logRow = array(
				'product_id' => $product_id,
				'pl_type'=>'1',
				'customer_id'=>$aProduct['customer_id'],
				'pl_add_time'=>date("Y-m-d H:i:s"),
				'pl_statu_pre'=>$aProduct['product_status'],
				'pl_statu_now'=>$uProduct['product_status'],
				'pl_note'=>'Product Record Check',
				'pl_ip'=>Common_Common::getIP(),
        'user_id' => -1,
        'account_id' => Service_Login::getUserId()
		);
		Service_ProductLog::add($logRow);
	}

	/**
	 * 生成判断是否同一报关产品的唯一串
	 * 客户ID+海关品名+hs_code+申报要素+单位
	 * @author solar
	 * @param mix $product
	 * @return string
	 */
	/* public static function generateGoodsKey($product) {
		$key = '';
		if(is_array($product)) $aProduct = $product;
		else $aProduct = Service_Product::getByField($product);
		$key .= $aProduct['customer_id'];
		$key .= str_replace(array('\u','"'), '', json_encode(trim($aProduct['hs_goods_name'])));
		$key .= trim($aProduct['hs_code']);
		$hemList = Service_HsElementMap::getByCondition(array('product_id'=>$aProduct['product_id']));
		foreach($hemList as $hemRow) {
			$key .= '+'.str_replace(array('\u','"'), '', json_encode(trim($hemRow['hem_detail'])));
		}
		$humList = Service_HsUomMap::getByCondition(array('product_id'=>$aProduct['product_id']));
		foreach($humList as $humRow) {
			$key .= '+'.$humRow['hum_quantity_law'].'+'.$humRow['hum_quantity_second'];
		}
		return $key;
	} */
	public static function generateGoodsKey($product) {
		$key = '';
		if(is_array($product)) $aProduct = $product;
		else $aProduct = Service_Product::getByField($product);
		$key .= $aProduct['customer_id'];
		$key .= str_replace(array('\u','"'), '', json_encode(trim($aProduct['hs_goods_name'])));
		$key .= trim($aProduct['hs_code']);
        $key .= trim($aProduct['pu_code']);
		$hemList = Service_HsElementMap::getByCondition(array('product_id'=>$aProduct['product_id']));
		foreach($hemList as $hemRow) {
			$key .= '+'.str_replace(array('\u','"'), '', json_encode(trim($hemRow['hem_detail'])));
		}
		/* $humList = Service_HsUomMap::getByCondition(array('product_id'=>$aProduct['product_id']));
		foreach($humList as $humRow) {
			$key .= '+'.$humRow['hum_quantity_law'].'+'.$humRow['hum_quantity_second'];
		} */
		//有无发票
		if($aProduct['has_invoice']==2) {
			$key .= 'noinvoice';
		}
		return $key;
	}

    public static function getGoodsKeyArr($product){
        $key = '';
        if(is_array($product)) $aProduct = $product;
        else $aProduct = Service_Product::getByField($product);
        $customerRow = Service_Customer::getByField($aProduct['customer_id'],'customer_id',"*");
        if($customerRow['trade_co']!=""){
            $customerList = Service_Customer::getByCondition(array('trade_co'=>$customerRow['trade_co']),"*");
        }else{
            $customerList[] = $customerRow;
        }
        //$key .= $aProduct['customer_id'];
        $key .= str_replace(array('\u','"'), '', json_encode(trim($aProduct['hs_goods_name'])));
        $key .= trim($aProduct['hs_code']);
        $key .= trim($aProduct['pu_code']);
        $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$aProduct['product_id']));
        foreach($hemList as $hemRow) {
            $key .= '+'.str_replace(array('\u','"'), '', json_encode(trim($hemRow['hem_detail'])));
        }
        /* $humList = Service_HsUomMap::getByCondition(array('product_id'=>$aProduct['product_id']));
        foreach($humList as $humRow) {
            $key .= '+'.$humRow['hum_quantity_law'].'+'.$humRow['hum_quantity_second'];
        } */
        //有无发票
        if($aProduct['has_invoice']==2) {
            $key .= 'noinvoice';
        }
        $keyArr = array();
        if($customerRow['customer_platform']=="FX"){
            foreach($customerList as $customer){
                $keyArr[] = $customer['customer_id'].$key;
            }
        }else{
            $keyArr[] = $customerRow['customer_code'].$key;
        }

        return $keyArr;
    }

	public static function generateHsKey($CODE_TS, $G_NAME_CN, $G_MODEL) {
		$key = '';
		$key .= trim($CODE_TS);
		$key .= '#'.str_replace(array('\u','"'), '', json_encode(trim($G_NAME_CN)));
		$key .= '#'.str_replace(array('\u','"'), '', json_encode(trim($G_MODEL)));
		return $key;
	}

	public static function getGModel($product_id) {
		$where['product_id'] = $product_id;
		$list = Service_HsElementMap::getByCondition($where);
		$elements = array();
		foreach($list as $row) {
			$hem_detail = trim($row['hem_detail']);
			$elements[] = $hem_detail ? $hem_detail : '/';//不在会有斜杆出现，申报要素[其他]为空时不再写进表
		}
		return implode('|', $elements);
	}

	/**
	 * @todo 获取图片
	 */
	private static function getOldAttach($productId){
		$con = array('product_id'=>$productId);
		$productAttachRows = Service_ProductAttached::getByCondition($con);

		return $productAttachRows;
	}
	/**
	 * @param unknown_type $productAttachRows
	 * @todo 删除图片
	 */
	private static function deleteOldAttach($productAttachRows){
		// 	            删除图片
		foreach($productAttachRows as $row){
			if($row['pa_file_type']=='img'){
				@unlink(APPLICATION_PATH."/../data/images/".$row['pa_path']);
			}
			if(!Service_ProductAttached::delete($row['pa_id'],'pa_id')){
				throw new Exception("内部错误!删除图片失败");
			}
		}
	}
    /* 更新普通产品 */
	public static function updateProductTransaction($row,$productId,$customerId,$picUrlArr=array(),$picLinkArr=array()){
	    $result = array("ask"=>0,"message"=>Ec_Lang::getInstance()->getTranslate('EcProductModify').Ec_Lang::getInstance()->getTranslate('fail'),"actionType"=>'update');

	    $row = self::fomatRow($row);
	    $error = self::validate($row,$customerId);
	    if(!empty($error)){
	        $result['error'] = $error;
	        return $result;
	    }

	    $db = Common_Common::getAdapter();
	    $db->beginTransaction();
	    try{
	        $product = Service_Product::getByField($productId,'product_id');
	        if($product['product_status']!='2'){
                throw new Exception(Ec_Lang::getInstance()->getTranslate('ProductStatusNotDraftStatus'));
            }
	        //在什么情况下不可更新 ---------------------------------------占位
	        if($product['customer_id']!=$customerId){//非本人不能更新
	        	//无权限
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('EcProductModify').Ec_Lang::getInstance()->getTranslate('fail').",".Ec_Lang::getInstance()->getTranslate('NoAuthority'));
	        }
	        /*if($product['product_receive_status'] >0){//第一次收货 之后 不可更新
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('UpdateProductFailProductMustNotNoASN'));
	        }*/
	        /*if($product['have_asn']=='1'){
	        	throw new Exception(Ec_Lang::getInstance()->getTranslate('UpdateProductFailProductMustNotNoASN'));
	        }*/
	        $customer = Service_Customer::getByField($customerId);
	        $customer_code = $customer['customer_code'];

	        //条形码
	        //$row['product_barcode'] = $row['product_barcode_type']==1?$row['product_barcode']:($customerId.'-'.$product['product_sku']);
	        $row['product_barcode'] = $row['product_barcode_type']==1?$row['product_barcode']:($customer_code.'-'.$row['product_sku']);


	        if(isset($row['product_sku'])){
	        	//unset($row['product_sku']);
	        }
	        if(isset($row['product_id'])){
	        	//unset($row['product_id']);
	        }


	        if(empty($row['product_barcode'])){
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('ProductBarcodeIsEmpty'));
	        }
	        /*$con = array('product_barcode'=>$row['product_barcode']);
	        $products = Service_Product::getByCondition($con,"*");

	        if(!empty($products)){
	            $products = $products[0];
	            if($products['product_id']!=$productId){
	                throw new Exception(Ec_Lang::getInstance()->getTranslate('ProductBarcodeIsExist'));
	            }
	        }*/

	        $row['product_update_time'] = date("Y-m-d H:i:s");


	        $productRow = array(
	        		'customer_code'=>$row['customer_code'],
	        		'customer_id' => $row['customer_id'],
	        		//'product_title_en' =>$row['product_title_en'],
	        		'product_title' => $row['product_title'],
	        		'pu_code' => $row['pu_code'],
					'currency_code' => $row['currency_code'],
	        		//'product_length' =>$row['product_length'],
	        		//'product_width' =>$row['product_width'],
	        		//'product_height' =>$row['product_height'],
                    'model_serial'=>$row['model_serial'],
	        		'product_weight' => $row['product_weight'],
	        		'product_declared_value' =>$row['product_declared_value'],
	        		'product_barcode_type' =>$row['product_barcode_type'],
	        		'product_type' =>$row['product_type'],
	        		//'pc_id' =>$row['pc_id'],
					'product_status' =>1,
	        		'product_update_time' =>$row['product_add_time'],
	        		'product_barcode' =>$row['product_barcode'],
	        		'hs_goods_name' => strtoupper($row['hs_goods_name']),
	        		'hs_code'		  =>$row['hs_code'],
	        		'has_invoice'=>$row['has_invoice'],
              'distributor_id' => $row['distributor_id'], // 供应商ID
                    'with_battery' =>$row['with_battery'],
                    'battery_type' =>$row['battery_type'],
                    'battery_detail' =>$row['battery_detail'],
	        );

	        if(!Service_Product::update($productRow,$productId)){
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorUpdateProductFailure'));
	        }


	        //添加hs_element_map
	        if(isset($row['hs_element'])){
	        	$hs_elements=$row['hs_element'];
	        	if(!empty($hs_elements)){
	        		Service_HsElementMap::delete($productId,'product_id');

                    $checkElement = array();
                    foreach($hs_elements as $hsk=>$hs_element){
                        $hd=  preg_replace('/\x{a0}/u',' ', $hs_element['hem_detail']);
                        $hd=  trim(strtoupper($hd));
                        $checkElement[$hs_element['he_id']] = $hd;
                    }
                    if($productRow['customer_code']=="E0728"||$productRow['customer_code']=="E0174"){
                        $existProduct = Service_Product::getByCondition(array('hs_code'=>$productRow['hs_code'],'hs_goods_name'=>$productRow['hs_goods_name'],'customer_id'=>$productRow['customer_id']),"*");
                        if(!empty($existProduct)){
                            foreach($existProduct as $ep){
                                if($ep['product_id']==$productId) continue;
                                $he = Service_HsElementMap::getByCondition(array('product_id'=>$ep['product_id'],'not_empty_hem_detail'=>1),"*");
                                $pass = 1;
                                if(count($checkElement)!=count($he)) continue;
                                if(!empty($he)){
                                    foreach($he as $e){
                                        if(!isset($checkElement[$e['he_id']])||$checkElement[$e['he_id']]!=$e['hem_detail']){
                                            $pass = 0;
                                            continue;
                                        }
                                    }
                                }
                                if($pass) throw new Exception($productRow['product_sku']."上传申报要素与".$ep['product_sku']."的一样,申报要素上传失败");
                            }
                        }
                    }

	        		foreach($hs_elements as $hsk=>$hs_element){
	        			$hscheck=Service_HsElement::getByField($hs_element['he_id']);
	        			if(!empty($hscheck) && $hscheck['hs_code']==$row['hs_code']){
                                              $hsDetail=  preg_replace('/\x{a0}/u',' ', $hs_element['hem_detail']);
                                            $hsDetail=  trim(strtoupper($hsDetail));

                            //只有申报要素：其他 为空的申报要素不在写进表里，其他申报要素不能为空
                            if( $hsDetail === '' || is_null( $hsDetail ) ) {
                                if( $hscheck['he_code'] == '其他' || $hscheck['he_code'] == 'GTIN'|| $hscheck['he_code'] == 'CAS') {
                                } else {
                                    throw new Exception('申报要素【'.$hscheck['he_code'].'】不能为空');
                                }
                            }

	        				$hsElementMapRow = array(
	        						'he_id'=>$hs_element['he_id'],
	        						'product_id'=>$productId,
	        						'hem_detail'=>$hsDetail,
	        						'hem_add_time'=>date('Y-m-d H:i:s',time()),
									'element_id'=>$hscheck['element_id']
	        				);
	        				//print_r($hsElementMapRow);
	        				if(!Service_HsElementMap::add($hsElementMapRow)){
	        					throw new Exception(Ec_Lang::getInstance()->getTranslate('InsertCustomsCodesAndProductRelationshipsError'));
	        				}
	        			}else{
	        				throw new Exception(Ec_Lang::getInstance()->getTranslate('CustomsCodeDoesNotExistOrError')."--{$hs_element['he_id']}");
	        			}
	        		}
	        	}
	        }

	        //添加hs_uom_map
	        if(isset($row['hu_id'])){
	        	Service_HsUomMap::delete($productId,'product_id');
	        	$huCheck = Service_HsUom::getByField($row['hu_id']);
	        	if(!empty($huCheck) && $huCheck['hs_code']==$row['hs_code']){
	        		if($row['pu_code_law']) {
                        $productUomRow = Service_ProductUom::getByField($huCheck['pu_code_law'],'pu_code',array('pu_int_request'));
                        if( (1==$productUomRow['pu_int_request']) && !ctype_digit(strval($row['pu_code_law']))){
                            throw new Exception("第一法定单位必须是大于0的正整数，您的不正确输入为：".$row['pu_code_law']);
                        }
	        			$row['pu_code_law'] = floor($row['pu_code_law']*10000)/10000;
	        		}
	        		if($row['pu_code_second']) {
                        $productUomRow = Service_ProductUom::getByField($huCheck['pu_code_second'],'pu_code',array('pu_int_request'));
                        if( (1==$productUomRow['pu_int_request']) && !ctype_digit(strval($row['pu_code_second']))){
                            throw new Exception("第二法定单位必须是大于0的正整数，您的不正确输入为：".$row['pu_code_second']);
                        }
	        			$row['pu_code_second'] = floor($row['pu_code_second']*10000)/10000;
	        		}
					$hsUomMapLawRow = array(
	        				'hu_id'=>$row['hu_id'],
	        				'product_id'=>$productId,
	        				'hum_quantity_law'=>$row['pu_code_law'],
	        				'hum_quantity_second'=>$row['pu_code_second'],
	        				'hum_add_time'=>date('Y-m-d H:i:s',time())
	        		);
	        		if(!Service_HsUomMap::add($hsUomMapLawRow)){
	        			throw new Exception(Ec_Lang::getInstance()->getTranslate('AddCustomsDeclarationError'));
	        		}
	        	}else{
	        		throw new Exception(Ec_Lang::getInstance()->getTranslate('CustomsReportingUnitDoesNotExistOrError'));
	        	}
	        }



	        $attaches = self::getOldAttach($productId);

	        Service_ProductAttached::addLink($picLinkArr, $productId);
	        Service_ProductAttached::copyImages($picUrlArr, $customerId, $productId);

	        self::deleteOldAttach($attaches);
	        $logRow = array(
	                'product_id' => $productId,
	                'pl_type'=>'0',
	                'customer_id'=>$customerId,
	                'pl_add_time'=>date("Y-m-d H:i:s"),
	                'pl_note'=>'ProductSku:['.$product['product_sku'].'] Content Update',
	                'pl_ip'=>Common_Common::getIP(),
                  'user_id' => -1,
                  'account_id' => Service_Login::getUserId()
	        );
	        //             print_r($logRow);exit;
	        //self::writeOrderLog($logRow);
	        if(!Service_ProductLog::add($logRow)){
	        	throw new Exception(Ec_Lang::getInstance()->getTranslate('AddLogError'));
	        }

	        //处理产品备案
	        self::handleRecord($productId);

	        //self::dataToWarehouse($row);
	        $db->commit();
	        //$db->rollback();
	        $result['productId'] = $productId;
			$result['product_sku'] = $product['product_sku'];
	        $result['ask'] = 1;
	        $result['message'] = Ec_Lang::getInstance()->getTranslate('ProductUpdateSuccess');//"产品更新成功";
	    }catch(Exception $e){
	        $db->rollback();
	        $result['message'] = $e->getMessage();
	        $result['errorCode'] = $e->getCode();
	    }
	    return $result;
	}

	public static function validateCombine($row,$customerId){
        $err = array();
        if ("" == $row['product_title']) {
            $err[] = Ec_Lang::getInstance()->getTranslate('pname').Ec_Lang::getInstance()->getTranslate('require'); //"产品名称必填";
        }
        if ("" == $row['product_sku']) {
           // $err[] =  Ec_Lang::getInstance()->getTranslate('ProductSKU').Ec_Lang::getInstance()->getTranslate('require');//"产品sku必填";
		   $err[] = Ec_Lang::getInstance()->getTranslate('ProductSkuRequiredMustBeAlphanumericCharactersAndUnderscores');
        }elseif (!preg_match('/^[0-9a-zA-Z\-]{1,12}$/', $row['product_sku'])){
        	$err[] = Ec_Lang::getInstance()->getTranslate('ProductSkuRequiredMustBeAlphanumericCharactersAndUnderscores');//"产品sku只能是数字字母破折号";
        }
        if(!isset($row['subs'])){
            $err[] = Ec_Lang::getInstance()->getTranslate('SubSkuMustChoose');//"子sku必须选择";
        }
        $subs = $row['subs'];
        $sum = 0;

        foreach ($subs as $v) {
            $pcr_product_id = $v['product_id'];
            $qty = $v['quantity'];
            $product = Service_Product::getByField($pcr_product_id,'product_id');
            if(!$product){
                $err[] = "Product_id:[{$pcr_product_id}] ".Ec_Lang::getInstance()->getTranslate('DoesNotExist');
                continue;
            }
            if($product['product_type']==1){
                $err[] = Ec_Lang::getInstance()->getTranslate('ProductCanMotBeCombined')."-->[{$product['product_sku']}]";
                continue;
            }
            if ($qty == 0) {
                $err[] = Ec_Lang::getInstance()->getTranslate('QuantityCanNotBeZero')."-->[{$product['product_sku']}]";
                continue;
            }

            $sum += $qty;
        }
        if ($sum < 2) {
            $err[] = Ec_Lang::getInstance()->getTranslate('PleaseSelectAtLeastTwoProducts');//"请至少选择两个产品";
        }
        return $err;

    }

	/**
	 * @author william-fan
	 * @todo 用于创建组合产品
	 **/
	public static function createCombineProductTransaction($row,$customerId,$picUrlArr=array(),$picLinkArr=array()){
	    $result = array("ask"=>0,"message"=>Ec_Lang::getInstance()->getTranslate('AddCombinationProductsError'));
	    $row = self::fomatRow($row);

	    $error = self::validateCombine($row,$customerId);

	    if(!empty($error)){
	        $result['error'] = $error;
	        return $result;
	    }

	    $db = Common_Common::getAdapter();
	    $db->beginTransaction();
	    try{
	        $subs = $row['subs'];

	        unset($row['subs']);
	        $con = array('product_sku'=>$row['product_sku'],'customer_id'=>$customerId);
	        $product = Service_Product::getByCondition($con,"*",0,0,'',0);
	        if(!empty($product)){
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('TheSkuAlreadyExists'));
	        }

	        $row['product_add_time'] = date("Y-m-d H:i:s");
// 	        $row['product_last_modified'] = date("Y-m-d H:i:s");
	        $row['product_type']=1;
	        $row['product_barcode'] =  $row['customer_code'].'-'.$row['product_sku'];
            $row['product_status'] = "1";
// 	        print_r($row);exit;
	        $productId = Service_Product::add($row);

	        if(!$productId){
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('AddCombinationProductsError'));
	        }

	        //创建组合产品
	        $weight = self::createSubsAndCalcuWeight($productId, $subs);

	        if(!Service_Product::update(array('product_weight'=>$weight,'product_update_time'=>date("Y-m-d H:i:s")), $productId)){
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('AddCombinationProductsError'));
	        }
	        /*
	        self::addPicture($picUrlArr, $customerId, $productId);
	        self::addLink($picLinkArr, $productId);
	        */
	        $logRow = array(
	                'product_id' => $productId,
	                'pl_type'=>'0',
	                'customer_id'=>$customerId,
	        		'pl_statu_pre'=>'1',
	        		'pl_statu_now'=>'1',
	                'pl_add_time'=>date("Y-m-d H:i:s"),
	                'pl_note'=>'ProductSku:['.$row['product_sku'].'] Create',
	                'pl_ip'=>Common_Common::getIP(),
                  'user_id' => -1,
                  'account_id' => Service_Login::getUserId()
	        );
	        //             print_r($logRow);exit;
	        //self::writeOrderLog($logRow);
	        if(!Service_ProductLog::add($logRow)){
	        	throw new Exception(Ec_Lang::getInstance()->getTranslate('AddLogError'));
	        }

	        $result['productId'] = $productId;
			$result['product_sku'] = $row['product_sku'];
	        $db->commit();
	        //$db->rollback();
	        $result['ask'] = 1;
	        $result['message'] = Ec_Lang::getInstance()->getTranslate('AddCombinationProductsSuccessful');//"添加组合产品成功";
	    }catch(Exception $e){
	        $db->rollback();
	        $result['message'] = $e->getMessage();
	        $result['errorCode'] = $e->getCode();
	    }
	    return $result;
	}

    /* 更新组合产品 */
	public static function updateCombineProductTransaction($row,$customerId,$productId,$picUrlArr=array(),$picLinkArr=array()){
	    $result = array("ask"=>0,"message"=>Ec_Lang::getInstance()->getTranslate('UpdateProductFails'));

	    $row = self::fomatRow($row);
	    $error = self::validateCombine($row,$customerId);

	    if(!empty($error)){
	        $result['error'] = $error;
	        return $result;
	    }

	    $db = Common_Common::getAdapter();
	    $db->beginTransaction();
	    $result = array("ask"=>0,"message"=>"");
	    try{
	        $subs = $row['subs'];
	        unset($row['subs']);
	        $product = Service_Product::getByField($productId,'product_id');
	        if(empty($product)){
	            throw new Exception("Product Not Exists",'10028');
	        }
	        if($product['customer_id']!=$customerId){//非本人不能更新
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('UpdateProductFailsAuthorityError'));
	        }
	        //需要判断 组合产品 在什么情况下 不可更新-----------------------占位
	        $orderProduct = Service_OrderProduct::getByField($productId, 'product_id');//存在相关订单 不可更新
	        if(!empty($orderProduct)){
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('UpdateProductFailedProductsAlreadyExistOrders')."-->{$product['product_sku']}");
	        }

	        if(isset($row['product_sku'])){
	            unset($row['product_sku']);
	        }
	        if(isset($row['product_id'])){
	            unset($row['product_id']);
	        }
	        if(isset($row['customer_id'])){
	            unset($row['customer_id']);
	        }

	        $row['product_update_time'] = date("Y-m-d H:i:s");


	        //创建组合产品
	        $weight = self::createSubsAndCalcuWeight($productId, $subs);

	        $row['product_weight'] = $weight;

	        if(!Service_Product::update($row,$productId)){
	            throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorUpdateProductFailure'));
	        }

	   /*      $attaches = self::getOldAttach($productId);

	        self::addLink($picLinkArr, $productId);
	        self::addPicture($picUrlArr, $customerId, $productId);

	        self::deleteOldAttach($attaches); */

	        $logRow = array(
	                'product_id' => $productId,
	                'pl_type'=>'0',
	                'customer_id'=>$customerId,
	                'pl_add_time'=>date("Y-m-d H:i:s"),
	                'pl_note'=>'ProductSku:['.$product['product_sku'].'] Content Update',
	                'pl_ip'=>Common_Common::getIP(),
                  'user_id' => -1,
                  'account_id' => Service_Login::getUserId()
	        );
	        //             print_r($logRow);exit;
	        //self::writeOrderLog($logRow);
	        if(!Service_ProductLog::add($logRow)){
	        	throw new Exception(Ec_Lang::getInstance()->getTranslate('AddLogError'));
	        }
	        $db->commit();
	        $result['productId'] = $productId;
			$result['product_sku'] = $product['product_sku'];

	        $result['ask'] = 1;
	        $result['message'] = "成功修改此组合产品.";
	    }catch(Exception $e){
	        $db->rollback();
	        $result['message'] = $e->getMessage();
	        $result['errorCode'] = $e->getCode();
	    }
	    return $result;
	}
	/**
	 * @author william-fan
	 * @todo 组合产品重量
	 */
	private static function createSubsAndCalcuWeight($productId,$subs){
		Service_ProductCombineRelation::delete($productId,'product_id');
		$weight = 0;
		foreach($subs as $v){
			$pcr_product_id = $v['product_id'];
			$qty = $v['quantity'];
			$subrow = array("product_id"=>$productId,"pcr_product_id"=>$pcr_product_id,"pcr_quantity"=>$qty,'pcr_add_time'=>date('Y-m-d H:i:s',time()));
			$temP = Service_Product::getByField($pcr_product_id,'product_id');
			if($temP['product_type']==1){//判断为组合产品，爆出异常
				throw new Exception("不能选择组合产品进行组合-->[".$temP['product_sku']."]");
			}
			$weight+=$temP['product_weight']*$qty;

			if(!Service_ProductCombineRelation::add($subrow)){
				throw new Exception('添加组合产品失败');
			}
		}

		return $weight;
	}


   /**
     * @author colin-yang
     * @todo检查普通产品提交字段有效性
     */
    public static function validate_for_soap($row,$customer_code){
    	$error = $errorCodeMsg = array();
    	if("" == $row['product_sku']){
    		$error[] = Ec_Lang::getInstance()->getTranslate('ProductSKU').Ec_Lang::getInstance()->getTranslate('require');//"产品sku必填";
            $errorCodeMsg[] = array( 'code'=>'PRO002', 'msg' => Ec_Lang::getInstance()->getTranslate('ProductSKU').Ec_Lang::getInstance()->getTranslate('require') );
    	}elseif (1 !== (int) $row['product_barcode_type'] &&!preg_match('/^[0-9a-zA-Z\-]{1,12}$/', $row['product_sku'])){
    		$error[] = Ec_Lang::getInstance()->getTranslate('ProductSkuRequiredMustBeAlphanumericCharactersAndUnderscores');//"产品sku必填必须是字母数字下划线";
            $errorCodeMsg[] = array( 'code'=>'PRO003', 'msg' => Ec_Lang::getInstance()->getTranslate('ProductSkuRequiredMustBeAlphanumericCharactersAndUnderscores') );
    	}
    	if($row['product_title']==''){
    		$error[] = Ec_Lang::getInstance()->getTranslate('ChineseDescription').Ec_Lang::getInstance()->getTranslate('require');//'产品名称必须填写';
            $errorCodeMsg[] = array( 'code'=>'PRO004', 'msg' => Ec_Lang::getInstance()->getTranslate('ChineseDescription').Ec_Lang::getInstance()->getTranslate('require') );
    	}
        if (!preg_match("/^[0-9a-zA-Z\- ]+$/", $row['product_title_en'])){
            $error[] = "英文名称[".$row['product_title_en']."] 只能包含英文字母、数字、空格和 - ";
            $errorCodeMsg[] = array( 'code'=>'PRO005', 'msg' => "英文名称[".$row['product_title_en']."] 只能包含英文字母、数字、空格和 - " );
        }
		/*
    	if($row['pu_code']==''){
    		$error[] = Ec_Lang::getInstance()->getTranslate('p_unit').Ec_Lang::getInstance()->getTranslate('require');//'产品单位必须填写';
    	}
		*/
		/*
    	if($row['pc_id']==''){//产品品类
    		$error[] = Ec_Lang::getInstance()->getTranslate('ProductCategory').Ec_Lang::getInstance()->getTranslate('require');//'产品目录必须填写';
    	}else{
			$product_category_array = Service_ProductCategory::getByField($row['pc_id'],'pc_id');
			if(empty($product_category_array)){
				$error[] = "非法的产品品类";
			}

		}
		*/
		/*
		if($row['currency_code']==''){//币种
				$error[] = "交易币种不能为空.";
		}else{
				$currency_array = Service_Currency::getByField($row['currency_code'],'currency_code');
			    if(empty($currency_array)){
					$error[] = "非法的交易币种.";
				}
		}
		*/
    	/*
		if($row['hs_goods_name']==''){
    		$error[] = Ec_Lang::getInstance()->getTranslate('CustomsGoodsName').Ec_Lang::getInstance()->getTranslate('require');//'海关品名必须填写';
    	}
		*/
		/*
    	if($row['hs_code']==''){
    		$error[] = "海关编码不能为空,且必须是10位的数字.";//'海关编码必须填写';
    	}else{
			$hs_code_array = Service_Hscodes::getByField($row['hs_code'],'hs_code');
			if(empty($hs_code_array)){
					$error[] =  '非法的海关编码.';
			}

		}
		*/
		if($row['hs_code']){
			$hs_code_array = Service_Hscodes::getByField($row['hs_code'],'hs_code');
			if(empty($hs_code_array)){
			    $error[] =  '非法的海关编码.';
                $errorCodeMsg[] = array( 'code'=>'PRO006', 'msg' => "非法的海关编码" );
			}
		}
		/*
        if(empty($row['product_length']) || !is_numeric($row['product_length']) || $row['product_length']<=0 ){
	            $error[] = "产品长度必须填写并且必须为正数.";
	    }

        if(empty($row['product_width']) || !is_numeric($row['product_width']) || $row['product_width']<=0 ){
	             $error[] = "产品宽度必须填写并且必须为正数.";
	    }

        if(empty($row['product_height']) || !is_numeric($row['product_height']) || $row['product_height']<=0 ){
	            $error[]="产品高度必须填写并且必须为正数.";
	    }
		*/
        if(empty($row['product_declared_value']) || !is_numeric($row['product_declared_value']) || $row['product_declared_value']<=0 ){
	           $error[]="申报价值必须为正的金额.";
            $errorCodeMsg[] = array( 'code'=>'PRO007', 'msg' => "申报价值必须为正的金额" );
	    }

        if(empty($row['product_weight']) || !is_numeric($row['product_weight']) || $row['product_weight']<=0 ){
	            $error[] = "重量必须填写并且必须为正数.";
            $errorCodeMsg[] = array( 'code'=>'PRO008', 'msg' => "重量必须填写并且必须为正数" );
	    }
    	/*
		if(isset($row['hs_element'])){
    		foreach ($row['hs_element'] as $hs=>$vahs){
    			$hscheck=Service_HsElement::getByField($vahs['he_id']);
    			if($vahs['hem_detail']==''){
    				$error[] = "{$hscheck['he_name']}".Ec_Lang::getInstance()->getTranslate('require');
    			}
    		}
    	}
		*/
		if($row['product_barcode_type']==1){
       if(!preg_match('/^[0-9a-zA-Z\-]{1,50}$/', $row['product_barcode'])){
           $error[] = "自定义条码仅限能输入字母、数字和横杠,最大长度为50位.";
           $errorCodeMsg[] = array( 'code'=>'PRO009', 'msg' => "自定义条码仅限能输入字母、数字和横杠,最大长度为50位" );
       } else {
           //检查条码是否存在
           $product = Service_Product::getByCondition( array( 'customer_code'=> $customer_code, 'product_barcode' => $row['product_barcode'] ) );
           if( $product ) {
               $error[] = "自定义条码已存在.";
               $errorCodeMsg[] = array( 'code'=>'PRO016', 'msg' => "自定义条码已存在" );
           }
       }
    }

    if($row['with_battery']==1 && empty( $row['battery_type'] ) ){
       $error[] = "如果带电池，电池类型必填.";
        $errorCodeMsg[] = array( 'code'=>'PRO010', 'msg' => "产品带电池，电池类型必填且不能0" );
    }

    if($row['battery_type']=="6"&&$row['battery_detail']==""){
        $error[] = "电池类型为其他时，电池类型补充必填.";
        $errorCodeMsg[] = array( 'code'=>'PRO011', 'msg' => "电池类型为其他时，电池类型补充必填" );
    }

        $productUomArr= Service_Product::getProductUom();
        if( mb_strlen( $row['pu_code'] ) != 3 || !in_array($row['pu_code'],$productUomArr)){
            $error[] = "产品单位字段[UOM]只能填值:001,002,003,004,005,006,007,008,009,010,011,012,013,014,015,016,017,018,019,020,021,022,023,025,026,027,028,029,031,034,037,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,139,140,141,142,163";
            $errorCodeMsg[] = array( 'code'=>'PRO012', 'msg' => "产品计量单位不存在" );
        }

		/*
    	if($row['pu_code_law']=='' || $row['pu_code_law']<=0 || !is_numeric($row['pu_code_law']) ){
    		$error[] = Ec_Lang::getInstance()->getTranslate('LegalUnitMustBeGreaterThan0');//'法定单位必须是大于0的数字';
    	}
		*/
    	return array( 'error' => $error, 'errorCodeMsg' => $errorCodeMsg );
    }



	/**
	 * @createDate 2013-11-13
	 * @author colin-yang
	 * @todo 创建普通产品
	 *
	 */
	public static function createProductForSoap($row,$customer_code,$picUrlArr=array(),$picLinkArr=array()){
	    $result = array("ask"=>0,"message"=>Ec_Lang::getInstance()->getTranslate('ProductCreationFailed'),'actionType'=>'create');
	    $row = self::fomatRow($row);
	    //print_r($row);
	    $error = self::validate_for_soap($row,$customer_code);
	    if(!empty($error['error'])){
	        $result['error'] = $error;
	        return $result;
	    }

	    $db = Common_Common::getAdapter();
	    $db->beginTransaction();
	    try{
	        $con = array('product_sku'=>$row['product_sku'],'customer_code'=>$customer_code);
	        $products = Service_Product::getByCondition($con,"*",0,0,'',0);
	        if(!empty($products)){
	            throw new Exception("sku已存在.", 15 );
	        }
	        //条形码
	        $row['product_barcode'] = $row['product_barcode_type']==1?$row['product_barcode']:($customer_code.'-'.$row['product_sku']);

	        if(empty($row['product_barcode'])){
	            throw new Exception("产品条码为空.");
	        }
	        /*$con = array('product_barcode'=>$row['product_barcode']);
	        $product = Service_Product::getByCondition($con,"*");
	        if(!empty($product)){
	            throw new Exception("产品条码已存在.");
	        }*/

	        $row['product_add_time'] = date("Y-m-d H:i:s");
	        $row['product_update_time'] = date("Y-m-d H:i:s");
	        //$row['product_type']=0;

	        $productRow = array(
	        	'product_sku' => $row['product_sku'],
	        	'customer_code'=>$row['customer_code'],
	        	'customer_id' => $row['customer_id'],
	        	'product_title' => $row['product_title'],
                'product_title_en'=>$row['product_title_en'],
	        	'pu_code' =>$row['pu_code'],
				'currency_code' => 'USD',
	        	'product_weight' => $row['product_weight'],
             'product_length' => isset($row['product_length'])?$row['product_length']:0,
              'product_width' => isset($row['product_width'])?$row['product_width']:0,
              'product_height' => isset($row['product_height'])?$row['product_height']:0,
				'has_invoice' => $row['has_invoice'],
	        	'product_declared_value' =>$row['product_declared_value'],
	        	'product_barcode_type' =>$row['product_barcode_type'],
	        	'product_type' =>0,
				'product_status' =>2,
	        	'product_add_time' =>$row['product_add_time'],
				'product_update_time' =>$row['product_update_time'],
				'is_accessories' =>$row['is_accessories'],
	        	'product_barcode' =>$row['product_barcode'],
	        	'hs_goods_name' => $row['hs_goods_name'],
                'hs_code'=>$row['hs_code'],
                'with_battery'=>$row['with_battery'],
                'battery_type'=>$row['battery_type'],
	        	'battery_detail'=>isset($row['battery_detail'])?$row['battery_detail']:"",
	        );


	        if(!$productId = Service_Product::add($productRow)){
	            throw new Exception("插入产品出错");
	        }
	        $row['product_id'] = $productId;
			/*
	        //添加hs_element_map
	        if(isset($row['hs_element'])){
	        	$hs_elements=$row['hs_element'];
	        	if(!empty($hs_elements)){
	        		foreach($hs_elements as $hsk=>$hs_element){
	        			$hscheck=Service_HsElement::getByField($hs_element['he_id']);
	        			if(!empty($hscheck) && $hscheck['hs_code']==$row['hs_code']){
	        				$hsElementMapRow = array(
	        					'he_id'=>$hs_element['he_id'],
	        					'product_id'=>$productId,
	        					'hem_detail'=>$hs_element['hem_detail'],
	        					'hem_add_time'=>date('Y-m-d H:i:s',time())
	        				);
	        				//print_r($hsElementMapRow);
	        				if(!Service_HsElementMap::add($hsElementMapRow)){
	        					throw new Exception("插入海关编码与产品关系出错");
	        				}
	        			}else{
	        				throw new Exception("海关编码不存在或者错误--{$hs_element['he_id']}");
	        			}
	        		}
	        	}
	        }
			*/
	        //添加hs_uom_map
			/*
	        if(isset($row['hu_id'])){
	        	$huCheck = Service_HsUom::getByField($row['hu_id']);
	        	if(!empty($huCheck) && $huCheck['hs_code']==$row['hs_code']){
	        		$hsUomMapLawRow = array(
	        			'hu_id'=>$row['hu_id'],
	        			'product_id'=>$productId,
	        			'hum_quantity_law'=>$row['pu_code_law'],
	        			'hum_quantity_second'=>$row['pu_code_second'],
	        			'hum_add_time'=>date('Y-m-d H:i:s',time())
	        		);
	        		if(!Service_HsUomMap::add($hsUomMapLawRow)){
	        			throw new Exception("添加海关申报单位和产品关系出错");
	        		}
	        	}else{
	        		throw new Exception("海关申报单位不存在或者出错");
	        	}
	        }
			*/


	        $customer = Service_Customer::getByField($customer_code,'customer_code');
	        $customerId = $customer['customer_id'];
	        /* var_dump($customer);
	        var_dump($customer_code);
	         $db->rollback();
	        exit; */
	        //Service_ProductAttached::addLink($picLinkArr, $productId);
	       // Service_ProductAttached::copyImages($picUrlArr, $customerId, $productId);

	        //料件号
	      	/*$uProduct['goods_id'] = 'BH'.str_pad($productId, 8, '0', STR_PAD_LEFT);
	        Service_Product::update($uProduct, $productId);*/

	        $logRow = array(
	                'product_id' => $productId,
	                'pl_type'=>'0',
	                'customer_id'=>$customerId,
	                'pl_add_time'=>date("Y-m-d H:i:s"),
	        		'pl_statu_pre'=>'1',
	        		'pl_statu_now'=>'1',
	                'pl_note'=>'产品SKU:['.$row['product_sku'].'] 由接口产生',
	                'pl_ip'=>Common_Common::getIP(),
                  'user_id' => -1,
                  'account_id' => Service_Login::getUserId()
	        );
	        //print_r($logRow);exit;
	        //self::writeOrderLog($logRow);

	        if(!Service_ProductLog::add($logRow)){
	        	throw new Exception("添加日志错误");
	        }
            /*if((isset($row['recordInfo'])&&$row['recordInfo']!="")&&(isset($row['isRecord'])&&$row['isRecord']=="1")){
                $recordInfoArr = explode("||",$row['recordInfo']);
                $hsCode = trim($recordInfoArr[1]);
                $hs_condition = array(
                    'hs_code'           => $hsCode,
                    'hs_code_status'    => 1
                );
                $aHsCodes = Service_Hscodes::getByCondition($hs_condition);
                if(empty($aHsCodes)) throw new Exception('海关编码['.$hsCode.']非法');
                $aHsUom = Service_HsUom::getByField($hsCode, 'hs_code',"*");
                if(empty($aHsUom)) {
                    throw new Exception('异常：海关编码['.$hsCode.']没有法定单位');
                }
                $puLawCodeArr1 = explode("(",$recordInfoArr[2]);
                $plcArr1 = explode(")",$puLawCodeArr1[1]);
                $productUom = Service_ProductUom::getByField($aHsUom['pu_code_law'],"pu_code","*");
                if($productUom['pu_name']!=$plcArr1[0]){
                    throw new Exception("海关编码[".$hsCode."]法定单位不是[".$plcArr1[0]."]而是[".$productUom['pu_name']."]");
                }
                if($aHsUom['pu_code_second']!=""){
                    $puLawCodeArr2 = explode("(",$recordInfoArr[4]);
                    $plcArr2 = explode(")",$puLawCodeArr2[1]);
                    $productUom = Service_ProductUom::getByField($aHsUom['pu_code_second'],"pu_code","*");
                    if($productUom['pu_name']!=$plcArr2[0]){
                        throw new Exception("海关编码[".$hsCode."]第二单位不是[".$plcArr1[0]."]而是[".$productUom['pu_name']."]");
                    }
                }
                $hsElementList = Service_HsElement::getByCondition(array('hs_code'=>$hsCode,'he_status'=>1));
                if(empty($hsElementList)) {
                    throw new Exception('异常：海关编码['.$hsCode.']没有申报要素');
                }
                $unicodeSpacePattern = '/\x{200b}/u';
                $specialCharsPattern    = "/[\\\'\":;?~`!@#$^&=)({}\[\]]/";
                $specialCharsPattern_cn = array("！","￥","（","）","【","】","、","；","：","“","”","‘","’","？","《","》","。","…",);
                $elementValueLength = 0;
                $aHsUom = Service_HsUom::getByField($hsCode, 'hs_code');
                for($i=8;$i<count($recordInfoArr)-2;$i+=2){
                    $hsElements = Service_HsElement::getByCondition(array('hs_code'=>$hsCode,'he_status'=>1,'he_name'=>$recordInfoArr[$i]),"*");
                    if(empty($hsElements)){
                        throw new Exception("海关编码[".$hsCode."]没有申报要素:".$recordInfoArr[$i]);
                    }else{
                        $element = preg_replace($unicodeSpacePattern, '', trim($recordInfoArr[$i+1])); //trim($excelRow[$i]);
                        if(empty($element)) throw new Exception("海关编码[".$hsCode."]没有申报要素:".$recordInfoArr[$i]);
                        $elementValueLength= mb_strlen($element,"utf-8");
                        $specialCharsCheck = preg_match($specialCharsPattern, $recordInfoArr[$i+1]);
                        if($specialCharsCheck){
                            throw new Exception("申报要素[".$recordInfoArr[$i]."]元素的内容[".$recordInfoArr[$i+1]."] 包含特殊字符");
                        }
                        foreach($specialCharsPattern_cn as $cn_val){
                            $specialCharsCheck_cn   = mb_strstr($element,$cn_val);
                            if($specialCharsCheck_cn){
                                throw new Exception('海关申报要素['.$recordInfoArr[$i].']元素的内容['.$element."]包含特殊字符");
                            }
                        }
                        if (!Service_GB18030::isValid($element)) {
                          throw new Exception('海关申报要素['.$recordInfoArr[$i].']元素的内容['.$element."]包含非GB18030字符集字符");
                        }
                        if($elementValueLength>200){
                            throw new Exception('海关申报要素['.$recordInfoArr[$i].']元素的内容['.$element.']总长度超过200个字符。');
                        }
                        $elementMap = array();
                        $elementMap['he_id'] = $hsElements[0]['he_id'];
                        $elementMap['product_id'] = $productId;
                        $element = $element;
                        $elementMap['hem_detail'] = strtoupper(trim($element, chr(194).chr(160)));
                        $elementMap['hem_add_time'] = date('Y-m-d H:i:s');
                        Service_HsElementMap::add($elementMap);

                    }

                }
                $hum_quantity_law = trim($recordInfoArr[3]);
                $productUomRow = Service_ProductUom::getByField($aHsUom['pu_code_law'],'pu_code',array('pu_int_request'));
                if( (1==$productUomRow['pu_int_request']) && !ctype_digit(strval($hum_quantity_law))){
                    throw new Exception("法定单位必须是大于0的正整数，您的不正确输入为：".$hum_quantity_law);
                }
                if($hum_quantity_law) {
                    $hum_quantity_law = floor($hum_quantity_law*1000)/1000;
                }
                if($aHsUom['pu_code_second']!='') {
                    $hum_quantity_second = trim($recordInfoArr[5]);
                    if($hum_quantity_second) {
                        $hum_quantity_second = floor($hum_quantity_second*1000)/1000;
                        //检测法定单位是否强制整数
                        $productUomRow = Service_ProductUom::getByField($aHsUom['pu_code_second'],'pu_code',array('pu_int_request'));
                        if( (1==$productUomRow['pu_int_request']) && !ctype_digit(strval($hum_quantity_second))){
                            throw new Exception("法定单位必须是大于0的正整数，您的不正确输入为：".$hum_quantity_second);
                        }
                    }
                }
                $uomsMap = array(
                    'hu_id'=>$aHsUom['hu_id'],
                    'product_id'=>$productId,
                    'hum_quantity_law'=>$hum_quantity_law,
                    'hum_quantity_second'=>trim($recordInfoArr[5]),
                    'hum_add_time'=>date("Y-m-d H:i:s"),
                );
                Service_HsUomMap::add($uomsMap);
                if($recordInfoArr[7]=="1")
                Service_Product::update(array('is_accessories'=>1), $productId);
                //处理产品备案
                self::handleRecord($productId);
            }*/

	        /*  $row['c_app_type'] = 0;
	        $row['c_code'] = $row['product_barcode']; */
	        //self::dataToWarehouse($row);
	        $result['productId'] = $productId;
	        $db->commit();
	        //$db->rollback();
	        $result['ask'] = 1;
	        $result['message'] = "产品创建成功";
	    }catch(Exception $e){
	        $db->rollback();
	        //echo $e->__toString();
	        $result['errorCode'] = $e->getCode();
	        $result['message'] = $e->getMessage();
            $code = $e->getCode();
            if( $code == 15 ) {
                $code = 'PRO0'.$code;
            } else {
                //其他错误都定义成系统错误
                $code = 'PRO001';
            }
            $result['error']['error'] = array( $e->getMessage() );
	        $result['error']['errorCodeMsg'][] = array( 'code' => $code, 'msg' => ( $code == 'PRO001' ?  '系统错误，操作失败' : $e->getMessage() ) );
	    }
	    return $result;
	}
	 /*获得组合产品的申报价值 author colin-yang*/
	 public static function getCombineDeclaredValue($product_id){
	 	  $total = 0;
		  if(!$product_id){ return 0;}
		  $product_array = Service_Product::getByField($product_id,'product_id');
		  if(!$product_array){
		  	return 0;
		  }
		  if($product_array['product_type']!='1'){
		  	return 0;
		  }

		  $son_products = Service_ProductCombineRelation::getByCondition(array('product_id'=>$product_id));
		  if(!$son_products){return 0;}
		  foreach($son_products as $product){
		  			$pcr_product_id = $product['pcr_product_id'];
					if(!$pcr_product_id){continue;}
					$son_product_array = Service_Product::getByField($pcr_product_id,'product_id');
					if(!$son_product_array){continue;}
					$total += $son_product_array['product_declared_value'];
		  }

		  return $total;
	 }//function end

    public static function getProductUom(){
        $uomArr = array(
            '001',//	台
            '002',//	座
            '003',//	辆
            '004',//	艘
            '005',//	架
            '006',//   套
            '007',//	个
            '008',//	只
            '009',//	头
            '010',//	张
            '011',//	件
            '012',//	支
            '013',//	枝
            '014',//	根
            '015',//	条
            '016',//	把
            '017',//	块
            '018',//	卷
            '019',//	副
            '020',//	片
            '021',//	组
            '022',//	份
            '023',//	幅
            '025',//	双
            '026',//	对
            '027',//	棵
            '028',//	株
            '029',//   井
            '031',//	盘
            '034',//	筒
            '037',//	盆
            '120',//	箱
            '121',//	批
            '122',//	罐
            '123',//	桶
            '124',//	扎
            '125',//	包
            '126',//	箩
            '127',//	打
            '128',//	筐
            '129',//	罗
            '130',//	匹
            '131',//	册
            '132',//	本
            '133',//	发
            '134',//	枚
            '135',//	捆
            '136',//	袋
            '139',//	粒
            '140',//	盒
            '141',//	合
            '142',//	瓶
            '163',//	部

        );
        return $uomArr;
    }


}
