<?php

class Merchant_ProductController extends Ec_Controller_Action
{
    /* public function init(){
        $params = self::getFrontController()->getRequest()->getParams();
        $this->view->ac = $params['action'];
    } */
    /*初始化*/
    public function preDispatch()
    {
        $this->tplDirectory = "merchant/views/product/";
        $params = self::getFrontController()->getRequest()->getParams();
        $this->view->ac = $params['action'];
        $this->view->url = $_SERVER['REDIRECT_URL'];
        //echo $this->view->url;exit;
    }

    /*选择产品*/
    public function repositoryAction()
    {
        $page = $this->getRequest()->getParam('page', 1);
        $pageSize = $this->getRequest()->getParam('pageSize', 20);
        $condition = array(
            'customer_id' => $this->_customerAuth['id'],
            'product_type' => 0,
            'product_sku' => $this->getRequest()->getParam('sku'),
            'product_title' => $this->getRequest()->getParam('title'),
            'pc_id' => $this->getRequest()->getParam('type'),
            'comefrom' => 'psearchdialog',
            'product_status' => '1',
        );
        $from = $this->_request->getParam('from', '');
        //判断参数的有效性
        $inject = true;
        switch ($from) {
            case 'product':
                $inject = false;
                break;
            case 'asn':
                $inject = false;
                break;
            case 'productCombine':
                $inject = false;
                break;
            case 'order':
                $condition['product_type'] = '';
                $inject = false;
                break;
        }

        $this->view->from = $from;
        $this->view->params = $condition;
        $this->view->pageSize = $pageSize;
        $this->view->page = $page;
        $this->view->count = Service_Product::getByCondition($condition, 'count(*)');
        $result = Service_Product::getByCondition($condition, '*', 'product_id DESC', $pageSize, $page);
        $category = Common_DataCache::getProductCategory();

        if (!empty($result)) {
            foreach ($result as $keyp => $valuep) {
                if (isset($category[$valuep['pc_id']])) {
                    $result[$keyp]['pc_name'] = $category[$valuep['pc_id']]['pc_name'];
                } else {
                    $result[$keyp]['pc_name'] = '';
                }
                if ($valuep['product_type'] == '1') {
                    $product_declared_value = Service_Product::getCombineDeclaredValue($valuep['product_id']);
                    if ($product_declared_value) {
                        $result[$keyp]['product_declared_value'] = $product_declared_value;
                    }
                }

            }
        }
        $this->view->result = $result;
        $this->view->category = $category;
        $this->view->user = $this->_customerAuth;
        echo $this->view->render($this->tplDirectory . "repository.tpl");
    }

    /*产品列表*/
    public function indexAction()
    {
        $page = $this->getRequest()->getParam('page', 1);
        $pageSize = $this->getRequest()->getParam('pageSize', 20);
        $condition = array(
            'customer_id' => $this->_customerAuth['id'],
            'comefrom' => 'psearchdialog',
            'product_type' => $this->getRequest()->getParam('product_type'),
            'product_sku' => trim($this->getRequest()->getParam('sku')),
            'product_title' => trim($this->getRequest()->getParam('title')),
            'pc_id' => $this->getRequest()->getParam('type'),
            'product_start_time' => trim($this->getRequest()->getParam('start_time')),
            'product_end_time' => trim($this->getRequest()->getParam('end_time')),
            'product_status' => $this->getRequest()->getParam('status'),
        );
        $this->view->condition = $condition;
        $this->view->params = $condition;
        $this->view->pageSize = $pageSize;
        $this->view->page = $page;
        $this->view->count = Service_Product::getByCondition($condition, 'count(*)');
        $this->view->result = Service_Product::getByCondition($condition, '*', 'product_id DESC', $pageSize, $page);
        $this->view->category = Common_DataCache::getProductCategory();
        $this->view->user = $this->_customerAuth;
        echo  Ec::renderTpl($this->tplDirectory . "index.tpl", 'noleftlayout');

    }

    /*普通产品新增修改*/
    public function addAction()
    {


        $customer = $this->_customerAuth;
        $customerId = $customer['id'];
        //session_start();
        $uom = Common_DataCache::getProductUom();
        $array = array(
            '001' => '台',
            '002' => '座',
            '003' => '辆',
            '004' => '艘',
            '005' => '架',
            '006' => '套',
            '007' => '个',
            '008' => '只',
            '009' => '头',
            '010' => '张',
            '011' => '件',
            '012' => '支',
            '013' => '枝',
            '014' => '根',
            '015' => '条',
            '016' => '把',
            '017' => '块',
            '018' => '卷',
            '019' => '副',
            '020' => '片',
            '021' => '组',
            '022' => '份',
            '023' => '幅',
            '025' => '双',
            '026' => '对',
            '027' => '棵',
            '028' => '株',
            '029' => '井',
            '031' => '盘',
            '034' => '筒',
            '037' => '盆',
            '120' => '箱',
            '121' => '批',
            '122' => '罐',
            '123' => '桶',
            '124' => '扎',
            '125' => '包',
            '126' => '箩',
            '127' => '打',
            '128' => '筐',
            '129' => '罗',
            '130' => '匹',
            '131' => '册',
            '132' => '本',
            '133' => '发',
            '134' => '枚',
            '135' => '捆',
            '136' => '袋',
            '139' => '粒',
            '140' => '盒',
            '141' => '合',
            '142' => '瓶',
            '163' => '部',
        );
        /*$newuom=array();
        foreach ($uom as $key => $value) {
            if (in_array($value['name'],$array)) {
                $newuom[$key]['code']=$value['code'];
                $newuom[$key]['name']=$value['name'];
            }
        }*/
        $this->view->uom = $array;
        $this->view->category = Common_DataCache::getProductCategory();

        $this->view->session_name = session_name();
        $this->view->sessionid = session_id();

        $productId = $this->_request->getParam('productId', '');

        if ($productId) {
            $productInfo = Service_Product::getProductAllInfo($productId, $customerId);
            if ($productInfo) {
                if ($productInfo['have_asn'] == '1') {
                    exit('有ASN单不能更改');
                }
                if ($productInfo['product_type'] == 1) {
                    //exit('cccccccc');
                    $this->_redirect("/merchant/product/combine/productId/" . $productId);
                    exit;
                }
                //                 print_r($productInfo);exit;

                // 获取供应商数据
                $distributor = Service_Distributor::getByPrimaryKey($productInfo['distributor_id']);

                if ($distributor) {
                    $productInfo['distributor'] = $distributor;
                }
                $this->view->productInfo = $productInfo;
            } else {
                exit('产品无效');
            }
        }
        //以下是复制商品
        $copyproductId = $this->_request->getParam('copyproductId', '');

        if ($copyproductId) {
            $productInfo = Service_Product::getProductAllInfo($copyproductId, $customerId);
            if ($productInfo) {
                if ($productInfo['product_type'] == 1) {
                    //exit('cccccccc');
                    $this->_redirect("/default/error/error/message/" . "商品无效");
                    exit;
                }
                if($productInfo['product_status']!='1'){

                }

                // 获取供应商数据
                $distributor = Service_Distributor::getByPrimaryKey($productInfo['distributor_id']);

                if ($distributor) {
                    $productInfo['distributor'] = $distributor;
                }
                $this->view->productInfo = $productInfo;
            } else {
                exit('产品无效');
            }
        }

        //$action = '增加';
        $action = Ec_Lang::getInstance()->getTranslate('ProductAdd');
        $actionLabel = 'add';
        if (!empty($productId)) {
            $action = Ec_Lang::getInstance()->getTranslate('ProductModify');
            $actionLabel = 'update';
        }
        $this->view->product_id = $productId;
        $this->view->action = $action;
        $this->view->actionLabel = $actionLabel;
        $this->view->customer = $customer;
        $currencyAll = Common_DataCache::getCurrency();
        $this->view->currency = $currencyAll;
        //echo Ec::renderTpl($this->tplDirectory . "add-all.tpl",'layout-iframe');
        if (empty($productId)) {
            //echo $this->view->render($this->tplDirectory . "add-all.tpl");
            echo Ec::renderTpl($this->tplDirectory . "add-all.tpl", 'noleftlayout');
            //echo Ec::renderTpl($this->tplDirectory . "add-all.tpl",'layout-iframe');
        } else {
            echo Ec::renderTpl($this->tplDirectory . "add-all.tpl", 'noleftlayout');
        }

    }

