<?php
class Service_Product extends Common_Service
{
    /**
     * @var null
     */
    public static $_modelClass = null;
    
    
    /**
     * @var Array
     */
    public static $_batteryTypeArray = array(
        '1'=>'配套电池',
        '2'=>'内置电池',
        '3'=>'纽扣电池',
        '4'=>'锂金属电池',
        '5'=>'离子电池',
        '6'=>'其他',
    );
    
    /**
     * @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);
    }

    /**
     * @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);
    }


    /**
     * @param $value
     * @param string $field
     * @return array
     */
    public static function getByProduct($value, $field = 'product_id')
    {
        $model = self::getModelInstance();
        $result = $model->getByField($value, $field, '*');
        if (!empty($result)) {
            $lang=Ec::getLang(1);
            $result['title']=isset($result['product_title'.$lang])?$result['product_title'.$lang]:'';
            $result['category'] = Service_ProductCategory::getByField($result['pc_id'], 'pc_id');
            $result['category']['name']=isset($result['category']['pc_name'.$lang])?$result['category']['pc_name'.$lang]:'';
            if ($result['pce_id'] != '0') {
                $result['ebayCategory'] = Service_ProductCategoryEbay::getByField($result['pce_id'], 'pce_id');
            }
        }
        return $result;
    }

