<?php

class Merchant_ProductBatchUploadController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "merchant/views/product/";
        $this->customerAuth = new Zend_Session_Namespace("customerAuth");
    }

    /**
     * @author colin-yang
     * @todo 用于下载批量产品模板
     */
    public function productBatchImportTempleteAction()
    {
        $fullPath = APPLICATION_PATH . "/../data/file" . '/productBatchImport.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 yang
     * @todo 选择产品批量导入
     */
    public function batchProductInputAction()
    {
        echo Ec::renderTpl($this->tplDirectory . "batch-product-import.tpl", 'noleftlayout');
    }


    /**
     * @author william-fan
     * @todo 产品批量导入检查
     */
    public function batchProductImportPreviewAction()
    {
        //set_time_limit(300);
        set_time_limit(300);
        ini_set('memory_limit', '512M');
        $productUpload = new Zend_Session_Namespace('productUpload');
        $field = 'XMLForInput';
        $xlsData = self::getXLSData($_FILES, $field);
        if (isset($xlsData['ask']) && $xlsData['ask'] == '0') {
            //echo 'sss';
            $this->view->uploadinfo = $xlsData;
            echo Ec::renderTpl($this->tplDirectory . "batch-product-import.tpl", 'noleftlayout');
            exit;
        } else {
            $orderRows = $this->_getDataArr($xlsData);
            $productUpload->uploadData = $orderRows;
            // print_r($orderRows);
            //  echo '<pre>';
            // print_r($orderRows);
            // echo '</pre>';
            $this->view->uploadData = $orderRows;
            echo Ec::renderTpl($this->tplDirectory . "batch-product-import-preview.tpl", 'noleftlayout');
        }

    }

    /**
     * @author colin-yang
     * @todo 用于实际地写入数据
     */
    public function doBatchInsertAction()
    {
        $productUpload = new Zend_Session_Namespace('productUpload');
        $sessionData = $productUpload->uploadData;
        // print_r($sessionData );
        // exit;
        $selectedData = array();
        if (empty($sessionData)) {
            $this->_redirect('/merchant/product-batch-upload/batch-product-input');
        }
        $ids = $this->_request->getParam('select');
        if (empty($ids)) {
            $this->_redirect('/merchant/product-batch-upload/batch-product-input');
        }
        foreach ($ids as $id) {
            if ($sessionData[$id])
                $selectedData[] = $sessionData[$id];
        }

        if (empty($selectedData)) {
            $this->_redirect('/merchant/product-batch-upload/batch-product-input');
        }

        $DB = Common_Common::getAdapter();
        $ids = $this->_request->getParam('select');
        $system_error_number = 1;
        foreach ($selectedData as $p => &$prow) {
            $prow['error'] = array();
            $prow['error_number'] = 0;
            $insertRow = $prow;
            unset($insertRow['error']);
            unset($insertRow['error_number']);
            unset($insertRow['product_url']);
            unset($insertRow['is_valid']);
            unset($insertRow['pc_name']);
            unset($insertRow['pu_name']);
            unset($insertRow['has_invoice_desc']);
            unset($insertRow['country_title']);
            unset($insertRow['product_url1']);
            unset($insertRow['product_url2']);
            unset($insertRow['product_url3']);
            unset($insertRow['product_url4']);
            unset($insertRow['product_url5']);
            unset($insertRow['country_code_of_origin']);
            //var_dump($insertRow);exit;
            $DB->beginTransaction();
            try {
                $productID = Service_Product::add($insertRow);

                // 批量上传，需要些日志
                Service_ProductLog::add(array(
                    'product_id' => $productID,
                    'pl_type' => 0,
                    'customer_id' => $insertRow['customer_id'],
                    'pl_add_time' => date('Y-m-d H:i:s'),
                    'pl_statu_pre' => 2,
                    'pl_statu_now' => 2,
                    'pl_note' => 'ProductSku:[' . $insertRow['product_sku'] . '] Create',
                    'pl_ip' => Common_Common::getIP(),
                    'user_id' => -1,
                    'account_id' => Service_Login::getUserId()
                ));

                $DB->commit();
            } catch (Zend_Exception  $exe) {
                $prow['error'][] = "新增失败,系统错误:" . $exe->getMessage();
                $DB->rollBack();
                continue;
            }
            $prow['error'][] = "新增成功.";
            if ($productID) {
                if ($prow['product_url1']) {
                    $attachmentRow = array('product_id' => $productID, 'pa_file_type' => 'link', 'pa_path' => $prow['product_url1']);
                    Service_ProductAttached::add($attachmentRow);
                }
                if ($prow['product_url2']) {
                    $attachmentRow = array('product_id' => $productID, 'pa_file_type' => 'link', 'pa_path' => $prow['product_url2']);
                    Service_ProductAttached::add($attachmentRow);
                }
                if ($prow['product_url3']) {
                    $attachmentRow = array('product_id' => $productID, 'pa_file_type' => 'link', 'pa_path' => $prow['product_url3']);
                    Service_ProductAttached::add($attachmentRow);
                }
                if ($prow['product_url4']) {
                    $attachmentRow = array('product_id' => $productID, 'pa_file_type' => 'link', 'pa_path' => $prow['product_url4']);
                    Service_ProductAttached::add($attachmentRow);
                }
                if ($prow['product_url5']) {
                    $attachmentRow = array('product_id' => $productID, 'pa_file_type' => 'link', 'pa_path' => $prow['product_url5']);
                    Service_ProductAttached::add($attachmentRow);
                }


            }


        }//foreach($found_product_results as $p =>$prow){


        /* if($category){
            foreach ($found_product_results as $keyp=>$valuep){

            }

        } */
        //echo "sdf";exit;

        $result = array("ask" => '1', 'data' => $selectedData);
        $this->view->result = $result;
        if ($productUpload) {
            unset($productUpload->uploadData);
        }

        echo Ec::renderTpl($this->tplDirectory . "batch-product-import.tpl", 'noleftlayout');

    }


    /**
     * @author colin-yang
     * @todo 读取EXCEL文件数据
     */
    public static function getXLSData($uploadFile, $field)
    {
        ini_set('memory_limit', '1024M');

        $customerAuth = new Zend_Session_Namespace("customerAuth");

        $customer = $customerAuth->data;
        $customerId = $customer['id'];
        //print_r($customer);
        //exit('sss');
        $path = APPLICATION_PATH . '/../data/productbatchupload/';
        $path .= $customerId;
        if (!file_exists($path)) {
            if (!mkdir($path, 0700, true)) {
                $result = array("ask" => 0, "message" => "上传文件失败失败", 'error' => array('上传目录不存在创建文件目录失败'));
                return $result;
            }
        }
        $config = array();
        $config['upload_path'] = $path;
        $config['allowed_types'] = 'xls|xlsx';
        $config['max_size'] = '5250000';
        $config['encrypt_name'] = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if (!$upload->do_upload($_FILES, $field)) {
            $result['ask'] = '0';
            $result['message'] = '上传文件失败';
            $result['error'] = $upload->display_errors();
            return $result;
            exit;
        }

        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if (empty($resultArray) || empty($full_path)) {
            $result = array("ask" => 0, "message" => "上传文件失败失败", 'error' => array('数据不存在'));
            return $result;
            exit;
        }

        $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);
        return $resultArray;
    }


    /**
     * @author colin yang
     * @todo 检查输入数据格式
     */
    private function _getDataArr($productRow)
    {
        $found_product_results = array();
        $sku_array = array();
        $customer_defined_barcode_array = array();
        foreach ($productRow as $key => $row) {
            if ($key < 1) {
                continue;
            }

            $errorArray = array();

            $productsku = trim($row[0]);//产品SKU
            $product_barcode_type_name = $row[4];//条码类型
            $bar_code = trim($row[5]);

            if (empty($productsku)) {
                continue;
            }

            //$product_length = $row[7];
            //$product_width = $row[8];
            //$product_height = $row[9];

            $currency_code = $row[6];
            $product_declared_value = $row[7];
            $product_weight = sprintf("%.4f", $row[8]);//毛重
            //$product_weight = sprintf("%.4f", $row[7]);//毛重
            $has_invoice_desc = trim($row[9]);    //有无发票
            $hs_goods_name = $row[10];
            $hs_code = $row[11];
            $distributor_id = 0; // 供应商ID
            $distributor_valid = TRUE; // 供应商代码为空或供应商代码有效时为TRUE，否则为FALSE
            $distributor_code = trim($row[12]); // 供应商代码

            $model_serial = $row[13];
            $with_battery = $row[14];
            $battery_type = $row[15];
            $battery_detail = $row[16];
            $product_url1 = strip_tags($row[17]);
            $product_url2 = strip_tags($row[18]);
            $product_url3 = strip_tags($row[19]);
            $product_url4 = strip_tags($row[20]);
            $product_url5 = strip_tags($row[21]);
            //标题行不读
            //print_r($this->_customerAuth);exit;

            $product_barcode = $this->_customerAuth['code'] . '-' . $productsku;
            $product_title = $row[1];//产品名称
            $product_title_en = trim($row[2]);
            //$pc_name = trim($row[3]);//产品类别
            $customer_id = $this->_customerAuth['id'];
            $customer_code = $this->_customerAuth['code'];


            /*
            if(empty($pu_name)){ $errorArray[] =  '产品单位不能为空.';}	else{
                $pu_array = Service_ProductUom::getByField($pu_name,"pu_name","*");
                if(empty($pu_array)){ $errorArray[] =  '非法的产品单位.';}	else{
                    $pu_code =  $pu_array['pu_id'];
                }
            }
            */
            /*$pu_code = '007';
            $pu_name = '个';*/

            $pu_name = $row[3];
            if ($pu_name == "") {
                $errorArray[] = '产品单位必填';
            } else {
                $uom = Service_ProductUom::getByField($pu_name, "pu_name");
                $pu_code = $uom['pu_code'];
                $productUomArr = Service_Product::getProductUom();
                if (!in_array($pu_code, $productUomArr)) {
                    $errorArray[] = '产品单位只能是[台,座,辆,艘,架,井,个,只,头,张,,件,支,枝,根,条,把,块,卷,副,片,组,份,幅,双,对,棵,株,套,盘,筒,盆,箱,批,罐,桶,扎,包,箩,打,筐,罗,匹,册,本,发,枚,捆,袋,粒,盒,合,瓶,部]';
                }
            }
            if (in_array($productsku, $sku_array)) {
                $errorArray[] = '产品SKU重复.';
            }
            $sku_array["{$productsku}"] = $productsku;

            if (!in_array($product_barcode_type_name, array('自定义类型', '默认类型', '序列号类型'))) {
                $errorArray[] = '条码类型必须指定';
            }
            switch ($product_barcode_type_name) {
                case '默认类型':
                    $product_barcode_type = 0;
                    break;
                case '自定义类型':
                    $product_barcode_type = 1;
                    break;
                case '序列号类型':
                    $product_barcode_type = 2;
                    break;
                default:
                    $product_barcode_type = 0;

            }

            $productInfo = Service_Product::getByCondition(array('product_sku' => $productsku, 'customer_id' => $customer_id));
            if ($productInfo) {
                $errorArray[] = '产品SKU已存在.';
            } else {
                if (1 !== $product_barcode_type && !preg_match('/^[0-9a-zA-Z\-]{1,12}$/', $productsku)) {
                    // 自定义类型条码不受此限制
                    $errorArray[] = '产品SKU必填，非自定义类型条码SKU必须是字母、数字和横杠,最大长度为12位.';
                }
            }
            if (empty($product_title)) {
                $errorArray[] = '产品名称不能为空';
            }
            if (empty($product_title_en)) {
                $errorArray[] = '产品英文名称不能为空';
            } else {
                if (!preg_match("/^[0-9a-zA-Z\- ]+$/", $product_title_en)) {
                    $errorArray[] = "产品英文名称只能包含英文字母、数字、空格和 - ";
                }
            }
            /*
            if(empty($pc_name)){ $errorArray[] =  '产品品类不能为空.';}	else{
                $category = Service_ProductCategory::getByField($pc_name,"pc_name","*");
                if(empty($category)){ $errorArray[] =  '非法的产品品类.';}	else{
                    $pc_id=  $category['pc_id'];
                }
            }

            if(!(is_numeric($product_length) && $product_length>0)){ $errorArray[] =  '产品长度必填，且必须为大于0的数';}
            if(!(is_numeric($product_width) && $product_width>0)){ $errorArray[] =  '产品宽度必填，且必须为大于0的数';}
            if(!(is_numeric($product_height) && $product_height>0)){ $errorArray[] =  '产品高度必填，且必须为大于0的数';}
            */


            if ($product_barcode_type == 1) {
                if (empty($bar_code)) {
                    $errorArray[] = '自定义条码类型必须提供条码';
                } else {
                    $product_barcode = $bar_code;

                    if (!preg_match('/^[0-9a-zA-Z\-]{1,18}$/', $bar_code)) {// 自定义类型条码不受此限制
                        //$errorArray[] = "自定义条码仅限能输入字母、数字和横杠,最大长度为18位.";
                    } else {
                        $productInfo = Service_Product::getByCondition(array('product_barcode' => $product_barcode));
                        if ($productInfo) {
                            $errorArray[] = '产品条码已存在.';
                        }

                        if (in_array($bar_code, $customer_defined_barcode_array)) {
                            $errorArray[] = '产品条码重复.';
                        }
                        $customer_defined_barcode_array[] = $bar_code;
                    }
                }


            }
            //有无发票
            $kvHasInvoice = array('有' => 1, '无' => 2);
            if (empty($has_invoice_desc)) {
                $errorArray[] = '有无发票必须填写.';
            } else if (!array_key_exists($has_invoice_desc, $kvHasInvoice)) {
                //} else if(!in_array($has_invoice_desc, array('有','无'))) {
                $errorArray[] = '有无发票必须填写有或者无.';
            } else {
                $has_invoice = $kvHasInvoice[$has_invoice_desc];
            }
            if ($with_battery == "是" && $battery_type == "") {
                $errorArray[] = '电池类型必须填.';
            }
            if ($battery_type == "其他" && $battery_detail == "") {
                $errorArray[] = "当电池类型为其他的时,电池类型补充";
            }
            $batteryType = "";
            if ($with_battery == "是") {
                if (!in_array($battery_type, array("配置电池", "内置电池", "纽扣电池", "锂金属电池", "离子电池", "其他"))) {
                    $errorArray[] = "电池类型这能填写这六种:配置电池,内置电池,纽扣电池,锂金属电池,离子电池,其他";
                }
                switch ($battery_type) {
                    case "配置电池":
                        $batteryType = 1;
                        break;
                    case "内置电池":
                        $batteryType = 2;
                        break;
                    case "纽扣电池":
                        $batteryType = 3;
                        break;
                    case "锂金属电池":
                        $batteryType = 4;
                        break;
                    case "离子电池":
                        $batteryType = 5;
                        break;
                    case "其他":
                        $batteryType = 6;
                        break;
                }
            }

            if (empty($currency_code)) {
                $errorArray[] = '申报币种必须填写.';
            } else {
                if ($currency_code != 'USD') {
                    $errorArray[] = '申报币种必须为美元(USD).';
                }

            }
            if (!(is_numeric($product_declared_value) && $product_declared_value > 0)) {
                $errorArray[] = '产品申报价值必须为正的金额';
            }
            if (!(is_numeric($product_weight) && $product_weight > 0)) {
                $errorArray[] = '产品重量必填，且必须为大于0的数';
            }


            if (empty($hs_goods_name)) {
                $errorArray[] = '海关品名不能为空.';
            } elseif (!Service_GB18030::isValid($row['hs_goods_name'])) {
                $errorArray[] = '海关品名含有非GB18030字符集字符';
            } elseif (preg_match('/^[a-zA-Z\s]+$/', $hs_goods_name)) {
                $errorArray[] = '海关品名不能全是字母';
            } elseif (preg_match('/^(((?=[\x21-\x7e]+)[^A-Za-z0-9])|\s)*$/', $hs_goods_name)) {
                $errorArray[] = '海关品名不能全是字符';
            }

            if (empty($hs_code) || !preg_match('/^[0-9]{10}$/', $hs_code)) {
                $errorArray[] = '海关编码不能为空,且必须是10位的数字.';
            } else {

                //$hs_code_array = Service_Hscodes::getByField($hs_code,'hs_code');
                $hs_condition = array(
                    'hs_code' => $hs_code,
                    'hs_code_status' => 1
                );
                $hs_code_array = Service_Hscodes::getByCondition($hs_condition);
                if (empty($hs_code_array)) {
                    $errorArray[] = '非法的海关编码.';
                }
            }

            // 对供应商代码有效性作判断
            if (!empty($distributor_code)) {
                $distributor = Service_Distributor::getByCode($distributor_code, $this->_customerAuth['code']);

                if ($distributor) {
                    $distributor_id = $distributor['distributor_id'];
                } else {
                    $distributor_valid = FALSE;
                    $errorArray[] = '无效的供应商代码【' . $distributor_code . '】';
                }
            }


            $product = array(
                'product_sku' => $productsku,
                'product_barcode' => $product_barcode,
                'product_title' => $product_title,
                'product_title_en' => $product_title_en,
                //'pc_name'=>$pc_name,
                //'pc_id'=>$pc_id,
                'customer_code' => $customer_code,
                'customer_id' => $customer_id,
                'pu_name' => $pu_name,
                'pu_code' => $pu_code,
                'currency_code' => $currency_code,
                'product_barcode_type' => $product_barcode_type,
                //'product_length'=>$product_length,
                //'product_width'=>$product_width,
                //'product_height'=>$product_height,
                'product_declared_value' => $product_declared_value,
                'product_weight' => $product_weight,
                'model_serial' => $model_serial,
                'hs_code' => $hs_code,
                'product_url' => $product_url1,
                'product_status' => 2,
                'product_type' => 0,
                'has_invoice' => $has_invoice,
                'has_invoice_desc' => $has_invoice_desc,
                'hs_goods_name' => strtoupper($hs_goods_name),
                //'country_title'=>$country_title,
                'distributor_id' => $distributor_id, // 供应商ID
                'with_battery' => $with_battery == "是" ? "1" : "0",
                'battery_type' => $batteryType,
                'battery_detail' => $battery_detail?$battery_detail:"",
                'product_url1' => $product_url1,
                'product_url2' => $product_url2,
                'product_url3' => $product_url3,
                'product_url4' => $product_url4,
                'product_url5' => $product_url5,
                'is_valid' => 1,
                'error' => $errorArray,
                'error_number' => count($errorArray)

            );
            if (count($errorArray) > 0) {
                $product['is_valid'] = 0;
            }
            $found_product_results[] = $product;


        }//foreach($resultArray

        return $found_product_results;

    }


}