    /*产品新增和保存*/
    public function addSaveAction()
    {
        $state = array(
            'statusCode' => 200,
            'message' => Ec_Lang::getInstance()->getTranslate('ProductAdd') . Ec_Lang::getInstance()->getTranslate('success') . '！',
            'navTabId' => 'productList',
            'callbackType' => 'forward',
            'forwardUrl' => '/merchant/product/add'
        );
        $user = $this->_customerAuth;

        /* print_r($user);
        exit; */
        $picUrl = $this->_request->getParam('picUrl', array());
        $picLink = $this->_request->getParam('picLink', array());

        $hs_elements = array();
        $he_ids = $this->_request->getParam('he_id', array());
        foreach ($he_ids as $he_id => $hevalue) {
            $hs_elements[] = array('he_id' => $he_id, 'hem_detail' => trim($hevalue));
        }


        $time = date('Y-m-d H:i:s');
        $data = array(
            'product_sku' => trim($this->getRequest()->getParam('product_sku')),
            'customer_code' => $user['code'],
            'customer_id' => $user['id'],
            'product_title_en' => trim($this->getRequest()->getParam('title_en')),
            'product_title' => trim($this->getRequest()->getParam('title')),
            'pu_code' => $this->_request->getParam('product_unit', ''),
            'currency_code' => $this->_request->getParam('currency_code'),
            //'product_length'		=> trim($this->getRequest()->getParam('length','0')),
            //'product_width'			=> trim($this->getRequest()->getParam('width','0')),
            //'product_height'		=> trim($this->getRequest()->getParam('height','0')),
            'product_weight' => trim($this->getRequest()->getParam('product_weight', '0')),
            'product_declared_value' => trim($this->getRequest()->getParam('declared_value')),
            'product_barcode_type' => $this->getRequest()->getParam('barcode_type'),
            'model_serial' => $this->getRequest()->getParam("model_serial", ""),
            'product_type' => 0,
            //'pc_id'					=> $this->getRequest()->getParam('type'),
            'product_add_time' => $time,
            'hs_goods_name' => trim($this->getRequest()->getParam('hs_goods_name')),
            'hs_code' => trim($this->getRequest()->getParam('hscode')),
            'hs_element' => $hs_elements,
            'hu_id' => $this->_request->getParam('hu_id', ''),
            'pu_code_law' => $this->_request->getParam('pu_code_law', ''),
            'pu_code_second' => $this->_request->getParam('pu_code_second', ''),
            'is_accessories' => $this->_request->getParam('is_accessories', '0'),
            'has_invoice' => $this->_request->getParam('has_invoice'),
            'with_battery' => $this->_request->getParam("with_battery", ""),
            'battery_type' => $this->_request->getParam("battery_type", ""),
            // 'battery_detail'        =>$this->_request->getParam("battery_detail",""),
            'distributor_id' => $this->_request->getParam('distributor_id', 0), // 供应商ID
            'distributor_code' => trim($this->_request->getParam('distributor_code', '')), // 供应商代码
        );
        // if($data['with_battery']=="1"){
        //     $data['battery_type'] = $this->_request->getParam("battery_type","");
        // }
        if ($data['battery_type'] == "6") {
            $data['battery_detail'] = $this->_request->getParam("battery_detail", "");
        } else {
            $data['battery_detail'] = '';
        }
        // print_r($data);exit;
        if (1 == $this->getRequest()->getParam('barcode_type')) {
            $data['product_barcode'] = $this->getRequest()->getParam('barcode');
        } else {
            $data['product_barcode'] = $user['code'] . '-' . $this->getRequest()->getParam('sku');
        }
        //print_r($data);exit;
        $productId = $this->_request->getParam('product_id', '');

        //print_r($this->_request->getParams());
        //exit;
        //echo $productId;exit;
        if ($productId) {
            $result = Service_Product::updateProductTransaction($data, $productId, $user['id'], $picUrl, $picLink);
        } else {
            $result = Service_Product::createProductTransaction($data, $user['code'], $picUrl, $picLink);
        }


        //print_r($result);exit;
        //Common_Common::outJson($result);
        die(json_encode($result));

        $lastId = Service_Product::add($result);
        if (empty($lastId)) {
            $state = array(
                'statusCode' => 300,
                'message' => '新增产品出错，请重新添加！'
            );
        } else {
            $path = './upload/merchant/' . $user['code'] . '/product';
            $isDir = Common_Common::createPath($path);
            if ($isDir) {
                $imgs = array();
                $upload = Common_Common::uploadImg($_FILES, 'pic', $path, false);
                if ($upload['error']) {
                    $state = array(
                        'statusCode' => 300,
                        'message' => '产品基本信息添加成功，上传图片产生错误：' . strip_tags($upload['msg'])
                    );
                    Common_Common::outJson($state);
                }
                if (!empty($upload['msg'])) {
                    foreach ($upload['msg'] as $key => $file) {
                        $flag = Service_ProductAttached::add(array(
                            'pa_path' => trim($path, ".") . '/' . $file['file_name'],
                            'pa_file_type' => 'img',
                            'product_id' => $lastId
                        ));
                        if (empty($flag)) {
                            $state = array(
                                'statusCode' => 300,
                                'message' => '产品基本信息添加成功，保存图片产生错误！'
                            );
                        }
                    }
                }
            }
        }

    }

    /*应该没在用*/
    public function editAction()
    {
        $id = $this->getRequest()->getParam('id');
        $state = array(
            'statusCode' => 300,
            'message' => '参数错误，载入失败！',
            'callbackType' => 'closeCurrent'
        );
        if (!empty($id) || is_int($id)) {
            $result = Service_Product::getCustomQuery('*', "where product_id=$id");
            if (!empty($result)) {
                $result = $result[0];
                $result['attached'] = Service_ProductAttached::getCustomQuery('*', "where product_id=$id and pa_file_type='img' order by pa_sort");
                $this->view->uom = Common_DataCache::getProductUom();
                $this->view->category = Common_DataCache::getProductCategory();
                $this->view->result = $result;
                echo $this->view->render($this->tplDirectory . "edit.tpl");
                return true;
            }
        }
        Common_Common::outJson($state);
    }