    /**
     * @param array $where
     * @return array
     */
    public static function listByWhere($where) {
    	$model = self::getModelInstance();
    	return $model->listByWhere($where);
    }

    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();
    }

    /**
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getByCondition($condition, $type, $pageSize, $page, $order);
    }

    /**
     * @param $val
     * @return array
     */
    public static function validator($val)
    {
        $validateArr = $error = array();

        return  Common_Validator::formValidator($validateArr);
    }


    /**
     * @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',
              'E022'=>'product_category_ebay.pce_title',
              'E25'=>'goods_id',
              'E26'=>'has_invoice',
              'E27'=>'hs_code',
              'E28'=>'customer.customer_company_name_like',
              'E29'=>'hs_goods_name',
              'E30'=>'putrec_seqno',
        );
        return $row;
    }

    /**
     * 关联获取跟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);
    }


    /**
     * 关联获取跟PRODUCT有关的海关产品信息查询
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getProductSearchByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getProductSearchByCondition($condition, $type, $pageSize, $page, $order);
    }

    public function recordAgainProcess($product_id){
        $productRow = Service_Product::getByField($product_id,'product_id',"*");
        $productInventory = Service_ProductInventory::getByField($product_id,"product_id","*");
        $result = array('ask'=>'1','message'=>'');
        if($productRow['product_status']=="2"){
            $result['ask'] = "0";
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:产品是草稿状态";
            return $result;
        }
        if(!empty($productInventory)){
            $errorMessage = "";
            if($productInventory['pi_onway']!="0"){
                $errorMessage .="有在途库存;";
            }
            if($productInventory['pi_pending']!="0"){
                $errorMessage .="有到货库存;";
            }
            if($productInventory['pi_sellable']!="0"){
                $errorMessage .="有可用库存;";
            }
            if($productInventory['pi_unsellable']!="0"){
                $errorMessage .="有不良品库存;";
            }
            if($productInventory['pi_reserved']!="0"){
                $errorMessage .="有冻结库存;";
            }
            if($errorMessage!=""){
                $result['ask'] = "0";
                $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:".$errorMessage;
                return $result;
            }
        }
        $existOrder = Service_OrderProduct::checkOrder($product_id);
        if(!empty($existOrder)){
            $result['ask'] = "0";
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:有订单";
            return $result;
        }
        $existReceiving = Service_ReceivingDetail::checkReceiving($product_id);
        if(!empty($existReceiving)){
            $result['ask'] = "0";
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:有ASN";
            return $result;
        }
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try{
            Service_ProductGoods::delete($product_id,'product_id');
            //Service_HsElementMap::delete($product_id,"product_id");
            //Service_HsUomMap::delete($product_id,"product_id");
            $updateProduct = array(
                'goods_id_old'=>$productRow['goods_id'],
                'product_status'=>2,
                'have_asn'=>'0',
                'product_update_time'=>date("Y-m-d H:i:s"),
            );
            Service_Product::update($updateProduct,$product_id,'product_id');
            $userAuth = new Zend_Session_Namespace('userAuthorization');
            $user = Service_User::getByField($userAuth->userId,"user_id","*");
            $log = array(
                'product_id'=>$product_id,
                'pl_type'=>'1',
                'user_id'=>$userAuth->userId,
                'customer_id'=>$productRow['customer_id'],
                'pl_statu_pre'=>$productRow['product_status'],
                'pl_statu_now'=>'2',
                'pl_note'=>"[".$user['user_name']."]重新备案",
                'pl_add_time'=>date("Y-m-d H:i:s"),
                'pl_ip'=>Common_Common::getIP(),
            );
            Service_ProductLog::add($log);
            $db->commit();
            $result['ask'] = 1;
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案成功";
        }catch (Exception $e){
            $result['ask'] = '0';
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:".$e->getMessage();
        }
        return $result;
    }

    public function batchDeclaredProcess($product_id,$declared_value){
        $productRow = Service_Product::getByField($product_id,'product_id',"*");
        $productInventory = Service_ProductInventory::getByField($product_id,"product_id","*");
        $result = array('ask'=>'1','message'=>'');
        if($productRow['product_status']=="2"){
            $result['ask'] = "0";
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:产品是草稿状态";
            return $result;
        }
        if(!empty($productInventory)){
            $errorMessage = "";
            if($productInventory['pi_onway']!="0"){
                $errorMessage .="有在途库存;";
            }
            if($productInventory['pi_pending']!="0"){
                $errorMessage .="有到货库存;";
            }
            if($productInventory['pi_sellable']!="0"){
                $errorMessage .="有可用库存;";
            }
            if($productInventory['pi_unsellable']!="0"){
                $errorMessage .="有不良品库存;";
            }
            if($productInventory['pi_reserved']!="0"){
                $errorMessage .="有冻结库存;";
            }
            if($errorMessage!=""){
                $result['ask'] = "0";
                $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:".$errorMessage;
                return $result;
            }
        }
        $existOrder = Service_OrderProduct::checkOrder($product_id);
        if(!empty($existOrder)){
            $result['ask'] = "0";
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:有订单";
            return $result;
        }
        $existReceiving = Service_ReceivingDetail::checkReceiving($product_id);
        if(!empty($existReceiving)){
            $result['ask'] = "0";
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:有ASN";
            return $result;
        }
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try{
            Service_ProductGoods::delete($product_id,'product_id');
            Service_HsElementMap::delete($product_id,"product_id");
            Service_HsUomMap::delete($product_id,"product_id");
            $updateProduct = array(
                'product_status'=>2,
                'have_asn'=>'0',
                'product_update_time'=>date("Y-m-d H:i:s"),
            );
            Service_Product::update($updateProduct,$product_id,'product_id');
            $userAuth = new Zend_Session_Namespace('userAuthorization');
            $user = Service_User::getByField($userAuth->userId,"user_id","*");
            $log = array(
                'product_id'=>$product_id,
                'pl_type'=>'1',
                'user_id'=>$userAuth->userId,
                'customer_id'=>$productRow['customer_id'],
                'pl_statu_pre'=>$productRow['product_status'],
                'pl_statu_now'=>'2',
                'pl_note'=>"[".$user['user_name']."]修改申报价值",
                'pl_add_time'=>date("Y-m-d H:i:s"),
                'pl_ip'=>Common_Common::getIP(),
            );
            Service_ProductLog::add($log);
            $db->commit();
            $result['ask'] = 1;
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案成功";
        }catch (Exception $e){
            $result['ask'] = '0';
            $result['message'] = "产品[".$productRow['product_barcode']."]重新备案失败:".$e->getMessage();
        }
        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;
                }
            }
        }
        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);
    }

    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'];
         } */
        //有无发票
        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) {
            if( $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 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);
    }

    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;
    }
    /**
     * 删除产品
     *
     * @param integer $productId    产品ID
     * @return array
     */
    public static function remove($productId) {
      $response  = array('valid' => FALSE, 'sku' => '', 'message' => '');
      $productId = (int) $productId;
      $db        = Common_Common::getAdapter();
      $userAuth  = new Zend_Session_Namespace('userAuthorization');

      $db->beginTransaction();

      try {
        $product = self::getByField($productId, 'product_id');

        if (empty($product)) {
          $response['sku'] = 'EMPTY SKU';
          throw new Exception('找不到产品信息');
        }

        $response['sku'] = $product['product_sku'];

        /*if (1 === (int) $product['product_type']) { // 组合产品
          $orderCount = Service_OrderProduct::getByCondition(array('product_id' => $productId), 'count(*)');
          $combine = Service_ProductCombineRelation::getByCondition(array('product_id' => $productId));

          if ($orderCount > 0) {
              throw new Exception('组合产品，不能删除');
          }

          foreach ($combine as $item) {
            $subProduct = Service_Product::getByField($item['pcr_product_id'], 'product_id');
            self::doRemove($subProduct, $item['product_id']);
          }

          self::delete($productId, 'product_id');
          Service_ProductCombineRelation::delete($productId, 'product_id');
        }
        else {*/
          self::doRemove($product);
        /*}*/

        $response['valid']   = TRUE;
        $response['message'] = '操作成功';

        $db->commit();
      }
      catch (Exception $e) {
        $db->rollBack();
        $response['message'] = $e->getMessage();
      }

      return $response;
    }
    /**
     * 删除产品信息
     *
     * @param integer $product    产品信息
     * @param integer $pcId       组合产品ID
     * @return void
     */
    private static function doRemove($product, $pcId = 0) {
      if (1 === (int) $product['product_type']) {
        throw new Exception('不支持组合产品');
      }

      if (2 !== (int) $product['product_status']) {
        if ($pcId > 0) {
          throw new Exception('子产品[' . $product['product_sku'] . ']不是草稿状态，不能删除');
        }
        else {
          throw new Exception('不是草稿状态，不能删除');
        }
      }

      $productId = $product['product_id'];
      $asnCount  = Service_ReceivingDetail::getByCondition(array('product_id' => $productId), 'count(*)');

      if ($asnCount > 0) {
        if ($pcId > 0) {
          throw new Exception('子产品[' . $product['product_sku'] . ']有收货单，不能删除');
        }
        else {
          throw new Exception('有收货单，不能删除');
        }
      }

      $orderCount = Service_OrderProduct::getByCondition(array('product_id' => $productId), 'count(*)');

      if ($orderCount > 0) {
        if ($pcId > 0) {
          throw new Exception('子产品[' . $product['product_sku'] . ']有订单，不能删除');
        }
        else {
          throw new Exception('有订单，不能删除');
        }
      }

      $combine = Service_ProductCombineRelation::getByCondition(array('pcr_product_id' => $productId));

      if ($combine) {
        foreach ($combine as $item) {
          if ((int) $pcId !== (int) $item['product_id']) {
            if ($pcId > 0) {
              throw new Exception('子产品[' . $product['product_sku'] . ']有其他组合产品，不能删除');
            }
            else {
              throw new Exception('有组合产品，不能删除');
            }
          }
        }
      }
      $po_order = Service_PoOrderBody::getByCondition(array('product_id'=>$productId),'count(*)');
      if($po_order > 0){
        if($pcId > 0){
          throw new Exception('子产品[' . $product['product_sku'] . ']有po订单，不能删除');      
        }else{
          throw new Exception('有po订单，不能删除');
          
        }
      }
      $purchase_order = Service_PurchaseOrderBody::getByCondition(array('product_id'=>$productId),'count(*)');
      if($purchase_order > 0){
        if($pcId > 0){
          throw new Exception('子产品[' . $product['product_sku'] . ']有采购订单，不能删除');      
        }else{
          throw new Exception('有采购单，不能删除');
          
        }
      }


      self::delete($productId, 'product_id');
      Service_ProductLog::delete($productId, 'product_id');
      Service_ProductAttached::delete($productId, 'product_id');
      Service_ProductAttribute::delete($productId, 'product_id');
    }
    public static function getXLSData($uploadFile,$field){
        $customerAuth = new Zend_Session_Namespace("customerAuth");

        $customer   = $customerAuth->data;
        $customerId = $customer['id'];
        //print_r($customer);
        //exit('sss');
        $path = APPLICATION_PATH.'/../data/orderupload/';
        $path.= $customerId;
        if(!file_exists($path)){
            if(!mkdir($path,0700,true)){
                $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('上传目录不存在创建文件目录失败'));
                return $result;
            }
        }
        $config = array();
        $config['upload_path']      = $path;
        $config['allowed_types']    = 'xls|xlsx|csv';
        $config['max_size']         = '10000';
        $config['encrypt_name']     = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if ( ! $upload->do_upload($_FILES,$field) ){
            $result['ask'] = '0';
            $result['message'] = '上传文件失败';
            $result['error'] =  $upload->display_errors();
            return $result;
            exit;
        }

        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if(empty($resultArray) || empty($full_path)){
            $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('数据不存在'));
            return $result;
            exit;
        }
        switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":
                $resultArray = Common_Upload::readEXCEL($full_path);
                break;
            case ".csv":
                $resultArray = Common_Upload::readCSV($full_path);
                break;
            default:
                $resultArray = array();
                break;
        }
        if(empty($resultArray) || !is_array($resultArray)){
            $result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
            //echo json_encode($result);
            //exit;
        }
        @unlink($full_path);
        return $resultArray;
    }
    /**
     * @todo 修改所有料号商品信息
     */
    public static function modifyGoodsInfo($row){
        /**
         * 1）相同料号申报要素全改
        2）相同编码，相同品名，法定第一数量，法定第二数量。更改。
        3）海关编码改了怎么办？（编码不能改，改编码必须打回，生成了新的料号）
        4）重塑product_goods表
        5）修改产品名称只改这一个sku的，修改产品名称只改这一个sku的。
         */
        $result = array(
            'state'=>0,
            'message'=>''
        );
        try{

            $productId = $row['product_id'];
            $productSku = $row['product_sku'];
            $productTitle = $row['product_title'];
            $productWeight = $row['product_weight'];
            $hsCode = $row['hs_code'];
            $puCode = $row['pu_code'];
            $humQantityLaw = $row['hum_quantity_law'];
            $humQuantitySecond = $row['hum_quantity_second'];
            $productNetWeight = $row['product_net_weight'];
            $hsGoodsName = $row['hs_goods_name'];
            $heDetail = $row['heDetail'];
            $productInfo = $row['productInfo'];

            if($productInfo['goods_id']!=''){
                /*$row = array(
                    'product_id'=>$productId,
                    'product_sku'=>$productSku,
                    'product_title'=>$productTitle,
                    'product_weight'=>$productWeight,
                    'hs_code'=>$hsCode,
                    'pu_code'=>$puCode,
                    'hum_quantity_law'=>$humQantityLaw,
                    'hum_quantity_second'=>$humQuantitySecond,
                    'product_net_weight'=>$productNetWeight,
                    'hs_goods_name'=>$hsGoodsName,
                    'heDetail'=>$heDetail,
                );*/

                //修改全部料号的申报要素信息
                $goodsCondition = array(
                    'goods_id'=>$productInfo['goods_id'],
                    'product_id_not'=>$productId,
                );
                $goodsLists = Service_Product::getByCondition($goodsCondition,"*");
                if(!empty($goodsLists)){
                    foreach ($goodsLists as $k=>$good){
                        $hsUomMap = Service_HsUomMap::getByField($good['product_id'], 'product_id');
                        $hsUom = Service_HsUom::getByCondition(array(
                            'hs_code' => $hsCode,
                            'hu_status' => 1,
                        ));
                        $hsUom = $hsUom[0];

                        $updateFiled = array(
                            'hs_code' => $hsCode,
                            'product_weight' => $productWeight,
                            'pu_code' => $puCode,
                            'hum_quantity_law' => $humQantityLaw,
                            'hum_quantity_second' => $humQuantitySecond,
                            'hs_goods_name' => $hsGoodsName,
                        );
                        $originalFiled = array(
                            'hs_code' => $good['hs_code'],
                            'product_weight' => $good['product_weight'],
                            'pu_code' => $good['pu_code'],
                            'hum_quantity_law' => $hsUomMap['hum_quantity_law'],
                            'hum_quantity_second' => $hsUomMap['hum_quantity_second'],
                            'hs_goods_name' => $good['hs_goods_name'],
                        );

                        $updateFiledName = array(
                            'hs_code' => '海关编码',
                            'product_weight' => '产品重量',
                            'pu_code' => '申报单位',
                            'hum_quantity_law' => '法一数量',
                            'hum_quantity_second' => '法二数量',
                            'product_net_weight' => '产品净重',
                            'hs_goods_name' => '海关品名',
                        );

                        $log = "修改sku{$productSku}信息,连带把这个sku相同料件号的申报要素信息也改了";
                        foreach ($originalFiled as $key => $value) {
                            if ($updateFiled[$key] != $value) {
                                $log .= $updateFiledName[$key] . ':' . $value . '->' . $updateFiled[$key];
                            }
                        }
                        $updateProduct = array(
                            'hs_code' => $hsCode,
                            'product_weight' => $productWeight,
                            'pu_code' => $puCode,
                            'product_net_weight' => $productNetWeight,
                            'hs_goods_name' => $hsGoodsName,
                        );
                        $updateLawQuantity = array();
                        if ($originalFiled['hum_quantity_law'] != $updateFiled['hum_quantity_law']) {
                            $updateLawQuantity['hum_quantity_law'] = $updateFiled['hum_quantity_law'];
                        }
                        if ($originalFiled['hum_quantity_second'] != $updateFiled['hum_quantity_second']) {
                            $updateLawQuantity['hum_quantity_second'] = $updateFiled['hum_quantity_second'];
                        }
                        if ($good['hs_code'] != $hsUom['hs_code']) {
                            $updateLawQuantity['hu_id'] = $hsUom['hu_id'];
                        }
                        if (!empty($updateLawQuantity)) {
                            Service_HsUomMap::update($updateLawQuantity, $good['product_id'], 'product_id');
                        }
                        if ($updateProduct['hs_code'] != $productInfo['hs_code']){
                            $log .= '修改海关编码：' . $good['hs_code'] . '->' . $updateProduct['hs_code'];
                        }
                        Service_HsElementMap::delete($good['product_id'], 'product_id');
                        foreach ($heDetail as $key => $detail) {
                            $addHsElementMap = array(
                                'product_id' => $good['product_id'],
                                'hem_detail' => $detail,
                                'he_id' => $key,
                                'hem_add_time' => date("Y-m-d H:i:s"),
                            );
                            Service_HsElementMap::add($addHsElementMap);
                        }

                        Service_Product::update($updateProduct, $good['product_id']);
                        $logRow = array(
                            'product_id' => $good['product_id'],
                            'pl_type' => 0,
                            'pl_ip' => Common_Common::getRealIp(),
                            'user_id' => Service_User::getUserId(),
                            'pl_statu_pre' => $productInfo['product_status'],
                            'pl_statu_now' => $productInfo['product_status'],
                            'pl_note' => $log,
                            'pl_add_time' => date("Y-m-d H:i:s"),
                        );
                        Service_ProductLog::add($logRow);
                    }
                }else{

                }

                $result['state'] = 1;
            }

        }catch (Exception $e){
            $result['message'] = $e->getMessage();
        }
        return $result;
    }



}