<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 16-10-19
 * Time: 下午5:50
 * To change this template use File | Settings | File Templates.
 */
class Product_ProductInfoController  extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "product/views/product/";
        $this->serviceClass = new Service_Product();
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $this->user_id = $userAuth->userId;
    }

    public function listAction(){
        $status=Service_ProductProcess::getProductStatus();
        $receiving=Service_ProductProcess::getProductReceivingStatus();
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);
            $isSellable = trim($this->_request->getParam('pi_sellable', ''));
            $warehoseId = trim($this->_request->getParam('warehouse_id', ''));

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();
         

            $condition = $this->serviceClass->getMatchFields($params);

            if ('largeZero' === $isSellable && '' !== $warehoseId) {
                $condition['pi_sellable'] = 'largeZero';
                $condition['warehouse_id'] = $warehoseId;
            }
            $condition['dateFor'] = isset($params['dateFor'])?$params['dateFor']:'';
            $condition['dateTo'] = isset($params['dateTo'])?$params['dateTo']:'';
            $user = Service_User::getByField($this->user_id,"user_id","*");
            if($user['customer_code']!=""){
                $customerCodeArr = explode(";",$user['customer_code']);
                $condition['customerCodeArr'] = $customerCodeArr;
            }
            //echo "<pre>";
            //var_dump($condition);
            //echo "</pre>";
            $count = $this->serviceClass->getAllByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    'product_sku',
                    'customer_code',
                    'product_title_en',
                    'product_title',
                    'product_status',
                    'product_receive_status',
                    'product_weight',
                    'pc_id',
                    'product_id',
                    'pce_title',
                    'product_category_ebay.pce_title',
                    'product_barcode',
                    'customer_id',
                    'product_type',
                    'goods_id',
                    'hs_code',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);

                $rows = $this->serviceClass->getAllByCondition($condition,$showFields, $pageSize, $page, array('product.product_id desc'));
                foreach($rows as $key=>$value){
                    if($value['E3']==""){
                        $customer = Service_Customer::getByField($value['E4'],'customer_id',"*");
                        $rows[$key]['E3'] = $customer['customer_code'];
                    }
                    $productCategory = Service_ProductCategory::getByField($value['E21'],'pc_id',"*");
                    $rows[$key]['pc_name'] = isset($productCategory['pc_name'])?$productCategory['pc_name']:"";
                }
                //print_r($rows);die();
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['status'] = $status;
                $return['receiving'] = $receiving;
                $return['message'] = "";
                $userRight = Service_UserRight::getByField("/product/product/beian","ur_url","*");
                $urmCondition = array(
                    'ur_id'=>$userRight['ur_id'],
                    'user_id'=>$this->user_id
                );
                $userRightMap = Service_UserRightMap::getByCondition($urmCondition,"count(*)");
              
                if($userRightMap){
                    $return['beianAuth'] = 1;
                }else{
                    $return['beianAuth'] = 0;
                }
            }
            die(Zend_Json::encode($return));
        }
        //var_dump($return);die;
        $this->view->status=$status;
        $this->view->receiving=$receiving;
        echo Ec::renderTpl($this->tplDirectory . "product_info_index.tpl", 'layout');
    }

    /*产品详细*/
    public function detailAction(){
        $skuid = $this->_request->getParam("skuid","");
        $productRow= $this->serviceClass->getByField($skuid, 'product_id');
        //$pUm = Service_ProductUom::getByField($productRow['pu_code'],'pu_code',"*");
        $productCategory  = Service_ProductCategory::getByField($productRow['pc_id'],'pc_id',"*");
        $productRow['pc_name'] = $productCategory['pc_name'];
        // $country = Service_Country::getByField($productRow['country_code_of_origin'],"country_code","*");
        // $productRow['country_name'] = $country['country_name'];
        //$productRow['pu_name'] = $pUm['pu_name'];
        if(empty($productRow['pu_code'])){ $productRow['pu_code'] = '007';}
        if($productRow['pu_code']){
            $pUm = Service_ProductUom::getByField($productRow['pu_code'],'pu_code',"*");
            $productRow['pu_name'] = $pUm['pu_name'];
        }else{
            $productRow['pu_name'] = "";
        }

        // 供应商信息
        if ($productRow['distributor_id']) {
            $productRow['distributor'] = Service_Distributor::getByPrimaryKey($productRow['distributor_id']);
        }

        $this->view->product = $productRow;//产品日记
        $logService = new Service_ProductLog();
        $logs = $logService->getByCondition(array('product_id'=>$skuid),"*");
        foreach($logs as $key=>$value){
            $customerService = new Service_Customer();
            $c = $customerService->getByField($value['customer_id'],"customer_id","*");
            $logs[$key]['customer_code'] = $c['customer_code'];
            if($value['user_id']=="-1"){
                if($value['account_id']=="0"){
                    $logs[$key]['operater'] = $c['customer_code'];
                }else{
                    $account = Service_Account::getByField($value['account_id'],"account_id","*");
                    $logs[$key]['operater'] = $account['account_name'];
                }
            }else{
                $user = Service_User::getByField($value['user_id'],'user_id',"*");
                $logs[$key]['operater'] = $user['user_name'];
            }
        }
        $this->view->logs = $logs;//产品日记

        $productInventory = new Service_ProductInventory();
        $inventory = $productInventory->getByCondition(array('product_id'=>$skuid),"*");
        foreach($inventory as $key=>$value){
            $warehouse = new Service_Warehouse();
            $w = $warehouse->getByField($value['warehouse_id'],"warehouse_id","*");
            $inventory[$key]['warehouse_code'] = $w['warehouse_code'];
        }
        $this->view->productInventory = $inventory;//产品库存

        $opService = new Service_OrderProduct();
        $orderProduct = $opService->getByCondition(array('product_id'=>$skuid),"*");
        $this->view->orderProduct = $orderProduct;//产品订单

        $oaService = new Service_ReceivingDetail();
        $productAsn = $oaService->getByCondition(array('product_id'=>$skuid),"*");
        $this->view->productAsn = $productAsn;//产品ASN
        $swapOrderDetail=new Service_SwapOrderDetail();
        $swapOrderout = $swapOrderDetail->getByCondition(array('product_id'=>$skuid),"*");
        $swapOrderin = Service_SwapOrderDetail::getByCondition(array('to_product_id'=>$skuid),"*");
        $this->view->swapOrderout = $swapOrderout;//易货单
        $this->view->swapOrderin = $swapOrderin;
        $inventoryBatchService = new Service_InventoryBatch();
        $inventoryBatchList = $inventoryBatchService->getByCondition(array('product_id'=>$skuid),"*");
        $this->view->inventoryBatchList = $inventoryBatchList;//产品批次库存

        $hsElementMap = Service_HsElementMap::getByCondition(array('product_id'=>$skuid),"*");
        if(!empty($hsElementMap)){
            foreach($hsElementMap as $k=>$v){
                $HE = Service_HsElement::getByField($v['he_id'],"he_id","*");
                $hsElementMap[$k]['HE'] = $HE;
                $HUM = Service_HsUomMap::getByField($v['product_id'],"product_id","*");
                $hsElementMap[$k]['HUM'] = $HUM;
                $HU = Service_HsUom::getByField($HUM['hu_id'],"hu_id","*");
                $productUom = Service_ProductUom::getByField($HU['pu_code_law'],"pu_code","*");
                $HU['pu_name'] = $productUom['pu_name'];
                $productUomSecond = Service_ProductUom::getByField($HU['pu_code_second'],"pu_code","*");
                $HU['pu_name_second'] = $productUomSecond['pu_name'];
                $hsElementMap[$k]['HU'] = $HU;
            }
        }else{
            $row = array();
            $HUM = Service_HsUomMap::getByField($skuid,"product_id","*");
            if($HUM){
                $row['HUM'] =  $HUM;
                $row['HE']['hs_code'] =  $productRow['hs_code'];
                $HU = Service_HsUom::getByField($HUM['hu_id'],"hu_id","*");
                $productUom = Service_ProductUom::getByField($HU['pu_code_law'],"pu_code","*");
                $HU['pu_name'] = $productUom['pu_name'];
                $productUomSecond = Service_ProductUom::getByField($HU['pu_code_second'],"pu_code","*");
                $HU['pu_name_second'] = $productUomSecond['pu_name'];
                $row['HU'] = $HU;

            }

            $hsElementMap[] = $row;
        }
        $userRight = Service_UserRight::getByField("/product/product/change","ur_url","*");
        $urmCondition = array(
            'ur_id'=>$userRight['ur_id'],
            'user_id'=>$this->user_id
        );
        $userRightMap = Service_UserRightMap::getByCondition($urmCondition,"count(*)");
        $userEditPg = Service_UserRight::getByField("/product/product/editpg","ur_url","*");
        $this->view->userEditPg = Service_UserRightMap::getByCondition(array( 'ur_id'=>$userEditPg['ur_id'],),"count(*)");
        $this->view->changeAuth = $userRightMap;
        $this->view->hsElementMap = $hsElementMap;

        echo Ec::renderTpl($this->tplDirectory . "product-detail-finance.tpl", 'layout');
    }

    public function exportProductAction() {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $file   = 'product-' . date('YmdHis');
        /*header('Content-Type: application/vnd.ms-excel;charset=gbk');
        header("Content-Disposition: attachment;filename={$file}");
        header('Cache-Control: max-age=0');*/
        require_once("PHPExcel.php");
        require_once("PHPExcel/Reader/Excel2007.php");
        require_once("PHPExcel/Reader/Excel5.php");
        require_once ('PHPExcel/IOFactory.php');

        $objExcel = new PHPExcel();
        $objProps = $objExcel->getProperties();
        $objProps->setCreator('EC');
        $objProps->setTitle('Template');
        $objExcel->setActiveSheetIndex(0);

        $objActSheet = $objExcel->getActiveSheet();

        $objActSheet->getColumnDimension('A')->setWidth(25);
        $objActSheet->getColumnDimension('B')->setWidth(20);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(25);
        $objActSheet->getColumnDimension('E')->setWidth(10);
        $objActSheet->getColumnDimension('F')->setWidth(10);
        $objActSheet->getColumnDimension('G')->setWidth(10);

        $objActSheet->setCellValue('A1','客户代码');
        $objActSheet->setCellValue('B1','产品SKU');
        $objActSheet->setCellValue('C1','产品条码');
        $objActSheet->setCellValue('D1','产品名称');
        $objActSheet->setCellValue("E1",'申报价值');
        $objActSheet->setCellValue('F1','申报币种');
        $objActSheet->setCellValue('G1','可用数量');


        //$exportData[0] = array('客户代码','产品SKU','产品条码','产品名称','申报价值','申报币种','可用数量');

        $params        = $this->getRequest()->getParams();
        if($params['type'] == '1'){
            $productSku    = isset($params['E1'])  ? trim($params['E1'])  : '';
            $productBracode  = isset($params['E2'])  ? trim($params['E2'])  : '';
            $customerCode  = isset($params['E3'])  ? trim($params['E3'])  : '';


            $condition     = array(
                'product_type' => '0', // 只能导出普通产品
            );

            if ('' !== $productSku) {
                $condition['product_sku'] = $productSku;
            }

            if ('' !== $customerCode) {
                $condition['customer_code'] = $customerCode;
            }

            if ('' !== $productBracode) {
                $condition['product_barcode'] = (string) $productBracode;
            }

            $condition['dateFor'] = isset($params["dateFor"])? trim($params['dateFor']):"";
            $condition['dateTo'] = isset($params["dateTo"])? trim($params['dateTo']):"";
            $user = Service_User::getByField($this->user_id,"user_id","*");
            if($user['customer_code']!=""){
                $customerCodeArr = explode(";",$user['customer_code']);
                $condition['customerCodeArr'] = $customerCodeArr;
            }
        }else{
            if ($params['pid']) {
                $condition['product_id_array'] = explode('|', $params['pid']);
            }else{
                //echo Common_Export::exportCsvForNotKey($exportData);
                die("无数据");
            }
        }


        $count = Service_Product::getByCondition($condition , 'count(*)');
        if(!$count){
            //echo Common_Export::exportCsvForNotKey($exportData);
            die("无数据");
        }
        $index = 1;
        $pagesize = 20;
        $pages = ceil($count / $pagesize);

        $index = 2;
        for ($page=1; $page <= $pages; $page++) {
            $proudctRows = Service_Product::getByCondition($condition , '*' , $pagesize ,$page);
            foreach ($proudctRows as $key => $value) {
                $pi = Service_ProductInventory::getByField($value['product_id'],"product_id","*");
                $piSellable = isset($pi['pi_sellable'])?$pi['pi_sellable']:"0";

                $exportData[$index]	=	array( $value['customer_code'] , $value['product_sku'], $value['product_barcode'] , $value['product_title'] , $value['product_declared_value'] , $value['currency_code'] ,$piSellable);

                $objActSheet->setCellValue('A'.$index,$value['customer_code']);
                $objActSheet->setCellValueExplicit('B'.$index,$value['product_sku'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit('C'.$index,$value['product_barcode'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValue('D'.$index, $value['product_title']);
                $objActSheet->setCellValue("E".$index,$value['product_declared_value']);
                $objActSheet->setCellValue('F'.$index,$value['currency_code']);
                $objActSheet->setCellValue('G'.$index,$piSellable);

                $index++;
            }

        }

        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="' . $file . '.xls');
        header("Content-Disposition:inline;filename=" . $file . '.xls');
        $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
        $objWriter->save('php://output');

    }
    /**
     * Note:已备案商品修改页面
     * User: Yao
     * Date: 2019/6/17
     * Time: 10:22
     */
    public function editAction() {
        $productUom = Service_ProductUom::getAll();
        $uom = array();
        if ($productUom) {
            foreach ($productUom as $item) {
                $uom[$item['pu_code']] = $item['pu_name'];
            }
        }
        $country = Service_Country::getAll();
        $this->view->country = $country;
        $this->view->uom = $uom;
        $this->view->uomObj = json_encode($uom);
        echo Ec::renderTpl($this->tplDirectory . 'product_edit.tpl', 'layout');
    }
    public function getProductInfoAction() {
        $response = array('status' => 0, 'message' => '非法请求', 'data' => array());
        if ($this->getRequest()->isPost()) {
            $productSku = trim($this->getRequest()->getPost('product_sku', ''));
            $customerCode = trim($this->getRequest()->getPost('customer_code'));
            if ('' === $productSku) {
                $response['message'] = '产品sku不能为空';

                exit(json_encode($response));
            }

            $product = Service_Product::getByCondition(array('product_sku' => $productSku, 'customer_code' => $customerCode));
            if (empty($product)) {
                $response['message'] = '没有找到产品信息';

                exit(json_encode($response));
            }
            if (count($product) > 1) {
                if ($customerCode) {
                    $response['message'] = '客户含有重复sku，无法操作';
                } else {
                    $response['message'] = 'sku有多条商品信息，请输入客户代码';
                }
                exit(json_encode($response));
            }
            $product = $product[0];
            if (0 !== (int)$product['product_status'] && 1 !== (int)$product['product_status'] && 3 !== (int)$product['product_status']) {
                $response['message'] = '产品不是已提交、备案中、已备案状态';
                exit(json_encode($response));
            }
            $hsUomMap = Service_HsUomMap::getByField($product['product_id'], 'product_id');
            if (empty($hsUomMap)) {
                $response['message'] = '产品缺乏法定数量信息';
                exit(json_encode($response));
            }

            $hsUom = Service_HsUom::getByCondition(array(
                'hs_code' => $product['hs_code'],
                'hu_status' => 1,
            ));
            if (empty($hsUom)) {
                $response['message'] = '产品缺乏海关申报单位信息';
                exit(json_encode($response));
            }
            $hsUom = $hsUom[0];
            $hsElement = Service_HsElement::getByCondition(array(
                'hs_code' => $product['hs_code'],
            ), '*', 0, 0, array('he_sort asc'));
            $heElementList = array();
            foreach ($hsElement as $elemnt) {
                $productElement = Service_HsElementMap::getByCondition(array(
                    'product_id' => $product['product_id'],
                    'he_id' => $elemnt['he_id'],
                ));
                if (!empty($productElement)) {
                    $heElementList[] = array_merge($elemnt, $productElement[0]);
                } else {
                    $elemnt['hem_detail'] = '';
                    $heElementList[] = $elemnt;
                }
            }
            // $hsElement = Service_HsElementMap::getLeftJoinHsElementByCondition(array('product_id'=>$product['product_id']));
            $response['status'] = 1;
            $response['message'] = '查询验证通过';
            $response['data'] = array(
                'product_id' => $product['product_id'],
                'goods_id' => $product['goods_id'],
                'hs_code' => $product['hs_code'],
                'hs_elemnt' => $heElementList,
                'customer_code' => $product['customer_code'],
                //'country_code_of_origin' => $product['country_code_of_origin'],
                'product_sku' => $product['product_sku'],
                'product_weight' => $product['product_weight'],
                'product_net_weight' => $product['product_net_weight'],
                'pu_code' => $product['pu_code'],
                'pu_code_law' => $hsUom['pu_code_law'],
                'pu_code_second' => $hsUom['pu_code_second'],
                'hum_quantity_law' => $hsUomMap['hum_quantity_law'],
                'hum_quantity_second' => $hsUomMap['hum_quantity_second'],
                'product_title' => $product['product_title'],
                'hs_goods_name' => $product['hs_goods_name'],
                'gift_flag' =>$product['gift_flag'],
                'special'   =>$product['special']
            );
        }
        exit(json_encode($response));
    }
    /**
     * Note:已备案商品信息修改
     * User: Yao
     * Date: 2019/6/17
     * Time: 10:20
     * 增加修改product_goods表功能
     */
    public function updateAction() {
        $return = array(
            'state' => 0,
            'message' => 'fail',
        );
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            if ($this->_request->isPost()) {
                $productId = $this->_request->getParam('product_id', '');
                $productSku = $this->_request->getParam('product_sku', '');
                $productTitle = $this->_request->getParam('product_title', '');
                $productWeight = $this->_request->getParam('product_weight', '');
                $hsCode = trim($this->_request->getParam('hs_code', ''));
                //$countryCodeOfOriginal = $this->_request->getParam('country_code_of_origin', '');
                $puCode = $this->_request->getParam('pu_code', '');
                $humQantityLaw = $this->_request->getParam('hum_quantity_law', '');
                $humQuantitySecond = $this->_request->getParam('hum_quantity_second', '');
                $heDetail = $this->_request->getParam('he_detail', '');
                $productNetWeight = $this->_request->getParam('product_net_weight', '');
                $hsGoodsName = trim($this->_request->getParam('hs_goods_name', ''));
                $special = trim($this->_request->getParam('special', ''));
                $log = '';
                if (empty($productId)) {
                    throw new Exception('参数错误');
                }
                $productInfo = Service_Product::getByField($productId);
                if (empty($productInfo)) {
                    throw new Exception('参数错误');
                }
                if (empty($productTitle) || $productTitle == '') {
                    throw new Exception('产品名称不能为空');
                }
                if (strlen($productTitle) > 255) {
                    throw new Exception('产品名称不能大于255个字符');
                }
                if (empty($productSku)) {
                    throw new Exception('产品sku不能为空');
                }
                if (empty($productWeight) || !is_numeric($productWeight) || $productWeight <= 0) {
                    throw new Exception('产品重量必须是正数');
                }
                if ($productNetWeight > $productWeight) {
                    throw new Exception('产品净重不能大于产品重量');
                }
                if (empty($productNetWeight) || !is_numeric($productNetWeight) || $productNetWeight <= 0) {
                    throw new Exception('产品净重必须是正数');
                }
                if (empty($hsGoodsName)) {
                    throw new Exception('海关品名不能为空');
                } elseif (!preg_match("/[\x{4e00}-\x{9fa5}]+/u", $hsGoodsName)) {
                    throw new Exception("海关品名必须包含中文字符");
                }

                $skuList = Service_Product::getByCondition(array('product_sku' => $productSku, 'customer_code' => $productInfo['customer_code']));
                $checkExit = array();
                foreach ($skuList as $p) {
                    if ($p['product_id'] != $productInfo['product_id'] && $p['product_sku'] == $productSku) {
                        $checkExit = $p;
                        break;
                    }
                }
                if (!empty($checkExit)) {
                    throw new Exception('已存在相同sku商品');
                }
                $hsCodeInfo = Service_Hscodes::getByField($hsCode, 'hs_code');
                if (empty($hsCodeInfo)) {
                    throw new Exception('海关编码不存在');
                }
                if ($hsCodeInfo['is_positive'] != 1) {
                    //throw new Exception('海关编码不在正面清单内');
                }
                $productUom = Service_ProductUom::getByField($puCode, 'pu_code');
                $hsUomMap = Service_HsUomMap::getByField($productInfo['product_id'], 'product_id');
                $hsUom = Service_HsUom::getByCondition(array(
                    'hs_code' => $hsCode,
                    'hu_status' => 1,
                ));
                if (empty($productUom)) {
                    throw new Exception('产品单位数据有误');
                }

                if (empty($hsUomMap)) {
                    throw new Exception('产品缺乏法定数量数据');
                }
                if (empty($hsUom) || count($hsUom) > 1) {
                    throw new Exception('海关申报单位数据有误');
                }

                if ($humQantityLaw <= 0 || !preg_match('/^\d+(?:\.\d{1,5})?$/', $humQantityLaw)) {
                    throw new Exception('第一法定数量必须大于0且不能超过5位小数');
                }
                if(in_array($productInfo['gift_flag'],[1,3])){
                    if($humQantityLaw!=$hsUomMap['hum_quantity_law']){
                        throw new Exception('赠品和大贸商品法一不能更改原法一:'.$hsUomMap['hum_quantity_law']."-->$humQantityLaw");
                    }
                }
                $hsUom = $hsUom[0];
                $firstUom = Service_ProductUom::getByField($hsUom['pu_code_law'], 'pu_code');
                if (empty($firstUom)) {
                    throw new Exception('产品海关申报单位数据有误');
                }

                if (1 === (int)$firstUom['pu_int_request']) {
                    if (!preg_match('/^[1-9]\d*(?:\.0{1,5})?$/', $humQantityLaw)) {
                        throw new Exception('第一法定数量必须为整数');
                    }
                }

                if ('035' === trim($firstUom['pu_code'])) {
                    if ($humQantityLaw != $productNetWeight) {
                        throw new Exception('第一法定数量（千克）[' . $humQantityLaw . ']与产品净重[' . $productNetWeight . ']不符');
                    }
                }
                if ('' !== trim($hsUom['pu_code_second'])) {
                    if ($humQuantitySecond <= 0 || !preg_match('/^\d+(?:\.\d{1,5})?$/', $humQuantitySecond)) {
                        throw new Exception('第二法定数量必须大于0且不能超过5位小数');
                    }

                    $secondUom = Service_ProductUom::getByField($hsUom['pu_code_second'], 'pu_code');

                    if (empty($secondUom)) {
                        throw new Exception('产品海关申报单位数据有误');
                    }

                    if (1 === (int)$secondUom['pu_int_request']) {
                        if (!preg_match('/^[1-9]\d*(?:\.0{1,5})?$/', $humQuantitySecond)) {
                            throw new Exception('第二法定数量必须为整数');
                        }
                    }

                    if ('035' === trim($secondUom['pu_code'])) { // 申报单位为千克，跟产品重量做比较
                        if ($productNetWeight != $humQuantitySecond) {
                            throw new Exception('第二法定数量（千克）与产品净重不符');
                        }
                    }
                } else {
                    $humQuantitySecond = 0;
                }
                if (empty($heDetail)) {
                    throw new Exception('海关申报要素不能为空');
                }
                $newHsElement = Service_HsElement::getByCondition(array('hs_code' => $hsCode), '*', 0, 0, 'he_sort asc');
                $elementNumber = 0;
                $elementValueLength = 0;
                foreach ($newHsElement as $hs) {
                    if (!isset($heDetail[$hs['he_id']])) {
                        throw new Exception('申报要素参数错误');
                    }
                    if (!in_array($hs['he_code'], array('GTIN', 'CAS', '其它','其他')) && empty($heDetail[$hs['he_id']])) {
                        //throw new Exception('申报要素：' . $hs['he_code'] . '不能为空');
                    }
                    $elementNumber += 1;
                    $elementValueLength += strlen(mb_convert_encoding($heDetail[$hs['he_id']], 'GB2312', 'UTF-8'));
                }
                $limitLenth = 250;
                if ($elementValueLength > $limitLenth) {
                    throw new Exception("各申报元素的内容总长度不超过" . $limitLenth . "个字符。");
                }
                $config = new Api_Inv_Config();
                $invtInfo = $config->getInvHeadConfig();
                //var_dump($invtInfo);
                $billBookProduct = Service_BillBookProduct::getByCondition([
                    'product_id' => $productInfo['product_id']
                ]);

                $billBookList = Service_BillBook::getByCondition([
                    'warehous_account_no' => $invtInfo['bwl_no'],
                    'goods_code' => $productInfo['goods_id'],
                ]);

                foreach ($billBookList as $billBook) {
                    if ($billBook['can_use_quantity'] || $billBook['frozen_quantity'] || $billBook['lock_quantity']) {
                        throw new Exception("备案序号" . $billBook['recorde_no'] . "料号:".$productInfo['goods_id']. '有库存不能修改');
                        if ($hsCode != $productInfo['hs_code']) {
                            if ($hsCode != $billBook['hs_code']) {
                                throw new Exception("备案序号" . $billBook['recorde_no'] . '海关编码未修改，请先修改备案信息');
                            }
                        }
                        if($puCode!=$productInfo['pu_code']){
                            if ($puCode != $billBook['decalare_unit']) {
                                throw new Exception("备案序号" . $billBook['recorde_no'] . '海关申报单位未修改，请先修改备案信息');
                            }
                        }
                        if($hsGoodsName!=$productInfo['hs_goods_name']){
                            if ($hsGoodsName != $billBook['product_title']) {
                                throw new Exception("备案序号" . $billBook['recorde_no'] . '海关品名未修改，请先修改备案信息');
                            }
                        }
                    }
                }

                $updateFiled = array(
                    'product_sku' => $productSku,
                    'product_title' => $productTitle,
                    'hs_code' => $hsCode,
                    'product_weight' => $productWeight,
                    'pu_code' => $puCode,
                    'hum_quantity_law' => $humQantityLaw,
                    'hum_quantity_second' => $humQuantitySecond,
                    'hs_goods_name' => $hsGoodsName,
                    'special'=>$special
                );
                $originalFiled = array(
                    'product_sku' => $productInfo['product_sku'],
                    'product_title' => $productInfo['product_title'],
                    'hs_code' => $productInfo['hs_code'],
                    'product_weight' => $productInfo['product_weight'],
                    'pu_code' => $productInfo['pu_code'],
                    'hum_quantity_law' => $hsUomMap['hum_quantity_law'],
                    'hum_quantity_second' => $hsUomMap['hum_quantity_second'],
                    'hs_goods_name' => $productInfo['hs_goods_name'],
                    'special'=>$productInfo['special']
                );
                $updateFiledName = array(
                    'product_sku' => 'sku',
                    'product_title' => '产品名称',
                    'hs_code' => '海关编码',
                    'product_weight' => '产品重量',
                    'pu_code' => '申报单位',
                    'hum_quantity_law' => '法一数量',
                    'hum_quantity_second' => '法二数量',
                    'product_net_weight' => '产品净重',
                    'hs_goods_name' => '海关品名',
                );
                foreach ($originalFiled as $key => $value) {
                    if ($updateFiled[$key] != $value) {
                        $log .= $updateFiledName[$key] . ':' . $value . '->' . $updateFiled[$key];
                    }
                }
                $updateProduct = array(
                    'product_sku' => $productSku,
                    'product_title' => $productTitle,
                    '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 ($productInfo['hs_code'] != $hsUom['hs_code']) {
                    $updateLawQuantity['hu_id'] = $hsUom['hu_id'];
                }
                if (!empty($updateLawQuantity)) {
                    Service_HsUomMap::update($updateLawQuantity, $productInfo['product_id'], 'product_id');
                }
                $oldHsElement = Service_HsElementMap::getByCondition(array('product_id' => $productInfo['product_id']));
                $updateHsElemnt = array();
                $addHsElementMap = array();
                if ($updateProduct['hs_code'] == $productInfo['hs_code']) {
                    foreach ($newHsElement as $hem) {
                        $productHsElement = Service_HsElementMap::getByCondition(array(
                                'product_id' => $productInfo['product_id'],
                                'he_id' => $hem['he_id'],
                            )
                        );
                        if ($productHsElement) {
                            $hemId = $productHsElement[0]['hem_id'];
                            if ($productHsElement[0]['hem_detail'] != $heDetail[$hem['he_id']]) {
                                $updateHsElemnt[$hemId] = $heDetail[$hem['he_id']];
                                $log .= $hem['he_name'] . ':' . $productHsElement[0]['hem_detail'] . '->' . $heDetail[$hem['he_id']];
                            }
                        } else {
                            $addHsElementMap[$hem['he_id']] = $heDetail[$hem['he_id']];
                            $log .= $hem['he_name'] . ':->' . $heDetail[$hem['he_id']];
                        }
                    }
                    $deleteMap = array();
                    foreach ($oldHsElement as $hsMap) {
                        $hElement = Service_HsElement::getByCondition(array(
                            'hs_code' => $hsCode,
                            'he_id' => $hsMap['he_id']
                        ));
                        if (empty($hElement)) {
                            $deleteMap[] = $hsMap['he_id'];
                            $elementInfo = Service_HsElement::getByField($hsMap['he_id']);
                            $log .= "删除要素：" . $elementInfo['he_name'];
                            Service_HsElementMap::delete($hsMap['hem_id']);
                        }
                    }
                    if (!empty($updateHsElemnt)) {
                        foreach ($updateHsElemnt as $hemId => $up) {
                            Service_HsElementMap::update(array('hem_detail' => $up), $hemId);
                        }
                    }
                    if (!empty($addHsElementMap)) {
                        foreach ($addHsElementMap as $heId => $heDetail) {
                            Service_HsElementMap::add(
                                array(
                                    'product_id' => $productInfo['product_id'],
                                    'hem_detail' => $heDetail,
                                    'he_id' => $heId,
                                    'hem_add_time' => date("Y-m-d H:i:s"),
                                )
                            );
                        }
                    }
                } else {
                    $log .= '修改海关编码：' . $productInfo['hs_code'] . '->' . $updateProduct['hs_code'];
                    Service_HsElementMap::delete($productInfo['product_id'], 'product_id');
                    foreach ($heDetail as $key => $detail) {
                        $addHsElementMap = array(
                            'product_id' => $productInfo['product_id'],
                            'hem_detail' => $detail,
                            'he_id' => $key,
                            'hem_add_time' => date("Y-m-d H:i:s"),
                        );
                        Service_HsElementMap::add($addHsElementMap);
                    }
                }
                if (empty($log)) {
                    //throw new Exception('没有修改内容');
                }
                Service_Product::update($updateProduct, $productInfo['product_id']);
                $logRow = array(
                    'product_id' => $productInfo['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_note'=>'增加条码：4955814149901',
                    'pl_add_time' => date("Y-m-d H:i:s"),
                );
                Service_ProductLog::add($logRow);
            }
            $return['state'] = 1;
            $return['message'] = '修改成功';
            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,
                    'productInfo'=>$productInfo,
                );
                $goodsResult =  Service_Product::modifyGoodsInfo($row);
                if($goodsResult['state']!='1'){
                    throw new Exception($goodsResult['message']);
                }

                //更新product_goods表
                //self::generateGoodsKey($productInfo);
                $goods_key = Service_Product::getGoodsKeyArr($productId);
                if(isset($goods_key[0])){
                    $productGoods = Service_ProductGoods::getByField($productInfo['goods_id'], 'goods_code', "*");
                    if (!empty($productGoods)) {
                        $productGood = Service_ProductGoods::getByField($productInfo['goods_id'], 'goods_code', "*");
                        $updatePg = array(
                            'goods_key' => $goods_key[0]
                        );
                        Service_ProductGoods::update($updatePg, $productGood['pg_id'], 'pg_id');
                    }
                }
            }

            $db->commit();
            //$db->rollBack();
        } catch (Exception $e) {
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(json_encode($return));
    }



    /**
     * Note:获取海关申报要素信息
     * User: Yao
     * Date: 2019/6/11
     * Time: 17:34
     */
    public function getHsElementAction() {
        $return = array(
            'state' => 0,
            'data' => array()
        );
        try {
            if ($this->_request->isXmlHttpRequest()) {
                $hsCode = $this->_request->getParam('hs_code');
                if (empty($hsCode)) {
                    throw new Exception('海关编码不存在');
                }
                $hsElement = Service_HsElement::getByCondition(array('hs_code' => $hsCode), '*', 0, 0, 'he_sort asc');
                $return['data'] = $hsElement;
                $hsUom = Service_HsUom::getByField($hsCode, 'hs_code');
                $return['hs_uom'] = $hsUom;
                $return['state'] = 1;
            }
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(json_encode($return));
    }

}