    /*应该没在用*/
    public function editSaveAction()
    {
        $state = array(
            'statusCode' => 200,
            'message' => '修改信息成功！',
            'navTabId' => 'productList',
            'callbackType' => 'closeCurrent'
        );
        $id = $this->getRequest()->getParam('eid');
        $user = $this->_customerAuth;
        $userId = $user['id'];
        $time = date('Y-m-d H:i:s');
        $data = array(
            'product_sku' => $this->getRequest()->getParam('sku'),
            'product_title_en' => $this->getRequest()->getParam('title_en'),
            'product_title' => $this->getRequest()->getParam('title'),
            'pu_code' => $this->getRequest()->getParam('uom'),
            'product_length' => $this->getRequest()->getParam('length'),
            'product_width' => $this->getRequest()->getParam('weight'),
            'product_height' => $this->getRequest()->getParam('height'),
            'product_sales_value' => $this->getRequest()->getParam('sales_value'),
            'product_purchase_value' => $this->getRequest()->getParam('purchase_value'),
            'product_declared_value' => $this->getRequest()->getParam('declared_value'),
            'product_barcode_type' => $this->getRequest()->getParam('barcode_type'),
            'pc_id' => $this->getRequest()->getParam('type'),
            'product_add_time' => $time
        );
        if (1 == $this->getRequest()->getParam('barcode_type')) {
            $data['product_barcode'] = $this->getRequest()->getParam('barcode');
        }
        $flag = Service_Product::customUpdate($data, "product_id=$id and customer_id=$userId");
        if (empty($flag)) {
            $state = array(
                'statusCode' => 300,
                'message' => '修改信息出错，请重新提交！'
            );
        } else {
            $path = './upload/merchant/' . $user['code'] . '/product';
            $isDir = Common_Common::createPath($path);
            $count = $this->getRequest()->getParam('imgs');
            if ($isDir) {
                if (empty($count)) {
                    $imgs = array();
                    $upload = Common_Common::uploadImg($_FILES, 'pic', $path, false);
                    if ($upload['error']) {
                        $state = array(
                            'statusCode' => 300,
                            'message' => '产品基本信息修改成功，上传图片产生错误：' . strip_tags($upload['msg'])
                        );
                        Common_Common::outJson($state);
                    }
                    if (!empty($upload['msg'])) {
                        foreach ($upload['msg'] as $key => $file) {
                            $flag = Service_ProductAttached::add(array(
                                'pa_path' => trim($path, ".") . '/' . $file['file_name'],
                                'pa_file_type' => 'img',
                                'product_id' => $id
                            ));
                            if (empty($flag)) {
                                $state = array(
                                    'statusCode' => 300,
                                    'message' => '产品基本信息修改成功，保存图片产生错误！'
                                );
                            }
                        }
                    }
                } else {
                    $imgs = Service_ProductAttached::getCustomQuery('*', "where product_id=$id and pa_file_type='img' order by pa_sort");
                    $sum = empty($imgs) ? 0 : count($imgs);
                    $total = count($_FILES);
                    for ($i = 1; $i <= $total; $i++) {
                        $field = 'pic_' . $i;
                        if (!empty($_FILES[$field]['name'])) {
                            $upload = Common_Common::uploadImg($_FILES, $field, $path);
                            if ($upload['error']) {
                                $state = array(
                                    'statusCode' => 300,
                                    'message' => '产品基本信息修改成功，上传图片产生错误：' . strip_tags($upload['msg'])
                                );
                                Common_Common::outJson($state);
                            }
                            $fname = trim($path, ".") . '/' . $upload['msg']['file_name'];
                            $index = $i - 1;
                            if ($index < $sum) {
                                $flag = Service_ProductAttached::update(array('pa_path' => $fname), $imgs[$index]['pa_id'], 'pa_id');
                                $flag && Common_Common::delFile(trim($imgs[$index]['pa_path'], '/'));
                            } else {
                                Service_ProductAttached::add(array(
                                    'pa_path' => $fname,
                                    'pa_file_type' => 'img',
                                    'product_id' => $id
                                ));
                            }
                        }
                    }
                }
            }
        }
        Common_Common::outJson($state);
    }

    /*应该没在用*/
    public function delAction()
    {
        $id = $this->getRequest()->getParam('productId');
        $state = array(
            'statusCode' => 300,
            'message' => '参数错误，删除失败！'
        );
        if (!empty($id) || is_int($id)) {
            $flag = Service_Product::delete($id, 'product_id');
            if (!empty($flag)) {
                $imgs = Service_ProductAttached::getCustomQuery('pa_path', "where product_id=$id");
                if (!empty($imgs)) {
                    foreach ($imgs as $key => $val) {
                        Common_Common::delFile(trim($val['pa_path'], '/'));
                    }
                    Service_ProductAttached::delete($id, 'product_id');
                }
                $state = array(
                    'statusCode' => 200,
                    'message' => '删除成功！'
                );
            }
        }
        Common_Common::outJson($state);
    }

    /**
     * @author william-fan
     * @todo 用于组合产品的操作
     */
    public function combineAction()
    {
        $productInfo = array();
        $customer = $this->_customerAuth;
        $customerCode = $customer['code'];
        $customerId = $customer['id'];
        if ($this->_request->isPost()) {
            $picUrl = $this->_request->getParam('picUrl', array());
            $picLink = $this->_request->getParam('picLink', array());

            $row = array(
                'product_title_en' => trim($this->_request->getParam('product_title_en', '')),
                'product_title' => trim($this->_request->getParam('product_title_cn', '')),
                'product_sku' => trim($this->_request->getParam('product_sku', '')),
                'customer_id' => $customerId,
                'customer_code' => $customerCode,
                'product_type' => '1'
            );

            $subs = array();
            $subArr = $this->_request->getParam('sub', array());
            foreach ($subArr as $sub_productId => $quantity) {
                $subs[] = array(
                    'product_id' => $sub_productId,
                    'quantity' => $quantity,
                );
            }

            $row['subs'] = $subs;
            $productId = $this->_request->getParam('product_id', '');
            if ($productId) {
                $result = Service_Product::updateCombineProductTransaction($row, $customerId, $productId, $picUrl, $picLink);
            } else {
                $result = Service_Product::createCombineProductTransaction($row, $customerId, $picUrl, $picLink);
            }

            if (!empty($result['error'])) {
                foreach ($result['error'] as $k => $v) {
                    $result['error'][$k] = preg_replace('/^([0-9]+)/', '', $v);
                }
            }

            //$this->view->infoArray = $result;
            //print_r($result);

            die(Zend_Json::encode($result));
            exit;
        }
        $this->view->session_name = session_name();
        $this->view->sessionid = session_id();

        /* $page		= $this->getRequest()->getParam('page', 1);
        $pageSize	= $this->getRequest()->getParam('pageSize', 20);
        $condition	= array(
                'customer_id'		=> $this->_customerAuth['id'],
                'product_type'		=> 1,
                'product_sku'		=> $this->getRequest()->getParam('sku'),
                'product_title'		=> $this->getRequest()->getParam('title'),
                'product_add_time'	=> $this->getRequest()->getParam('time')
        );
        $this->view->params		= $condition;
        $this->view->pageSize	= $pageSize;
        $this->view->page		= $page;
        $this->view->count		= Service_Product::getByCondition($condition, 'count(*)');
        $this->view->result		= Service_Product::getByCondition($condition, '*', 'product_id DESC', $pageSize, $page); */
        $this->view->user = $this->_customerAuth;

        $productId = $this->_request->getParam('productId', '');
        $this->view->product_id = $productId;

        if (!empty($productId)) {
            $productInfo = Service_Product::getProductAllInfo($productId, $customerId);
            if ($productInfo['product_type'] == '0') {
                //exit('cccccccc');
                $this->_redirect("/merchant/product/add/productId/" . $productId);
                exit;
            }
            $this->view->productCombineInfo = $productInfo;
        }
        //print_r($productInfo);


        $actionLabel = "add";
        $action = Ec_Lang::getInstance()->getTranslate('CombineProductAdd');;

        if (!empty($productId)) {
            $action = Ec_Lang::getInstance()->getTranslate('CombineProductModify');
            $actionLabel = "update";
        }
        $this->view->action = $action;
        $this->view->is_combine = 1;/*为组合产品*/
        $this->view->actionLabel = $actionLabel;
        //var_dump(Ec::renderTpl($this->tplDirectory . "add-all.tpl",'noleftlayout'));
        echo Ec::renderTpl($this->tplDirectory . "product-create-combine.tpl", 'noleftlayout');
        //echo 'sssff';
        //echo $this->view->render($this->tplDirectory . "add-all.tpl");
    }

