<?php
require_once "PHPExcel1.8/PHPExcel.php";
require_once "PHPExcel1.8/PHPExcel/Reader/Excel2007.php";
require_once "PHPExcel1.8/PHPExcel/Reader/Excel5.php";
require_once "PHPExcel1.8/PHPExcel/IOFactory.php";

class Product_ProductController 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'] : '';
            $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));
        }
        $this->view->status = $status;
        $this->view->receiving = $receiving;
        echo Ec::renderTpl($this->tplDirectory . "product_index.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage' => array('Fail.')
        );

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(

                'product_id' => '',
                'product_sku' => '',
                'customer_code' => '',
                'product_title_en' => '',
                'product_title' => '',
                'product_status' => '',
                'product_receive_status' => '',
                'product_weight' => '',
                'pc_id' => '',
            );
            $row = $this->serviceClass->getMatchEditFields($params, $row);
            $paramId = $row['product_id'];
            if (!empty($row['product_id'])) {
                unset($row['product_id']);
            }
//            $  Service_ProductCategory::getAll();
//

            $errorArr = $this->serviceClass->validator($row);

            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message' => '',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }

            if (!empty($paramId)) {
                $result = $this->serviceClass->update($row, $paramId);
            } else {
                $result = $this->serviceClass->add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('Success.');
            }

        }
        die(Zend_Json::encode($return));
    }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'product_id')) {
            $rows = $this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    public function deleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                if ($this->serviceClass->delete($paramId)) {
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }
            }
        }
        die(Zend_Json::encode($result));
    }


    //进入添加产品的页面
    public function toAddProductAction()
    {
        echo Ec::renderTpl($this->tplDirectory . "product_add.tpl", 'layout');
    }

    //进入产品明细页面
    public function toProductDetailAction()
    {
        $skuid = $this->_request->getParam("skuid");
        $productRow = array();

        if (!empty($skuid)) {
            $productRow = $this->serviceClass->getByField($skuid, 'product_id');
        }
        $this->view->product = $productRow;
        echo Ec::renderTpl($this->tplDirectory . "product_detail.tpl", 'layout');
    }


    /**
     * 获取产品分类
     */
    public function getProductCategoryAction()
    {

        $result = array(
            "state" => 0,
            "data" => array(),
            "ids" => array(),
            "message" => Ec::Lang('operationFail')
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            $language = Ec::getLang(1);
            $showFields = array(
                'ur_name' . $language . ' as title',
                'ur_module as module',
                'um_id as menu_id',
                'ur_id as id',
            );
            $menuArr = Common_DataCache::getUserMenu();
            $result['data'] = Service_UserRight::getByCondition(array(), $showFields, 0, 0, array('um_id', 'ur_module', 'ur_sort'));
            foreach ($result['data'] as $key => $val) {
                $result['data'][$key]['menu'] = isset($menuArr[$val['menu_id']]['um_title' . $language]) ? $menuArr[$val['menu_id']]['um_title' . $language] : '';
            }
            $rightUraIdArr = array();
            if (!empty($paramId)) {
                $rightAction = Service_UserRightMap::getByCondition(array('user_id' => $paramId), 'ur_id');
                if (!empty($rightAction)) {
                    foreach ($rightAction as $v) {
                        $rightUraIdArr[$v['ur_id']] = $v['ur_id'];
                    }
                }
            }
            $result['ids'] = $rightUraIdArr;
            $result['state'] = 1;
        }
        die(Zend_Json::encode($result));

    }

    /*产品详细*/
    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), "*");
        foreach ($inventoryBatchList as $k => $v) {
            if ($v['from_product_id'] > 0) {
                $fromProduct = Service_Product::getByField($v['from_product_id'], 'product_id', "*");
                $inventoryBatchList[$k]['from_goods_id'] = $fromProduct['goods_id'];
            } else {
                $inventoryBatchList[$k]['from_goods_id'] = "";
            }
        }
        $this->view->inventoryBatchList = $inventoryBatchList;//产品批次库存

        $hsElementMap = Service_HsElementMap::getByCondition(array('product_id' => $skuid), "*");
        $sort = array();
        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;
                $hsElementMap[$k]['he_sort'] = $HE['he_sort'];
                $sort[$k] = $HE['he_sort'];
            }
            array_multisort($sort, SORT_ASC, $hsElementMap);
        } 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-log.tpl", 'layout');
    }

    public function printAction()
    {
        $productCodes = $this->_request->getParam('productCodes', "");
        //$printNumber = $this->_request->getParam('printNumber',"");
        $productArr = explode(",", $productCodes);
        //$printCode = array();
        $productList = array();
        foreach ($productArr as $key => $value) {
            if ($value == "") continue;
            $productService = new Service_Product();
            $p = $productService->getByField($value, "product_barcode", "*");
            if ($p['product_type'] != "1") {
                $category = Service_ProductCategory::getByField($p['pc_id'], 'pc_id', "*");
                $p['pc_name_en'] = $category['pc_name_en'];
                //$productList[] = $p;
                $item = array(
                    'product_barcode' => $p['product_barcode'],
                    'customer_code' => $p['customer_code'],
                    'pc_name_en' => $p['pc_name_en'],
                );
                $printNumber = $this->_request->getParam("product_" . $p['product_id'], "1");
                for ($i = 0; $i < $printNumber; $i++) {
                    $productList[] = $item;
                }
            }
        }
        $this->view->productList = $productList;
        echo Ec::renderTpl($this->tplDirectory . "product-print.tpl", 'layout');
    }

    public function recordAction()
    {
        $response = array("state" => 0, "message" => '');
        $product_id = $this->_request->getParam('product_id');
        if (empty($product_id)) exit(Zend_Json::encode(array('state' => 0, 'message' => '参数错误')));
        $aProduct = Service_Product::getByField($product_id);
        if (empty($aProduct)) exit(Zend_Json::encode(array('state' => 0, 'message' => '找不到产品')));
        if ($aProduct['product_status'] != 0) {
            exit(Zend_Json::encode(array('state' => 0, 'message' => '产品不是备案中的状态')));
        }
        //$recordProcess = new Service_ProductRecordProcess();
        //$fpr_id = $recordProcess->addGoodsRecord($product_id, $aProduct['goods_id']);
        //if(!is_int($fpr_id)) exit(Zend_Json::encode(array('state'=>0, 'message'=>$fpr_id)));
        //$result = $recordProcess->ftpSendRecord($fpr_id);
        //if(!$result) exit(Zend_Json::encode(array('state'=>0, 'message'=>'提交备案失败')));
        $uProduct['product_status'] = 1;
        $uProduct['product_update_time'] = date('Y-m-d H:i:s');
        Service_Product::update($uProduct, $product_id);
        $log['product_id'] = $product_id;
        $log['pl_type'] = 1;
        $log['user_id'] = Service_User::getUserId();
        $log['pl_statu_pre'] = $aProduct['product_status'];
        $log['pl_statu_now'] = $uProduct['product_status'];
        $log['pl_note'] = '备案';
        $log['pl_add_time'] = date('Y-m-d H:i:s');
        $log['pl_ip'] = Common_Common::getIP();
        Service_ProductLog::add($log);
        $response['state'] = 1;
        exit(Zend_Json::encode($response));
    }

    public function changeAction()
    {
        $product_id = $this->_request->getParam("product_id", "");
        $productWeight = $this->_request->getParam("product_weight", "");
        $productHeight = $this->_request->getParam("product_height", "");
        $productLength = $this->_request->getParam("product_length", "");
        $productWidth = $this->_request->getParam("product_width", "");
        $product_title_en = $this->_request->getParam("product_title_en","");
        $productRow = Service_Product::getByField($product_id, "product_id", "*");
        $result = array(
            'state' => '1',
            'errorMessage' => array(),
        );
        if ($productWeight == "") {
            $result['state'] = "0";
            $result['errorMessage'][] = "产品重量不能为空!";
            exit(Zend_Json::encode($result));
        }
        if (!preg_match("/^[1-9]\d*(.\d+)*$|^0.\d*[1-9]+\d*$/", $productWeight)) {
            $result['state'] = "0";
            $result['errorMessage'][] = "产品重量只能是大于0的数值";
            exit(Zend_Json::encode($result));
        }
        if (!preg_match("/^([1-9]\d*|[0]{1}\.{1}\d+|[1-9]\d*\.{1}\d+)\d*$|^0{1}$/", $productHeight)) {
            $result['state'] = "0";
            $result['errorMessage'][] = "产品高只能是大于0的数值";
            exit(Zend_Json::encode($result));
        }
        if (!preg_match("/^([1-9]\d*|[0]{1}\.{1}\d+|[1-9]\d*\.{1}\d+)\d*$|^0{1}$/", $productLength)) {
            $result['state'] = "0";
            $result['errorMessage'][] = "产品长只能是大于0的数值";
            exit(Zend_Json::encode($result));
        }
        if (!preg_match("/^([1-9]\d*|[0]{1}\.{1}\d+|[1-9]\d*\.{1}\d+)\d*$|^0{1}$/", $productWidth)) {
            $result['state'] = "0";
            $result['errorMessage'][] = "产品宽只能是大于0的数值";
            exit(Zend_Json::encode($result));
        }
        if(empty($product_title_en)){
            $result['state'] = "0";
            $result['errorMessage'][] = "产品英文名称不能为空";
            exit(Zend_Json::encode($result));
        }
        /*$existOrderProduct = Service_OrderProduct::changeWeightCondition($product_id);
        if($existOrderProduct){
            $result['state'] = "0";
            $result['errorMessage'][] = "有未出货的订单,重量不能修改";
            exit(Zend_Json::encode($result));
        }*/
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $updateProduct = array(
                'product_weight' => $productWeight,
                'product_height' => $productHeight,
                'product_length' => $productLength,
                'product_width' => $productWidth,
                'product_title_en'=>$product_title_en,
                'product_update_time' => date("Y-m-d H:i:s"),
            );
            Service_Product::update($updateProduct, $product_id, 'product_id');
            $pl_note = "";
            if ($productWeight != $productRow['product_weight']) {
                $pl_note .= '改重量:' . $productRow['product_weight'] . "=>" . $productWeight . ";";
            }
            if ($productLength != $productRow['product_length']) {
                $pl_note .= '长:' . $productRow['product_length'] . "=>" . $productLength . ";";
            }
            if ($productWidth != $productRow['product_width']) {
                $pl_note .= '宽:' . $productRow['product_width'] . "=>" . $productWidth . ";";
            }
            if ($productHeight != $productRow['product_height']) {
                $pl_note .= '高:' . $productRow['product_height'] . "=>" . $productHeight . ";";
            }
            if ($product_title_en != $productRow['product_title_en']) {
                $pl_note .= '英文名称:' . $productRow['product_title_en'] . "=>" . $product_title_en . ";";
            }
            $logRow = array(
                'product_id' => $product_id,
                'pl_type' => '0',
                'customer_id' => $productRow['customer_id'],
                'pl_add_time' => date("Y-m-d H:i:s"),
                'pl_statu_pre' => $productRow['product_status'],
                'pl_statu_now' => $productRow['product_status'],
                'pl_note' => $pl_note,
                'pl_ip' => Common_Common::getIP(),
                'user_id' => $this->user_id,
            );
            Service_ProductLog::add($logRow);
            $db->commit();
            //$db->rollBack();
            $result['state'] = 1;
            $result['errorMessage'][] = '操作成功';
        } catch (Exception $e) {
            $result['state'] = '0';
            $result['errorMessage'][] = '操作失败:' . $e->getMessage();
        }
        exit(Zend_Json::encode($result));
    }

    public function recordAgainAction()
    {
        $product_id = $this->_request->getParam("product_id", "");
        $objProduct = new Service_Product();
        $result = $objProduct->recordAgainProcess($product_id);
        exit(Zend_Json::encode($result));
    }

    public function batchRecordAgainAction()
    {
        $pidArr = $this->_request->getParam("pidArr", "");
        $productIdArr = explode("|", $pidArr);
        $objProduct = new Service_Product();
        $success = 0;//成功个数
        $fail = 0;//失败个数
        $count = 0;
        $return = array(
            'message' => array(),
            'count' => '',
            'success' => '',
            'fail' => '',
        );
        foreach ($productIdArr as $product_id) {
            if ($product_id == "") continue;
            $count++;
            $result = $objProduct->recordAgainProcess($product_id);
            $return['message'][] = $result;
            if ($result['ask'] == "1") {
                $success++;
            } else {
                $fail++;
            }
        }
        $return['count'] = $count;
        $return['success'] = $success;
        $return['fail'] = $fail;
        exit(Zend_Json::encode($return));
    }

    public function uploadTemplateAction()
    {
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        $fullPath = APPLICATION_PATH . "/../data/xls" . '/batchRecord.xls';
        //方法2
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header = "Content-Disposition: attachment; filename=" . $filename . ";";
        header($header);
        //     header("Content-Transfer-Encoding: binary");
        //     header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }

    public function uploadTemplateDeclaredAction()
    {
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        $fileType = $this->_request->getParam("fileType", "");
        if ($fileType == "element") {
            $fullPath = APPLICATION_PATH . "/../data/xls" . '/batchEditElement.xls';
        } elseif ($fileType == "IMEI") {
            $fullPath = APPLICATION_PATH . "/../data/xls" . '/batchEditIMEI.xls';
        } elseif ($fileType == "batch-bag") {
            $fullPath = APPLICATION_PATH . "/../data/xls" . '/batch-bag.xls';
        } else {
            $fullPath = APPLICATION_PATH . "/../data/xls" . '/batchDeclaredValue.xls';
        }
        //方法2
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header = "Content-Disposition: attachment; filename=" . $filename . ";";
        header($header);
        //     header("Content-Transfer-Encoding: binary");
        //     header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }

    public function batchRecordUploadAction()
    {
        $result = array("ask" => 1, "message" => "", 'error' => array(), 'data' => array());
        $xlsData = Service_Product::getXLSData($_FILES, 'filename');
        if (count($xlsData[0]) != 2 || ($xlsData[0][0] != "客户代码" || $xlsData[0][1] != "产品sku")) {
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照客户代码,产品sku排列!";
            die(json_encode($result));
        }

        // print_r($xlsData);exit;
        foreach ($xlsData as $key => $value) {
            if ($key == 0) continue;
            $existError = 0;
            $customer_code = trim($value[0]);
            $product_sku = trim($value[1]);
            $resultData = array(
                'customer_code' => $customer_code,
                'product_sku' => $product_sku,
                'ok' => 1
            );
            $resultData['message'] = "";
            if ($customer_code == "") {
                $existError = 1;
                $resultData['message'] .= "客户代码为空;";
            }
            if ($product_sku == "") {
                $existError = 1;
                $resultData['message'] .= "产品sku为空;";
            }
            if ($existError) {
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }

            $customer = Service_Customer::getByField($customer_code, 'customer_code', "*");
            if (empty($customer)) {
                $resultData['message'] .= "不存在客户" . $customer_code;
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $p = Service_Product::getByCondition(array('customer_code' => $customer_code, 'product_sku' => $value[1]), "*");
            if (empty($p)) {
                $resultData['message'] .= "客户" . $customer_code . "不存在产品" . $product_sku;
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $aProduct = $p[0];
            /*     if($aProduct['goods_id']==''){
                     $resultData['message'] .= "sku没生成料件号".$aProduct['goods_id'];
                     $resultData['ok'] = '0';
                     $result['data'][] = $resultData;
                     continue;
                 }*/
            /*  if($aProduct['product_status'] != '3') {
                  $resultData['message'] .= "sku ".$value[1]."不为已提交状态";
                  $resultData['ok'] = '0';
                  $result['data'][] = $resultData;
                  continue;
              }*/
            /* $goodsCondition = array(
                 'goods_code'=>$aProduct['goods_id'],
                 //'product_id'=>$aProduct['product_id'],
             );*/
            /*$productGoods = Service_ProductGoods::getByCondition($goodsCondition);
            if(empty($productGoods)){
                $resultData['message'] .= "sku在料件表中不存在".$aProduct['goods_id'];
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }*/
            $objProduct = new Service_Product();
            $re = $objProduct->recordAgainProcess($aProduct['product_id']);
            if ($re) {
                if ($re['ask'] == 1) {
                    $resultData['ok'] = '1';
                } else {
                    $resultData['ok'] = '0';
                }

                $resultData['message'] .= $re['message'];
                $result['data'][] = $resultData;
                continue;
            }

        }
        die(json_encode($result));
    }

    /*导入修改申报价值*/
    public function batchDeclaredValueAction()
    {
        $result = array("ask" => 1, "message" => "", 'error' => array(), 'data' => array());
        $xlsData = Service_Product::getXLSData($_FILES, 'file');
        if (count($xlsData[0]) != 3 || ($xlsData[0][0] != "客户代码" || $xlsData[0][1] != "产品sku" || $xlsData[0][2] != "申报价值(USD)")) {
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照客户代码,产品sku,申报价值排列!";
            die(json_encode($result));
        }
        foreach ($xlsData as $key => $value) {
            if ($key == 0) continue;
            $existError = 0;
            $customer_code = trim($value[0]);
            $product_sku = trim($value[1]);
            $declared_value = trim($value[2]);
            $resultData = array(
                'customer_code' => $customer_code,
                'product_sku' => $product_sku,
                'declared_value' => $declared_value,
                'ok' => 1
            );
            $resultData['message'] = "";
            if ($customer_code == "") {
                $existError = 1;
                $resultData['message'] .= "客户代码为空;";
            }
            if ($product_sku == "") {
                $existError = 1;
                $resultData['message'] .= "产品sku为空;";
            }
            if ($declared_value == "") {
                $existError = 1;
                $resultData['message'] .= "产品申报价值为空;";
            } else {
                if (!is_numeric($declared_value)) {
                    $existError = 1;
                    $resultData['message'] .= "产品申报价值必须为数字;";
                }
            }
            if ($existError) {
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }

            $customer = Service_Customer::getByField($customer_code, 'customer_code', "*");
            if (empty($customer)) {
                $resultData['message'] .= "不存在客户" . $customer_code;
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $p = Service_Product::getByCondition(array('customer_code' => $customer_code, 'product_sku' => $product_sku), "*");
            if (empty($p)) {
                $resultData['message'] .= "客户" . $customer_code . "不存在产品" . $product_sku;
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $productInfo = $p[0];
            try {
                $db = Common_Common::getAdapter();
                $db->beginTransaction();
                $process = new Service_ProductProcess();
                $process->changeDecalarValidate($productInfo);
                $validate[] = array('name' => '申报价值', 'value' => $declared_value, 'regex' => array('require', 'positive'));
                $valdate = Common_Validator::formValidator($validate);
                if (!empty($valdate)) {
                    throw new Exception(implode(',', $valdate));
                }
                $updateArray = array(
                    'product_declared_value' => trim($declared_value),
                );
                if ($updateArray['product_declared_value'] - $productInfo['product_declared_value'] == 0) {
                    throw new Exception('没有修改内容');
                }

                if (Service_Product::update($updateArray, $productInfo['product_id'])) {
                    $logRow = array(
                        'product_id' => $productInfo['product_id'],
                        'pl_type' => '0',
                        'customer_id' => $productInfo['customer_id'],
                        'pl_add_time' => date("Y-m-d H:i:s"),
                        'pl_statu_pre' => $productInfo['product_status'],
                        'pl_statu_now' => $productInfo['product_status'],
                        'pl_note' => '改申报价值:' . $productInfo['product_declared_value'] . "=>" . $updateArray['product_declared_value'],
                        'pl_ip' => Common_Common::getIP(),
                        'user_id' => $this->user_id,
                    );
                    Service_ProductLog::add($logRow);
                    $resultData['message'] = '更新成功';
                    $result['data'][] = $resultData;
                } else {
                    throw new Exception('更新失败');
                }
                $db->commit();
            } catch (Exception $e) {
                $resultData['ok'] = '0';
                $resultData['message'] = $e->getMessage();
                $result['data'][] = $resultData;
                $db->rollBack();
            }

        }
        die(json_encode($result));
    }

    public function uploadDeleteAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        $result = array("ask" => 1, "message" => "", 'error' => array(), 'data' => array());
        $xlsData = Service_Orders::getXLSData($_FILES, 'uploadfilename');
        if (count($xlsData[0]) != 2 || ($xlsData[0][0] != "客户代码" || $xlsData[0][1] != "产品SKU")) {
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照客户代码,产品SKU排列!";
            die(json_encode($result));
        }
        foreach ($xlsData as $key => $value) {

            $value[0] = trim($value[0]);
            $value[1] = trim($value[1]);

            if ($key == 0) continue;
            $resultData = array(
                'customer_code' => $value[0],
                'product_sku' => $value[1],
                'ok' => 0,
                'message' => '',
            );
            if ($value[0] == "" || $value[1] == "") {
                $resultData['message'] = "客户代码或产品SKU不能为空;";
                $result['data'][] = $resultData;
                continue;
            }

            $customer = Service_Customer::getByField($value[0], 'customer_code', "*");
            if (empty($customer)) {
                $resultData['message'] = "不存在客户" . $value[0];
                $result['data'][] = $resultData;
                continue;
            }

            $p = Service_Product::getByCondition(array('customer_code' => $value[0], 'product_sku' => $value[1]), "*");
            if (empty($p)) {
                $resultData['message'] = "客户" . $value[0] . "不存在产品" . $value[1];
                $result['data'][] = $resultData;
                continue;
            }

            $aProduct = $p[0];
            $response = Service_Product::remove($aProduct['product_id']);
            if ($response['valid']) {
                $resultData['ok'] = 1;
            }
            $resultData['message'] = $response['valid'] ? "删除成功" : $response['message'];

            $result['data'][] = $resultData;
        }
        die(json_encode($result));

    }

    public function uploadTemplateDownloadAction()
    {
        header("Content-type: text/html; charset=utf-8");
        $oExcel = new PHPExcel();
        $oExcel->setActiveSheetIndex();
        $oActiveSheet = $oExcel->getActiveSheet();
        $oExcel->getDefaultStyle()->getFont()->setName('宋体');
        $oExcel->getDefaultStyle()->getFont()->setSize(12);
        $oActiveSheet->setCellValue('A1', '客户代码');
        $oActiveSheet->setCellValue('B1', '产品SKU');

        //下载输出
        $oWriter = PHPExcel_IOFactory::createWriter($oExcel, 'Excel5');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) {//IE
            $filename = urlencode('productBatchDelete' . date('YmdHis') . '.xls');
        } else {
            $filename = 'productBatchDelete' . date('YmdHis') . '.xls';
        }

        header('Content-Disposition:attachment;filename="' . $filename . '"');

        header("Content-Transfer-Encoding:binary");
        $oWriter->save('php://output');
    }

    public function editDecalarAction()
    {
        $reuslt = array('state' => 0, 'errorMessage' => null);
        if ($this->_request->isPost()) {
            try {
                $param = $this->_request->getPost();
                $db = Common_Common::getAdapter();
                $db->beginTransaction();
                if ($param['product_id']) {
                    $productInfo = Service_Product::getByField($param['product_id']);
                    if (empty($productInfo)) {
                        throw new Exception('提交数据出错');
                    }
                    $process = new Service_ProductProcess();
                    $process->changeDecalarValidate($productInfo);
                    $validate[] = array('name' => '申报价值', 'value' => $param['product-decare-value'], 'regex' => array('require', 'positive'));
                    $valdate = Common_Validator::formValidator($validate);
                    if (!empty($valdate)) {
                        throw new Exception(implode(',', $valdate));
                    }
                    $updateArray = array(
                        'product_declared_value' => trim($param['product-decare-value']),
                    );
                    if ($updateArray['product_declared_value'] - $productInfo['product_declared_value'] == 0) {
                        throw new Exception('没有修改内容');
                    }

                    if (Service_Product::update($updateArray, $productInfo['product_id'])) {
                        $reuslt['state'] = 1;
                        $logRow = array(
                            'product_id' => $productInfo['product_id'],
                            'pl_type' => '0',
                            'customer_id' => $productInfo['customer_id'],
                            'pl_add_time' => date("Y-m-d H:i:s"),
                            'pl_statu_pre' => $productInfo['product_status'],
                            'pl_statu_now' => $productInfo['product_status'],
                            'pl_note' => '改申报价值:' . $productInfo['product_declared_value'] . "=>" . $updateArray['product_declared_value'],
                            'pl_ip' => Common_Common::getIP(),
                            'user_id' => $this->user_id,
                        );
                        Service_ProductLog::add($logRow);
                    } else {
                        throw new Exception('更新失败');
                    }

                }
                $db->commit();
            } catch (Exception $e) {
                $reuslt['errorMessage'][] = $e->getMessage();
                $db->rollBack();
            }
        }
        echo Zend_Json::encode($reuslt);
    }

    public function editpgAction()
    {
        $reuslt = array('state' => 0);
        if ($this->_request->isPost()) {
            try {
                $param = $this->_request->getPost();
                $db = Common_Common::getAdapter();
                $db->beginTransaction();
                if ($param['product_id']) {
                    $productInfo = Service_Product::getByField($param['product_id']);
                    if (empty($productInfo)) {
                        throw new Exception('提交数据出错');
                    }
                    $goods_id = $productInfo['goods_id'];
                    $new_goods_id = $param['new_goods_id'];
                    if ($goods_id == $new_goods_id) {
                        throw new Exception('旧料件号[' . $goods_id . ']与新料件号[' . $new_goods_id . ']一样');
                    }
                    $existProductInventory = Service_ProductInventory::getJoinProductByCondition(array('goods_id' => $goods_id), 'count(*)');
                    /*if($existProductInventory){
                        throw new Exception('料件号['.$goods_id.']对应的产品SKU有库存');
                    }*/
                    $existOrder = Service_OrderProduct::getJoinProductByCondition(array('goods_id' => $goods_id));
                    if (!empty($existOrder)) {
                        throw new Exception('料件号[' . $goods_id . ']对应的产品SKU已有订单');
                    }
                    /*$existAsn = Service_ReceivingDetail::getJoinProductByCondition(array('goods_id'=>$goods_id));
                    if(!empty($existAsn)){
                        throw new Exception('料件号['.$goods_id.']对应的产品SKU已有入区单');
                    }*/
                    //throw new Exception("EXCEPTION");
                    $newProductGoods = Service_ProductGoods::getByField($new_goods_id, 'goods_code', "*");
                    if (empty($newProductGoods)) {
                        $productGood = Service_ProductGoods::getByField($goods_id, 'goods_code', "*");
                        $updatePg = array(
                            'goods_code' => $new_goods_id
                        );
                        Service_ProductGoods::update($updatePg, $productGood['pg_id'], 'pg_id');
                    }
                    $productList = Service_Product::getByCondition(array('goods_id' => $goods_id), "*");
                    foreach ($productList as $product) {
                        $updateProduct = array(
                            'goods_id' => $new_goods_id,
                            'goods_id_old' => $goods_id,
                        );
                        Service_Product::update($updateProduct, $product['product_id'], 'product_id');
                        $productLog = array(
                            'product_id' => $product['product_id'],
                            'pl_type' => '0',
                            'customer_id' => $product['customer_id'],
                            'pl_add_time' => date("Y-m-d H:i:s"),
                            'pl_statu_pre' => $product['product_status'],
                            'pl_statu_now' => $product['product_status'],
                            'pl_note' => '与SKU[' . $productInfo['product_sku'] . ']共用同一个料件号sku[' . $productInfo['product_sku'] . ']修改料件号:' . $product['goods_id'] . "=>" . $new_goods_id,
                            'pl_ip' => Common_Common::getIP(),
                            'user_id' => $this->user_id,
                        );
                        Service_ProductLog::add($productLog);
                    }

                }
                $db->commit();
                $reuslt['state'] = "1";
                $reuslt['message'] = "料件号已修改成功";
            } catch (Exception $e) {
                $reuslt['message'] = $e->getMessage();
                $db->rollBack();
            }
        }
        echo Zend_Json::encode($reuslt);
    }

    public function beianAction()
    {
        $reuslt = array('state' => 0);
        if ($this->_request->isPost()) {
            try {
                $param = $this->_request->getPost();
                $db = Common_Common::getAdapter();
                $db->beginTransaction();
                if ($param['product_id']) {
                    $productInfo = Service_Product::getByField($param['product_id']);
                    if (empty($productInfo)) {
                        throw new Exception('提交数据出错');
                    }
                    if ($productInfo['product_status'] == "1") {
                        throw new Exception('产品已备案');
                    }
                    $goods_id = $productInfo['goods_id'];
                    $productList = Service_Product::getByCondition(array('goods_id' => $goods_id), "*");
                    foreach ($productList as $product) {
                        $updateProduct = array(
                            'product_status' => '1',
                            'product_update_time' => date("Y-m-d H:i:s"),
                        );
                        Service_Product::update($updateProduct, $product['product_id'], "product_id");
                        $productLog = array(
                            'product_id' => $product['product_id'],
                            'pl_type' => '0',
                            'customer_id' => $product['customer_id'],
                            'pl_add_time' => date("Y-m-d H:i:s"),
                            'pl_statu_pre' => $product['product_status'],
                            'pl_statu_now' => 1,
                            'pl_note' => '料件号[' . $goods_id . ']人工备案',
                            'pl_ip' => Common_Common::getIP(),
                            'user_id' => $this->user_id,
                        );
                        Service_ProductLog::add($productLog);
                    }
                    Service_ProductGoods::update(array('pg_status' => 1), $goods_id, 'goods_code');
                }
                $db->commit();
                $reuslt['state'] = "1";
                $reuslt['message'] = "已备案成功";
            } catch (Exception $e) {
                $reuslt['message'] = $e->getMessage();
                $db->rollBack();
            }
        }
        echo Zend_Json::encode($reuslt);
    }

    public function batchEditElementAction()
    {
        $result = array("ask" => 1, "message" => "", 'error' => array(), 'data' => array());
        $xlsData = Service_Product::getXLSData($_FILES, 'elementfile');
        //var_dump($xlsData);
        //exit;
        $hsCodeArr = array();
        $excelHead = $xlsData[0];
        $hs_code = "";
        foreach ($xlsData as $key => $value) {
            if ($key == 0) continue;
            if (!in_array($value[2], $hsCodeArr)) {
                $hsCodeArr[] = $value[2];
            }
            if (count($hsCodeArr) > 1) {
                $result['ask'] = 0;
                $result['message'] = "文件有多个海关编码";
                break;
            }
        }
        if ($result['ask'] == "0") die(Zend_Json::encode($result));
        $hs_code = $hsCodeArr[0];
        $hs_condition = array(
            'hs_code' => $hsCodeArr[0],
            'hs_code_status' => 1
        );

        $aHsCodes = Service_Hscodes::getByCondition($hs_condition);
        if (empty($aHsCodes)) {
            $result['ask'] = 0;
            $result['message'] = '海关编码[' . $hsCodeArr[0] . ']非法';
            die(Zend_Json::encode($result));
        }
        $hsElementList = Service_HsElement::getByCondition(array(
            'hs_code' => $hsCodeArr[0],
            'he_status' => 1
        ), "*", 0, 0, 'he_sort asc');
        if (empty($hsElementList)) {
            $result['ask'] = 0;
            $result['message'] = '异常：海关编码[' . $hsCodeArr[0] . ']没有申报要素';
            die(Zend_Json::encode($result));
        }
        $ascii = ord('A');
        $aError = "";
        foreach ($hsElementList as $key => $hsElementRow) {
            $i = $key + 4;
            if (trim($excelHead[$i]) != $hsElementRow['he_name']) {
                $aError .= '表头错误：' . chr($ascii + $i) . '1单元格应该为"' . $hsElementRow['he_name'] . '";';
            }
        }
        if ($aError != "") {
            $result['ask'] = 0;
            $result['message'] = $aError;
            die(Zend_Json::encode($result));
        }
        $line = 1;
        $unicodeSpacePattern = '/\x{200b}/u';
        foreach ($xlsData as $excelRowIndex => $excelRow) {
            $data = array(
                'ask' => '1',
                'message' => '',
                'customer_code' => trim($excelRow[0]),
                'product_sku' => trim($excelRow[1]),
                'hs_code' => trim($excelRow[2]),
                'hs_goods_name' => trim($excelRow[3])
            );
            if ($excelRowIndex == 0) continue;
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $line++;
                $customerCode = trim($excelRow[0]);
                $customer = Service_Customer::getByField($customerCode, 'customer_code');

                if (empty($customer)) {

                    throw new Exception('第' . $line . '行：客户[' . $customerCode . ']不存在');
                }/*elseif ('FX' !== strtoupper($customer['customer_platform']))
                {
                    throw new Exception('第' . $line . '行：客户[' . $customerCode . ']不是分销平台客户');
                }*/
                $productSku = trim($excelRow[1]);
                if (empty($productSku)) {
                    throw new Exception('第' . $line . '行：产品SKU不能为空');
                }
                $where = array(
                    'customer_code' => $customerCode,
                    'product_sku' => $productSku
                );
                $aProduct = Service_Product::getByWhere($where);
                if (empty($aProduct)) {
                    throw new Exception('第' . $line . '行：客户[' . $customerCode . ']不存在产品SKU[' . $productSku . ']');

                }
                if ($aProduct['hs_code'] != $hs_code) {
                    $updateProduct = array(
                        'hs_code' => $hs_code,
                        'hs_goods_name' => trim($excelRow[3])
                    );
                    Service_Product::update($updateProduct, $aProduct['product_id'], 'product_id');
                    $log = "hs_code:" . $aProduct['hs_code'] . "=>" . $hs_code . "&hs_goods_name:" . $aProduct['hs_goods_name'] . "=>" . trim($excelRow[3]);
                    $phsElementList = Service_HsElementMap::getByCondition(array('product_id' => $aProduct['product_id']), "*");
                    foreach ($phsElementList as $k => $v) {
                        Service_HsElementMap::delete($v['hem_id'], 'hem_id');
                        $he = Service_HsElement::getByField($v['he_id'], 'he_id', "*");
                        $log .= "删除申报要素:" . $he['he_name'] . "=>" . $v['hem_detail'] . ";";
                    }
                    $logRow = array(
                        'product_id' => $aProduct['product_id'],
                        'pl_type' => '0',
                        'customer_id' => 0,
                        'pl_add_time' => date("Y-m-d H:i:s"),
                        'pl_statu_pre' => '1',
                        'pl_statu_now' => '1',
                        'pl_note' => '修改备案信息:' . $log,
                        'pl_ip' => Common_Common::getIP(),
                        'user_id' => $this->user_id,
                        'account_id' => 0
                    );
                    Service_ProductLog::add($logRow);
                    foreach ($hsElementList as $key => $hsElementRow) {
                        $i = $key + 4;
                        $elementMap = array();
                        $elementMap['he_id'] = $hsElementRow['he_id'];
                        $elementMap['product_id'] = $aProduct['product_id'];
                        $element = preg_replace($unicodeSpacePattern, '', trim($excelRow[$i]));
                        $elementMap['hem_detail'] = strtoupper(trim($element));//strtoupper(trim($element, chr(194).chr(160)));
                        $elementMap['hem_add_time'] = date('Y-m-d H:i:s');
                        Service_HsElementMap::add($elementMap);
                    }
                } else {
                    $log = "";
                    $updateProduct = array(
                        'hs_code' => $hs_code,
                        'hs_goods_name' => trim($excelRow[3])
                    );
                    Service_Product::update($updateProduct, $aProduct['product_id'], 'product_id');
                    $log = "hs_code:" . $aProduct['hs_code'] . "=>" . $hs_code . "&hs_goods_name:" . $aProduct['hs_goods_name'] . "=>" . trim($excelRow[3]);
                    foreach ($hsElementList as $key => $hsElementRow) {
                        $i = $key + 4;

                        if (preg_match("/(\xC2\xA0)/u", $excelRow[$i])) {
                            $msg = '海关申报要素含有网页空白符,请把标识位([?])的空白删除或者改成半角空格: ' . preg_replace("/(\xC2\xA0)/u", "[?]", $excelRow[$i]);
                            throw new Exception($msg);
                        }
                        $hem = Service_HsElementMap::getByCondition(array('he_id' => $hsElementRow['he_id'], 'product_id' => $aProduct['product_id']), "*");
                        $he = Service_HsElement::getByField($hsElementRow['he_id'], 'he_id', "*", 0, 0, 'he_sort asc');
                        $elementMap = array();
                        $elementMap['he_id'] = $hsElementRow['he_id'];
                        $elementMap['product_id'] = $aProduct['product_id'];
                        $element = preg_replace($unicodeSpacePattern, '', trim($excelRow[$i]));
                        $elementMap['hem_detail'] = strtoupper(trim($element));//strtoupper(trim($element, chr(194).chr(160)));
                        $elementMap['hem_add_time'] = date('Y-m-d H:i:s');
                        //Service_HsElementMap::add($elementMap);
                        //$log.="添加申报要素:".$he['he_name']."=>".$elementMap['hem_detail'].";";
                        if (empty($hem)) {
                            /*$elementMap = array();
                            $elementMap['he_id']        = $hsElementRow['he_id'];
                            $elementMap['product_id']   = $aProduct['product_id'];
                            $element                    = preg_replace($unicodeSpacePattern, '', trim($excelRow[$i]));
                            $elementMap['hem_detail']   = strtoupper(trim($element));//strtoupper(trim($element, chr(194).chr(160)));
                            $elementMap['hem_add_time'] = date('Y-m-d H:i:s');*/
                            //Service_HsElementMap::add($elementMap);
                            $log .= "添加申报要素:" . $he['he_name'] . "=>" . $elementMap['hem_detail'] . ";";
                        } else {
                            /*$updateHem = array(
                                'hem_detail'=>strtoupper(preg_replace($unicodeSpacePattern, '', trim($excelRow[$i]))),
                                'hem_add_time'=>date('Y-m-d H:i:s')
                            );
                            Service_HsElementMap::update($updateHem,$hem[0]['hem_id'],"hem_id");*/
                            Service_HsElementMap::delete($hem[0]['hem_id'], 'hem_id');
                            $log .= "修改申报要素[" . $he['he_name'] . "]:" . $hem[0]['hem_detail'] . "=>" . $elementMap['hem_detail'] . ";";
                        }
                        Service_HsElementMap::add($elementMap);
                    }
                    $logRow = array(
                        'product_id' => $aProduct['product_id'],
                        'pl_type' => '0',
                        'customer_id' => 0,
                        'pl_add_time' => date("Y-m-d H:i:s"),
                        'pl_statu_pre' => '1',
                        'pl_statu_now' => '1',
                        'pl_note' => '修改备案信息:' . $log,
                        'pl_ip' => Common_Common::getIP(),
                        'user_id' => $this->user_id,
                        'account_id' => 0
                    );
                    Service_ProductLog::add($logRow);
                }
                $db->commit();
                $data['ask'] = "1";
                $data['message'] = "备案信息修改成功";
            } catch (Exception $e) {
                $data['message'] = $e->getMessage();
                $data['ask'] = "0";
                $db->rollBack();
            }
            $result['data'][] = $data;
        }
        echo Zend_Json::encode($result);
    }

    public function batchEditImeiAction()
    {
        $result = array("ask" => 1, "message" => "", 'error' => array(), 'data' => array());
        $xlsData = Service_Product::getXLSData($_FILES, 'elementfile3');
        //var_dump($xlsData);
        //exit;
        foreach ($xlsData as $key => $value) {
            if ($key == 0) continue;
            $customerCode = trim($value[0]);
            $productSku = trim($value[1]);
            $data = array(
                'ask' => '1',
                'message' => '',
                'customer_code' => $customerCode,
                'product_sku' => $productSku,
                'is_scan_imei' => trim($value[2]),
                //'hs_goods_name'=>trim($excelRow[3])
            );
            $p = Service_Product::getByCondition(array('customer_code' => $customerCode, 'product_sku' => $productSku), "*");
            if (empty($p)) {
                $resultData['ask'] = 0;
                $resultData['message'] = "客户" . $value[0] . "不存在产品" . $value[1];
                $result['data'][] = $resultData;
                continue;
            }
            $aProduct = $p[0];
            $is_scan_imei = "0";
            if (trim($value[2]) == "是") $is_scan_imei = 1;
            $updateProduct = array(
                'is_scan_imei' => $is_scan_imei,
                'product_update_time' => date("Y-m-d H:i:s")
            );
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                Service_Product::update($updateProduct, $aProduct['product_id'], "product_id");
                $logRow = array(
                    'product_id' => $aProduct['product_id'],
                    'pl_type' => '0',
                    'customer_id' => $aProduct['customer_id'],
                    'pl_add_time' => date("Y-m-d H:i:s"),
                    'pl_statu_pre' => $aProduct['product_status'],
                    'pl_statu_now' => $aProduct['product_status'],
                    'pl_note' => '是否扫描IMEI号:' . $aProduct['is_scan_imei'] . "=>" . $is_scan_imei,
                    'pl_ip' => Common_Common::getIP(),
                    'user_id' => $this->user_id,
                );
                Service_ProductLog::add($logRow);
                $db->commit();
                $data['ask'] = "1";
                $data['message'] = "修改成功";
            } catch (Exception $e) {
                $data['message'] = $e->getMessage();
                $data['ask'] = "0";
                $db->rollBack();
            }
            $result['data'][] = $data;
        }
        echo Zend_Json::encode($result);
    }

    /* @desc:根据料件号更新重量
     *
     */
    public function editWeightByGoodsidAction()
    {
        $goodsId = trim($this->_request->getParam('goodsId', ''));
        $weight = trim($this->_request->getParam('weight', ''));
        $obj = new Service_ProductProcess();
        $result = $obj->editWeightByGoodsId($goodsId, $weight);
        die(json_encode($result));
    }

    //当特定用户的尺寸或重量为设置，可以调用此方法进行更新
    public function updateWeightSizeAction()
    {
        if ($this->_request->isPost()) {
            $obj = new Service_ProductProcess();
            $result = $obj->updateSizeWeight();
            $this->view->error = $obj->getError();
        }
        echo Ec::renderTpl($this->tplDirectory . "update_weight_size.tpl", 'layout');
        exit;
    }

    /**
     * @date 2022/7/16
     * @todo 批量导入商品
     * @auther 46935
     */
    public function batchImportAction()
    {
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        try {
            $upload = new Process_Upload();
            $savePath = APPLICATION_PATH . '/../data/product/';
            $uploadInfo = $upload->uploadXls($savePath, 'batch_product_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $uploadProcess = new Process_ProductUpload();
            $uploadProcess->setFilePath($filePath);
            $data = $uploadProcess->getData();
            if (empty($data)) {
                throw new Exception('上传商品信息不存在');
            }
            $db = Common_Common::getAdapter();
            foreach ($data as $productInfo) {
                $uploadProcess->validateProduct($productInfo);
                $db->beginTransaction();
                try {
                    if (!empty($productInfo['error'])) {
                        throw new Exception(implode(",", $productInfo['error']));
                    }
                    $productAdd = [
                        'goods_id' => $productInfo['goods_id'],
                        'product_sku' => $productInfo['product_sku'],
                        'product_barcode' => $productInfo['product_barcode'],
                        'customer_code' => $productInfo['customer_code'],
                        'customer_id' => $productInfo['customer_id'],
                        'product_title' => $productInfo['product_title'],
                        'product_title_en' => $productInfo['product_title_en'],
                        'product_status' => $productInfo['product_status'],
                        'product_receive_status' => $productInfo['product_receive_status'],
//                            'is_recorded'=>'',
                        'hs_goods_name' => $productInfo['hs_goods_name'],
                        'hs_code' => $productInfo['hs_code'],
                        'currency_code' => $productInfo['currency_code'],
                        'pu_code' => $productInfo['pu_code'],
                        'product_length' => $productInfo['product_length'],
                        'product_width' => $productInfo['product_width'],
                        'product_height' => $productInfo['product_height'],
                        'product_net_weight' => $productInfo['product_net_weight'] ?: 0,
                        'product_weight' => $productInfo['product_weight'],
//                            'product_sales_value'=>'',
//                            'product_purchase_value'=>'',
                        'product_declared_value' => $productInfo['product_declared_value'],
                        'product_is_qc' => $productInfo['product_is_qc'],
                        'product_barcode_type' => $productInfo['product_barcode_type'],
                        'product_type' => 0,
                        'pc_id' => $productInfo['pc_id'],
//                            'pce_id'=>'',
                        'product_add_time' => date("Y-m-d H:i:s"),
//                            'product_update_time'=>'',
//                            'have_asn'=>'',
//                            'is_accessories'=>'',
//                            'has_invoice'=>'',
//                            'distributor_id'=>'',
                        'model_serial' => $productInfo['model_serial'],
                        'with_battery' => $productInfo['with_battery'],
                        'battery_type' => $productInfo['battery_type'],
//                            'hs_billing'=>$productInfo[''],
//                            'group_class'=>'',
                        'hs_declaration_elements' => '',
//                            'battery_detail'=>'',
//                            'form_type'=>'',
//                            'is_scan_imei'=>'',
//                            'hs_code_ciq'=>'',
//                            'putrec_seqno'=>'',
//                            'p_model'=>'',

                    ];
                    $goodsId = $productInfo['goods_id'];
                    if ($productInfo['product_status'] == 1) {
                        if (empty($productInfo['goods_id'])) {
                            $goodsId = Service_CustomerProcess::generateGoodsId($productInfo['customer_id']);
                            $productAdd['goods_id'] = $goodsId;
                        }
                    }
                    $newProductId = Service_Product::add($productAdd);
                    if (!$newProductId) {
                        throw new Exception("添加商品错误");
                    }
                    $productLog = array(
                        'product_id' => $newProductId,
                        'pl_type' => '0',
                        'customer_id' => $productAdd['customer_id'],
                        'pl_add_time' => date("Y-m-d H:i:s"),
                        'pl_statu_pre' => '0',
                        'pl_statu_now' => $productInfo['product_status'],
                        'pl_note' => '批量导入商品:[' . $productInfo['product_sku'] . '] Create',
                        'pl_ip' => Common_Common::getIP(),
                    );
                    Service_ProductLog::add($productLog);
                    if ($productInfo['hs_code']) {
                        $hsUom = Service_HsUom::getByField($productAdd['hs_code'], 'hs_code');
                        $addHuosMap = [
                            'product_id' => $newProductId,
                            'hu_id' => $hsUom['hu_id'],
                            'hum_quantity_law' => $productInfo['hum_quantity_law'],
                            'hum_quantity_second' => $productInfo['hum_quantity_second'],
                            'hum_add_time' => date("Y-m-d H:i:s")
                        ];

                        Service_HsUomMap::add($addHuosMap);
                    }
                    if ($productInfo['he_detail']) {
                        $elements = [];
                        foreach ($productInfo['he_detail'] as $heDetail) {
                            $addHeDetail = [
                                'product_id' => $newProductId,
                                'he_id' => $heDetail['he_id'],
                                'hem_detail' => $heDetail['he_detail'],
                                'hem_add_time' => date("Y-m-d H:i:s")
                            ];
                            $elements[] = $heDetail['he_detail'] ? $heDetail['he_detail'] : "/";
                            Service_HsElementMap::add($addHeDetail);
                        }
                        $productAdd['product_id'] = $newProductId;
                        $goods_key = Service_Product::generateGoodsKey($productInfo);
                        $aGoods = Service_ProductGoods::getByField($goods_key, 'goods_key');
                        //复制product_goods
                        if (empty($aGoods)) {
                            $product_model = implode(',', $elements);
                            $hs_key = Service_Product::generateHsKey($productInfo['hs_code'], $productInfo['hs_goods_name'], $product_model);
                            $aGoods = array(
                                'goods_code' => $productInfo['goods_id'] ? $productInfo['goods_id'] : $goodsId,
                                'goods_key' => $goods_key,
                                'hs_key' => $hs_key,
                                'product_id' => $newProductId,
                                'pg_update_time' => date("Y-m-d H:i:s"),
                                'pg_status' => -1,
                            );
                            if (!(Service_ProductGoods::add($aGoods))) {
                                throw new Exception("添加料件号失败");
                            }
                        }
                    }
                    $db->commit();
                } catch (Exception $e) {
                    $return['error'][] = $productInfo['product_sku'] . ':' . $e->getMessage();
                    $db->rollBack();
                }
            }
            $return['state'] = 1;
            $return['message'] = '导入成功';
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @date 2022/7/16
     * @todo 批量导入检查
     * @auther 46935
     */
    public function importCheckAction()
    {
        $return = [
            'state' => 0,
            'message' => '',
            'file_name' => '',
            'file_id' => '',
            'error' => [],
        ];
        try {
            $upload = new Process_Upload();
            $savePath = APPLICATION_PATH . '/../data/product/';
            $uploadInfo = $upload->uploadXls($savePath, 'batch_product_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $uploadProcess = new Process_ProductUpload();
            $uploadProcess->setFilePath($filePath);
            $data = $uploadProcess->getData();
            if (empty($data)) {
                throw new Exception('上传商品信息不存在');
            }
            $hasError = false;
            foreach ($data as &$productInfo) {
                $uploadProcess->validateProduct($productInfo);
                if ($productInfo['error']) {
                    $hasError = true;
                }
            }
            if ($hasError) {
                $phpExcel = PHPExcel_IOFactory::load($filePath);
                $sheet = $phpExcel->getSheet(0);
                $maxColumn = $sheet->getHighestDataColumn();
                $maxIndex = PHPExcel_Cell::columnIndexFromString($maxColumn);
                $maxColumnChar = PHPExcel_Cell::stringFromColumnIndex($maxIndex);
                $index = 2;
                foreach ($data as $product) {
                    $sheet->setCellValue($maxColumnChar . $index, implode(',', $product['error']));
                    $index++;
                }
                $writer = PHPExcel_IOFactory::createWriter($phpExcel, 'Excel5');
                $fileName = md5(date("Ymdhis") . rand(100, 999)) . '.xls';
                $writer->save($savePath . $fileName);
                $return['file_name'] = $fileName;
                $return['message'] = "包含错误信息";
            } else {
                $return['message'] = '预检完成，数据没有错误信息';
            }
            $return['state'] = 1;
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @date 2022/7/16
     * @todo 下载检查结果
     * @auther 46935
     */
    public function downloadResultAction()
    {
        $fileName = $this->_request->getParam('file_name');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        $fullPath = APPLICATION_PATH . "/../data/product" . '/' . $fileName;
        if (file_exists($fullPath)) {
            $filename = basename($fullPath);
            header("Content-Type: APPLICATION/OCTET-STREAM");
            //Force the download
            $header = "Content-Disposition: attachment; filename=" . $filename . ";";
            header($header);
            echo file_get_contents($fullPath);
            exit;
        }
        //方法2

    }
}