    /*应该没在用*/
    public function combineAddAction()
    {
        echo $this->view->render($this->tplDirectory . "combineAdd.tpl");
    }

    /**
     * @author william-fan
     * @todo用于上传图片
     */
    public function uploadimgAction()
    {
        //debug_print_backtrace();
        $return = array(
            "ask" => 0,
            "message" => "Upload Fail"
        );
        //$customerId = $this->_request->getParam('customerId', "");
        //exit;
        /*$customer=Service_Login::getLoginInfo();
            $customerId = $customer['id'];
        }*/
        $customerId = $this->_customerAuth['id'];
        //file_put_contents('test001.txt', $customerId);
        $result = Service_ProductAttached::uploadImage($_FILES['Filedata'], $customerId);
        //file_put_contents('test002.txt', var_export($result,true));
        if ($result) {
            $return['ask'] = 1;
            $return['data'] = $result;
            $return['message'] = "";
        }
        die(Zend_Json::encode($return));

        $targetFolder = '/uploads'; // Relative to the root

        $verifyToken = md5('unique_salt' . $_POST['timestamp']);
        //file_put_contents('test5.txt',$verifyToken);
        if (!empty($_FILES)) {
            $tempFile = $_FILES['Filedata']['tmp_name'];
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . '/test/uploadify' . $targetFolder;
            $targetFile = rtrim($targetPath, '/') . '/' . $_FILES['Filedata']['name'];

            // Validate the file type
            $fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // File extensions
            $fileParts = pathinfo($_FILES['Filedata']['name']);

            if (in_array($fileParts['extension'], $fileTypes)) {
                move_uploaded_file($tempFile, $targetFile);
                echo '1';
            } else {
                echo 'Invalid file type.';
            }
        }

    }

    /**
     * @author william-fan
     * @todo 查看图片
     */
    public function viewAttachAction()
    {

        $attachId = $this->_request->getParam('aid', "");

        if ($attachId) {
            $productAttach = Service_ProductAttached::getByField($attachId, 'pa_id');
            if (empty($productAttach)) {
                header("Location: /images/noimg.jpg");
                exit;
            }
            $path = APPLICATION_PATH . "/../data/images/" . $productAttach['pa_path'];

            if ($productAttach['pa_file_type'] == 'img' && file_exists($path)) {
                header('Content-Type: image/jpeg');
                echo file_get_contents($path);
            } else {
                header("Location: " . $productAttach['pa_path']);
            }
            exit();
        }

        header("Location: /images/noimg.jpg");
    }

    /**
     * @author william-fan
     * @todo 产品库存表
     */
    public function inventoryAction()
    {
        $page = $this->getRequest()->getParam('page', 1);
        $pageSize = $this->getRequest()->getParam('pageSize', 20);

        $condition = array();
        $product_sku = $this->getRequest()->getParam('sku');

        $condition = array(
            'customer_id' => $this->_customerAuth['id'],
            'product_sku' => $product_sku
        );

        $warehouse_id = $this->_request->getParam("warehouse_id", "");
        $condition["warehouse_id"] = $warehouse_id;
        $condition['customer_id'] = $this->_customerAuth['id'];
        if ($product_sku != '') {
            $product = Service_Product::getByField($product_sku, 'product_sku');
            if (!empty($product)) {
                $condition['product_id'] = $product['product_id'];
            }
        }


        /* 以下为业务逻辑方法调用 */
        $count = Service_ProductInventory::getByCondition($condition, 'count(*)');
        $return['count'] = $count;

        if ($count) {
            $cacheProduct = array();
            $rows = Service_ProductInventory::getByCondition($condition, '*', $pageSize, $page);
            foreach ($rows as $k => $v) {
                //                     if(isset($cacheProduct[$v['product_id']])){
                //                         $product = $cacheProduct[$v['product_id']];
                //                     }else{
                //                         $product = Merchant_Service_Product::getByField($v['product_id']);
                //                         $cacheProduct[$v['product_id']] = $product ;
                //                     }
                $product = Common_DataCache::getProduct($v['product_id'], $this->_customerAuth['id']);

                $rows[$k]['product_sku'] = $product['product_sku'];
                $rows[$k]['product_title_en'] = $product['product_title_en'];
                $rows[$k]['product_id'] = $product['product_id'];

                $warehouse = Common_DataCache::getWarehouse(0, $v['warehouse_id']);

                $rows[$k]['warehouse_code'] = $warehouse['warehouse_code'];
                $rows[$k]['warehouse_id'] = $warehouse['warehouse_id'];
            }

            $return['data'] = $rows;
            $return['ask'] = 1;
            $return['message'] = "";
        }
        /* echo '<pre>';
        print_r($condition);
         print_r($rows);
        echo '</pre>'; */
        $this->view->result = $rows;
        $this->view->condition = $condition;
        $warehouse = Common_DataCache::getWarehouse();
        $this->view->warehouse = $warehouse;
        $this->view->count = $count;
        $this->view->pageSize = $pageSize;
        $this->view->page = $page;
        echo Ec::renderTpl($this->tplDirectory . "product-inventory.tpl", 'layout');
    }

    /**
     * @author william-fan
     * @todo 用于获取hs_element相关信息
     */
    public function getElementAction()
    {
        if ($this->_request->isPost()) {
            $hs_code = $this->_request->getParam('hs_code', ''); //海关编码
            $product_id = $this->_request->getParam('product_id', '');
            $user = $this->_customerAuth;
            $customerId = $user['id'];
            if ($product_id) {
                //修改的情况
                $productInfo = Service_Product::getProductAllInfo($product_id, $customerId);
                $return = array(
                    'ask' => '0',
                    'hs_elements' => '',
                    'hs_uom' => '',
                    'hs_attribute' => ''
                );

                if (isset($productInfo['hs_element_maps'])) {
                    $return['ask'] = '1';
                    $hs_element_maps = $productInfo['hs_element_maps'];
                    if(!empty($hs_element_maps)){
                        $return['hs_elements'] = $productInfo['hs_element_maps'];
                    }else{
                        $condition = array(
                            'hs_code' => $hs_code,
                            'he_status' => '1'
                        );
                        $hsElements = Service_HsElement::getByCondition($condition, '*', 0, 0, 'he_sort asc');
                        if (!empty($hsElements)) {
                            $return['hs_elements'] = $hsElements;
                        }
                    }
                }
                if (isset($productInfo['hs_uom_map'])) {
                    $return['ask'] = '1';
                    $return['hs_uom'] = $productInfo['hs_uom_map'];
                }
                $hsAttribute = Service_HsAttribute::getByField($productInfo['hs_code'], 'hs_code');
                if (!empty($hsAttribute)) {
                    $return['hs_attribute'] = $hsAttribute;
                }
                die(Zend_Json::encode($return));
            } else {
                //新增的情况
                $return = array(
                    'ask' => '0',
                    'hs_elements' => '',
                    'hs_uom' => '',
                    'hs_attribute' => ''
                );
                if (empty($hs_code)) {
                    die(Zend_Json::encode($return));
                } else {
                    $hs_codes = Service_Hscodes::getByCondition(array('hs_code' => $hs_code, 'hs_code_status' => '1'));
                    if (empty($hs_codes)) {
                        die(Zend_Json::encode($return));
                    }
                }
                $condition = array(
                    'hs_code' => $hs_code,
                    'he_status' => '1'
                );
                //print_r($condition);
                $hsElements = Service_HsElement::getByCondition($condition, '*', 0, 0, 'he_sort asc');
                if (!empty($hsElements)) {
                    $return['hs_elements'] = $hsElements;
                    foreach ($hsElements as $hse => $vhse) {

                    }
                    $return['ask'] = '1';
                }
                $conditionuom = array(
                    'hs_code' => $hs_code
                );
                $hsUoms = Service_HsUom::getByCondition($condition, '*', 0, 0);

                if (!empty($hsUoms)) {
                    $hsUom = $hsUoms[0];
                    $puLaw = Service_ProductUom::getByField($hsUom['pu_code_law'], 'pu_code');
                    $hsUom['pu_name_law'] = $puLaw['pu_name'];
                    if ($hsUom['pu_code_second'] != '') {
                        $pusecond = Service_ProductUom::getByField($hsUom['pu_code_second'], 'pu_code');
                        if ($pusecond) {
                            $hsUom['pu_name_second'] = $pusecond['pu_name'];
                        }
                    }
                    $return['hs_uom'] = $hsUom;
                    $return['ask'] = '1';
                }
                $hsAttribute = Service_HsAttribute::getByField($hs_code, 'hs_code');
                if (!empty($hsAttribute)) {
                    $return['hs_attribute'] = $hsAttribute;
                }
                //print_r($return);
                die(Zend_Json::encode($return));
            }
        }
    }

    public function inventoryLogAction()
    {
        $productId = $this->_request->getParam('productId', "");
        $pi_id = $this->_request->getParam('pi_id', "");
        $inventory = Service_ProductInventory::getByField($pi_id, 'pi_id', "*");
        $customer = Service_Customer::getByField($inventory['customer_id'], "customer_id", "*");
        $inventory['customer_code'] = $customer['customer_code'];
        $warehouse = Service_Warehouse::getByField($inventory['warehouse_id'], "warehouse_id", "*");
        $inventory['warehouse_code'] = $warehouse['warehouse_code'];
        $this->view->inventory = $inventory;

        $productInventoryLog = Service_ProductInventoryLog::getByCondition(array('product_id' => $productId), "*");
        foreach ($productInventoryLog as $k => $v) {
            $warehouse = Service_Warehouse::getByField($v['warehouse_id'], "warehouse_id", "*");
            $productInventoryLog[$k]['warehouse_code'] = $warehouse['warehouse_code'];
        }

        $this->view->productInventoryLog = $productInventoryLog;

        $inventoryBatch = Service_ProductInventory::getByCondition(array('product_id' => $productId), "*");
        foreach ($inventoryBatch as $k => $v) {
            $warehouse = Service_Warehouse::getByField($v['warehouse_id'], "warehouse_id", "*");
            $inventoryBatch[$k]['warehouse_code'] = $warehouse['warehouse_code'];
        }
        $this->view->inventoryBatch = $inventoryBatch;
        echo $this->view->render($this->tplDirectory . "product-detail.tpl");
        //echo Ec::renderTpl($this->tplDirectory . "product-detail.tpl", 'layout-index');
    }

    public function playflashAction()
    {
        echo Ec::renderTpl($this->tplDirectory . 'play-flash.tpl', 'noleftlayout');
    }

    /*产品详细*/
    public function detailAction()
    {
        $productId = $this->_request->getParam("productId", "");
        $productRow = Service_Product::getByField($productId, "product_id", "*");
        if (empty($productRow)) {
            echo "找不到相关产品信息.";
            exit;
        }
        $category = Service_ProductCategory::getByField($productRow['pc_id'], "pc_id", "*");
        $productRow['category_name'] = $category['pc_name'];
        $categoryFirst = Service_ProductCategory::getByField($productRow['pce_id'], "pc_id", "*");
        $productRow['category_first_name'] = $categoryFirst['pc_name'];
        if (!$productRow['pu_code']) {
            $productRow['pu_code'] = '007';
        }
        $productUom = Service_ProductUom::getByField($productRow['pu_code'], "pu_code", "*");
        $productRow['pu_name'] = $productUom['pu_name'];

        if ($productRow['product_type'] == '1') {
            $productRow['product_declared_value'] = Service_Product::getCombineDeclaredValue($productId);

        }

        // 根据供应商ID获取供应商数据
        if ($productRow['distributor_id']) {
            $productRow['distributor'] = Service_Distributor::getByPrimaryKey($productRow['distributor_id']);
        }

        $this->view->productRow = $productRow;
        $productLog = Service_ProductLog::getByCondition(array('product_id' => $productId), "*");

        foreach ($productLog as $k => $v) {
            if (-1 === (int)$v['user_id']) { // -1是客户操作
                $productLog[$k]['user_code'] = $productRow['customer_code'];

                if ((int)$v['account_id']) {
                    $user = Service_Account::getByCondition(array('account_id' => $v['account_id']));
                    $productLog[$k]['user_code'] = $user ? $user['account_name'] : $productRow['customer_code'];
                }
            } else {
                $productLog[$k]['user_code'] = '系统';
            }
        }

        $this->view->logStatus = array(
            '0' => '删除',
            '1' => '确认'
        );
        $this->view->productLog = $productLog;

        //0:在途;1:收货中;2:处理完成
        $this->view->asnStatusArr = array(
            '0' => '在途',
            '1' => '收货中',
            '2' => '处理完成'
        );
        $this->view->productAsn = Service_ReceivingDetail::getByCondition(array('product_id' => $productId), "*");

        $this->view->orderProduct = Service_OrderProduct::getByCondition(array('product_id' => $productId), "*");

        $productInventory = Service_ProductInventory::getByCondition(array('product_id' => $productId), "*");
        foreach ($productInventory as $k => $v) {
            $warehouse = Service_Warehouse::getByField($v['warehouse_id'], "warehouse_id", "*");
            $productInventory[$k]['warehouse_code'] = $warehouse['warehouse_code'];
        }
        $productImage = Service_ProductAttached::getByCondition(array('product_id' => $productId), "*");
        $this->view->productImage = $productImage;
        $this->view->productInventory = $productInventory;
        /*海关要素的处理*/
        $hsinfo_array = array();
        $hsunit_array = array();
        if ($productRow['product_type'] == '0' && $productRow['hs_code'] != '') {
            $condition = array(
                'product_id' => $productRow['product_id'],
            );

            $hsinfo_array = Service_HsElementMap::getJoinHSElementByCondition($condition, '*', '', '', 'hs_element.he_sort');
            $hsunit_array = Service_HsUomMap::getJoinUomByCondition($condition);
            $hsunit_array = $hsunit_array[0];

            if ($hsunit_array) {
                if ($hsunit_array['pu_code_law']) {
                    $pu_array = Service_ProductUom::getByField($hsunit_array['pu_code_law'], $field = 'pu_code');
                    if ($pu_array) {
                        $hsunit_array['pu_code_law'] = $pu_array['pu_name'];
                    }
                }

                if ($hsunit_array['pu_code_second']) {
                    $pu_array = Service_ProductUom::getByField($hsunit_array['pu_code_second'], $field = 'pu_code');
                    if ($pu_array) {
                        $hsunit_array['pu_code_second'] = $pu_array['pu_name'];
                    }
                }

            }
            if (empty($hsinfo_array)) {//如果没有要素内容也要显示单位情况
                $hsinfo_array[] = $hsunit_array;
            }
            //print_r($hsunit_array);
            //print_r($hsinfo_array);
            /*
            if($hsinfo_array){
                foreach($hsinfo_array as &$row){
                        $row['product_bar_code'] = $productRow['product_barcode'];
                        $row['hs_code'] = $productRow['hs_code'];



                }//foreach(){

            }//if($hsinfo_array){
            */


        }//if($productRow['product_type']==
        $this->view->hsinfo_array = $hsinfo_array;
        $this->view->hsunit_array = $hsunit_array;

        echo Ec::renderTpl($this->tplDirectory . "detail.tpl", 'noleftlayout');
        //echo $this->view->render($this->tplDirectory . "detail.tpl");
    }

    /*海关编码辅助输入*/
    public function hscodeAuxiliaryInputAction()
    {

        $page = $this->getRequest()->getParam('page', 1);
        $pageSize = $this->getRequest()->getParam('pageSize', 20);
        $condition = array(
            'p_name' => $this->getRequest()->getParam('p_name'),
            'hs_code' => $this->getRequest()->getParam('s_hs_code'),
            'hs_code_status' => 1

        );


        $from = $this->_request->getParam('from', '');
        $globals_hs_code = $this->_request->getParam("global_hs_code", "");
        //判断参数的有效性
        $inject = true;
        switch ($from) {
            case 'product':
                $inject = false;
                break;
            case 'asn':
                $inject = false;
            case 'order':
                $inject = false;
        }

        $this->view->from = $from;
        $this->view->params = $condition;
        $this->view->pageSize = $pageSize;
        $this->view->page = $page;
        $this->view->globals_hs_code = $globals_hs_code;

        $this->view->count = Service_Hscodes::getByCondition($condition, 'count(*)');

        $result = Service_Hscodes::getByCondition($condition, '*', 'hs_code DESC', $pageSize, $page);


        $this->view->result = $result;


        echo $this->view->render($this->tplDirectory . "hscodeAuxiliaryInput.tpl");
    }

    /*转为备案中*/
    function changeIntoBeianzhongAction()
    {

        $productId = $this->_request->getParam('productId', '');

        if ($productId) {
            $productInfo = Service_Product::getByField($productId, 'product_id');

            if ($productInfo) {
                if ($productInfo['have_asn'] == '1') {
                    exit('有ASN单不能更改');
                }
                if ($productInfo['product_type'] == 1) {
                    //exit('cccccccc');
                    exit('组合产品不能改变状态.');
                    exit;
                }

                if ($productInfo['product_status'] == '0') {
                    $row = array('product_status' => 2);
                    Service_Product::update($row, $productId, "product_id");
                }


            }
        }

        $this->_redirect("/merchant/product/index/?status=2");
        exit;


    }


    /*
     * @author colin-yang
     * @todo 选择产品模板
     */
    public function productSelectTempleteAction()
    {
        $fullPath = APPLICATION_PATH . "/../data/file" . '/productSelect.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;
    }

    /**
     * @author colin-fan  在新增备货订单的时候
     * @todo 选择产品模板
     */
    public function selectProductTempleteAction()
    {
        $fullPath = APPLICATION_PATH . "/../data/file" . '/productDemo.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;
    }

    /*通过导入EXCEL文件 colin-yang*/
    public function batchInputAction()
    {
        $result = array("ask" => 0, "message" => "不明错误，导致失败", 'error' => array(), 'data' => array());
        $path = APPLICATION_PATH . '/../data';
        //$field = $this->getRequest()->getParam('XMLForInput', 'XMLForInput');
        $field = 'XMLForInput';
        $config = array();
        $config['upload_path'] = $path;
        $config['allowed_types'] = 'xls|xlsx';
        $config['max_size'] = '10000000000';
        $config['encrypt_name'] = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if (!$upload->do_upload($_FILES, $field)) {
            $result['error'] = "文件上传失败";
            echo json_encode($result);
            exit;
        }

        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if (empty($resultArray) || empty($full_path)) {
            $result = array("ask" => 0, "message" => "上传文件失败", 'error' => array());
            echo json_encode($result);
            exit;
        }

        $resultArray = Common_Upload::readEXCEL($full_path);

        if (empty($resultArray) || !is_array($resultArray)) {
            $result = array("ask" => 0, "message" => "由于文件内容不符合预期导致数据为空.", 'error' => array());
            echo json_encode($result);
            exit;
        }
        @unlink($full_path);
        //读取product表根据XML中的SKU
        $found_product_results = array();


        foreach ($resultArray as $key => $row) {
            if ($key < 1) {
                continue;
            }
            //标题行不读
            $productsku = $row[0];
            $product_number = $row[1];

            if (empty($productsku)) {
                continue;
            }

            $condition = array('product_sku' => $productsku, 'customer_id' => $this->_customerAuth['id']);
            $productInfo = Service_Product::getByCondition($condition);
            if (empty($productInfo)) {
                $product = array(
                    'product_id' => '0',
                    'product_sku' => $productsku,
                    'product_title' => '',
                    'pc_id' => '',
                    'product_weight' => '',
                    'product_number' => '',
                    'is_valid' => '0',
                    'error' => "SKU不存在<br/>",
                    'error_number' => 1
                );
                $found_product_results[] = $product;
                continue;
            }//if(empty($productInfo))


            $productInfo = $productInfo[0];
            $product = array(
                'product_id' => $productInfo['product_id'],
                'product_sku' => $productInfo['product_sku'],
                'product_title' => $productInfo['product_title'],
                'product_title_en' => $productInfo['product_title_en'],
                'pc_id' => $productInfo['pc_id'],
                'product_weight' => $productInfo['product_weight'],
                'product_declared_value' => $productInfo['product_declared_value'],
                'product_number' => $product_number,
                'is_valid' => '1',
                'error' => '',
                'error_number' => 0
            );
            //$found_product_results[] = $product;

            //判断产品类型是否正确
            if ($productInfo['product_type'] != '0') {
                $product['is_valid'] = '0'; //这个产品不能使用
                $product['error'] .= '不为普通产品<br/>';
                $product['error_number'] += 1;
            }

            //判断产品状态是否正确
            if ($productInfo['product_status'] != '1') {
                $product['is_valid'] = '0';
                $product['error'] .= '产品未备案<br/>';
                $product['error_number'] += 1;
            }
            //$product_number="a";
            if (!($product_number && is_numeric($product_number) && $product_number > 0 && preg_match('/^[0-9]+$/', $product_number))) {
                $product['is_valid'] = '0';
                $product['error'] .= '产品数量必填，并且必须为正整数<br/>';
                $product['error_number'] += 1;
            }

            $found_product_results[] = $product;


        }//foreach($resultArray

        if (empty($found_product_results) || !is_array($found_product_results)) {
            $result = array("ask" => 0, "message" => "在产品资料库中抄不到对应的数据.", 'error' => array());
            echo json_encode($result);
            exit;
        }
        //从所有合格不合格的数据中分离出合格与不合格

        $correct_product_results = array();
        $incorrect_product_results = array();

        foreach ($found_product_results as $k => $row) {

            if ($row['error_number'] > 0) {
                $incorrect_product_results[] = $row;
            } else {
                $correct_product_results[] = $row;
            }

        }
        //echo "sdf";exit;
        $result = array("ask" => '1', 'data' => $correct_product_results, 'errordata' => $incorrect_product_results);
        echo json_encode($result);
        exit;


    }    //function end


    public function exportAction()
    {
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体')->setSize(10);
        $objActSheet = $table->setActiveSheetIndex(0);
        $objActSheet->setTitle(Ec_Lang::getInstance()->getTranslate('product'));
//            $objActSheet->getStyle("{$key}1")->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
//            $objActSheet->getStyle("{$key}1")->getBorders()->getLeft()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_YELLOW);         
        $tableStyle = array(
            'allborders' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
                'color' => array(
                    'rgb' => '000000'
                )
            )
        );

        $objTitleArr = array('a' => '客户代码', 'b' => '产品SKU', 'c' => '条码类型', 'd' => '产品代码', 'e' => '产品名称', 'f' => '英文名', 'g' => '状态', 'h' => '单位', 'i' => '申报币种', 'j' => '申报价值', 'k' => '产品重量（KG）', 'l' => '海关编码', 'm' => '海关品名', 'n' => '招海料号', 'o' => '产品品类', 'p' => '供应商代码', 'q' => '长（CM）', 'r' => '宽（CM）', 's' => '高（CM）', 't' => '产品接收类型', 'u' => '质检类型', 'v' => '产品分类', 'w' => '产品添加时间', 'x' => '是否属于零件类', 'y' => '有无发票', 'z' => '产品型号', 'aa' => '法定单位', 'ab' => '法定数量', 'ac' => '第二法定单位', 'ad' => '第二法定数量', 'ae' => '要素代码', 'af' => '要素名称', 'ag' => '申报要素内容', 'ah' => '法定单位', 'ai' => '法定数量', 'aj' => '第二法定单位', 'ak' => '第二法定数量', 'al' => '要素代码', 'am' => '要素名称', 'an' => '申报要素内容', 'ao' => '法定单位', 'ap' => '法定数量', 'aq' => '第二法定单位', 'ar' => '第二法定数量', 'as' => '要素代码', 'at' => '要素名称', 'au' => '申报要素内容', 'av' => '法定单位', 'aw' => '法定数量', 'ax' => '第二法定单位', 'ay' => '第二法定数量', 'az' => '要素代码', 'ba' => '要素名称', 'bb' => '申报要素内容', 'bc' => '法定单位', 'bd' => '法定数量', 'be' => '第二法定单位', 'bf' => '第二法定数量', 'bg' => '要素代码', 'bh' => '要素名称', 'bi' => '申报要素内容');
        foreach ($objTitleArr as $key => $val) {
            $objActSheet->getColumnDimension($key)->setWidth(10);
            $objActSheet->setCellValue("{$key}1", $val);
            $objActSheet->getStyle("{$key}1")->getBorders()->applyFromArray($tableStyle);
        }

        $condition = array(
            'customer_id' => $this->_customerAuth['id'],
            'product_type' => $this->getRequest()->getParam('product_type'),
            'comefrom' => 1,
            'product_sku_keyword' => $this->getRequest()->getParam('sku'),
            'product_title' => $this->getRequest()->getParam('title'),
            'pc_id' => $this->getRequest()->getParam('type'),
            'product_add_time' => $this->getRequest()->getParam('start_time'),
            'product_end_time' => $this->getRequest()->getParam('end_time'),
            'product_status' => $this->getRequest()->getParam('status')
        );
        $pageSize = 20;
        $index = 2;
        $count = Service_Product::getByCondition($condition, 'count(*)');
        if ($count) {
            $category = Common_DataCache::getProductCategory();
            $status = array("备案中", "已备案", "草稿", "确认");
            $pages = ceil($count / $pageSize);
            for ($page = 1; $page <= $pages; $page++) {
                $productArr = Service_Product::getByCondition($condition, '*', 'product_id DESC', $pageSize, $page);
                $objActSheet->duplicateStyle($objActSheet->getStyle('A1'), "A{$index}:BI{$index}");
                foreach ($productArr as $key => $value) {
                    $productInfo = Service_Product::getProductAllInfo($value['product_id'], $value['customer_id']);
                    $objActSheet->setCellValueExplicit("A" . $index, $productInfo['customer_code'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("B" . $index, $productInfo['product_sku'], PHPExcel_Cell_DataType::TYPE_STRING);
                    if ($productInfo['product_barcode_type'] == 2) {
                        $objActSheet->setCellValueExplicit("C" . $index, '序列条码', PHPExcel_Cell_DataType::TYPE_STRING);
                    } else if ($productInfo['product_barcode_type'] == 0) {
                        $objActSheet->setCellValueExplicit("C" . $index, '默认条码', PHPExcel_Cell_DataType::TYPE_STRING);
                    } else if ($productInfo['product_barcode_type'] == 1) {
                        $objActSheet->setCellValueExplicit("C" . $index, '自定义条码', PHPExcel_Cell_DataType::TYPE_STRING);
                    }
                    $objActSheet->setCellValueExplicit("D" . $index, $productInfo['product_barcode'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("E" . $index, $productInfo['product_title'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("F" . $index, $productInfo['product_title_en'], PHPExcel_Cell_DataType::TYPE_STRING);
                    if ($productInfo['product_status'] == 1) {
                        $objActSheet->setCellValueExplicit("G" . $index, '已备案', PHPExcel_Cell_DataType::TYPE_STRING);
                    } else if ($productInfo['product_status'] == 2) {
                        $objActSheet->setCellValueExplicit("G" . $index, '草稿', PHPExcel_Cell_DataType::TYPE_STRING);
                    } else {
                        $objActSheet->setCellValueExplicit("G" . $index, '备案中', PHPExcel_Cell_DataType::TYPE_STRING);
                    }
                    //单位
                    $productUom = Service_ProductUom::getByField($productInfo['pu_code'], "pu_code", "*");
                    $objActSheet->setCellValueExplicit("H" . $index, $productUom['pu_name'], PHPExcel_Cell_DataType::TYPE_STRING);

                    $objActSheet->setCellValueExplicit("I" . $index, $productInfo['currency_code'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("J" . $index, $productInfo['product_declared_value'], PHPExcel_Cell_DataType::TYPE_NUMERIC);
                    $objActSheet->setCellValueExplicit("K" . $index, $productInfo['product_weight'], PHPExcel_Cell_DataType::TYPE_NUMERIC);
                    $objActSheet->setCellValueExplicit("L" . $index, $productInfo['hs_code'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("M" . $index, $productInfo['hs_goods_name'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("N" . $index, $productInfo['goods_id'], PHPExcel_Cell_DataType::TYPE_STRING);
                    //产品品类
                    $objActSheet->setCellValueExplicit("O" . $index, ($productInfo['category_name'] == '--') ? '' : $productInfo['category_name'], PHPExcel_Cell_DataType::TYPE_STRING);
                    //产品供应商代码
                    $distributor = Service_Distributor::getByPrimaryKey($productInfo['distributor_id']);
                    $objActSheet->setCellValueExplicit("P" . $index, $distributor['distributor_code'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("Q" . $index, $productInfo['product_length'], PHPExcel_Cell_DataType::TYPE_NUMERIC);
                    $objActSheet->setCellValueExplicit("R" . $index, $productInfo['product_width'], PHPExcel_Cell_DataType::TYPE_NUMERIC);
                    $objActSheet->setCellValueExplicit("S" . $index, $productInfo['product_height'], PHPExcel_Cell_DataType::TYPE_NUMERIC);
                    //产品接收类型
                    if ($productInfo['product_receive_status'] == 0) {
                        $objActSheet->setCellValueExplicit("T" . $index, '新产品', PHPExcel_Cell_DataType::TYPE_STRING);
                    } else {
                        $objActSheet->setCellValueExplicit("T" . $index, '已收过货产品', PHPExcel_Cell_DataType::TYPE_STRING);
                    }
                    //质检类型
                    if ($productInfo['product_is_qc'] == 0) {
                        $objActSheet->setCellValueExplicit("U" . $index, '不质检', PHPExcel_Cell_DataType::TYPE_STRING);
                    } else {
                        $objActSheet->setCellValueExplicit("U" . $index, '质检', PHPExcel_Cell_DataType::TYPE_STRING);
                    }
                    //产品类型
                    $objActSheet->setCellValueExplicit("V" . $index, $productInfo['product_type_title'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("W" . $index, $productInfo['product_add_time'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("X" . $index, ($productInfo['is_accessories'] == 0) ? '否' : '是', PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("Y" . $index, ($productInfo['has_invoice'] == 0) ? '无' : '有', PHPExcel_Cell_DataType::TYPE_STRING);
                    $objActSheet->setCellValueExplicit("Z" . $index, $productInfo['model_serial'], PHPExcel_Cell_DataType::TYPE_STRING);

                    $Pi = "AA";
                    if (isset($productInfo['hs_element_maps']) && $productInfo['hs_element_maps']) {
                        foreach ($productInfo['hs_element_maps'] as $key => $value) {
                            $objActSheet->setCellValueExplicit($Pi++ . $index, isset($productInfo['hs_uom_map']['pu_name_law']) ? $productInfo['hs_uom_map']['pu_name_law'] : '', PHPExcel_Cell_DataType::TYPE_STRING);
                            $objActSheet->setCellValueExplicit($Pi++ . $index, isset($productInfo['hs_uom_map']['hum_quantity_law']) ? $productInfo['hs_uom_map']['hum_quantity_law'] : '', PHPExcel_Cell_DataType::TYPE_NUMERIC);
                            $objActSheet->setCellValueExplicit($Pi++ . $index, isset($productInfo['hs_uom_map']['pu_name_second']) ? $productInfo['hs_uom_map']['pu_name_second'] : '', PHPExcel_Cell_DataType::TYPE_STRING);
                            $objActSheet->setCellValueExplicit($Pi++ . $index, isset($productInfo['hs_uom_map']['hum_quantity_second']) ? $productInfo['hs_uom_map']['hum_quantity_second'] : '', PHPExcel_Cell_DataType::TYPE_NUMERIC);
                            $objActSheet->setCellValueExplicit($Pi++ . $index, $value['he_name'], PHPExcel_Cell_DataType::TYPE_STRING);#要素代码
                            $objActSheet->setCellValueExplicit($Pi++ . $index, $value['he_name'], PHPExcel_Cell_DataType::TYPE_STRING);#要素名称
                            $objActSheet->setCellValueExplicit($Pi++ . $index, $value['hem_detail'], PHPExcel_Cell_DataType::TYPE_STRING);
                        }
                    }
                    $index++;
                }

            }
        }

        $objWriter = PHPExcel_IOFactory::createWriter($table, 'Excel5');
        header("Pragma: public");
        header("Expires: 0");
        header("Accept-Ranges: bytes");
        header('cache-control:must-revalidate');
        header("Content-Disposition: attachment; filename=product" . date('Y-m-d') . ".xls");
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');
    }

    public function printAction()
    {
        $sku = $this->_request->getParam('sku', "");
        //$printNumber = $this->_request->getParam('printNumber',"");
        //$printCode = array();
        $productList = array();
        foreach ($sku as $key => $value) {
            if ($value == "") continue;
            $p = Service_Product::getByField($key, "product_id");
            if (!empty($p) && $p['product_type'] != "1") {
                if ($p['pc_id']) {
                    $category = Service_ProductCategory::getByField($p['pc_id'], 'pc_id', "*");
                    $p['pc_name_en'] = $category['pc_name_en'];
                } else {
                    $p['pc_name_en'] = '';
                }
                $item = array(
                    'product_barcode' => $p['product_barcode'],
                    'customer_code' => $p['customer_code'],
                    'pc_name_en' => $p['pc_name_en'],
                    'number' => $value
                );
                $productList[] = $item;
            }
        }
        $this->view->productList = $productList;
        echo Ec::renderTpl($this->tplDirectory . "product-print.tpl", 'noleftlayout');
    }

}