<?php
class Warehouse_InventoryController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "warehouse/views/product/";
        $this->serviceClass = new Service_ProductInventory();
    }

    public function listAction()
    {
        $wh=Common_DataCache::getWarehouseSimple();
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );
  
            
            $params = $this->_request->getParams();
			Common_Common::trim_blank($params);
            $condition = $this->serviceClass->getMatchFields($params);
			if($params['product_sku']||$params['product_title']){
				   $product_array = Service_Product::getByCondition(array('product_sku_keyword'=>$params['product_sku'],'product_title_like'=>$params['product_title']),array('product_id','product_sku'));
					if($product_array){
						$product_id_array = array();
						foreach($product_array as $row){
							$product_id_array[] = (int)$row['product_id'];
						}
						$condition['product_id_array'] = $product_id_array;
						
					}else{					
						$condition['product_id_array'] = array('-1');
					}
			}
			
			
			
            if($params['customerCode']!=""){
                $customer = Service_Customer::getByField(trim($params['customerCode']),"customer_code","*");
                if(!empty($customer)){
                    $condition['customer_id'] = $customer['customer_id'];
                }else{
                    $condition['customer_id'] = '--';
                }
            }
            
            if($params['goods_code'] != ""){
                $condition['goods_id'] = $params['goods_code'];
            }

            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    
                'product_barcode',
                'warehouse_id',
                'pi_onway',
                'pi_pending',
                'pi_sellable',
                'pi_unsellable',
                'pi_reserved',
                'pi_shipped',
                'pi_update_time',
                'pi_id',
                'product_id',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('pi_id desc'));
                foreach($rows as &$r){
                    $product=Service_Product::getByField($r['E2']);
                    $r['E17']=$product['product_title'];
                }
                $return['data'] = $rows;
                $return['warehouse'] = $wh;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . "product_inventory_index.tpl", 'layout');
    }
	/*导出*/
    public function exportAction(){
        set_time_limit(600);
        ini_set('memory_limit', '2G');
        $piIdArr = $this->_request->getParam("piId", "");
        $exportType = $this->_request->getParam("exportType", "");
        $exportObj = new Common_ExportForExcel(array('font_size'=>11));
        $exportObj->setSheet(0);
        $width = array(
            'A' => 10,
            'B' => 20,
            'C' => 20,
            'D' =>15,
            'E' => 20,
            'F' => 15,
            'G' => 15,
            'H' => 15,
            'I' => 15,
            'J' => 15
        );
        for ($index = 'A'; $index <= 'I'; $index++) {
            $exportObj->setWidth($index, $width[$index]);
        }
        $titile[0] = array(
            '客户代码',
            '产品SKU',
            '产品代码',
            '料件号',
            '产品名称',
            '在途',
            '已收货',
            '可用',
            '问题库存',
            '出货占用',
            '已出货',
            '更新时间',
            '申报价值',
            '重量'
           );
        $exportObj->setRowsValue($titile);
        $exportIndex=2;
        $index = 2;
        $exportRow = array();
        if ($exportType == "1") {
            foreach ($piIdArr as $val) {
                if ($val == "")continue;
                $pi = Service_ProductInventory::getByField($val, "pi_id", "*");
                $p = Service_Product::getByField($pi['product_id'], "product_id", "*");
                $exportRow[$index] = array(
                    $p['customer_code'],
                    $p['product_sku'],
                    $p['product_barcode'],
                    $p['goods_id'],
                    $p['product_title'],
                    $pi['pi_onway'],
                    $pi['pi_pending'],
                    $pi['pi_sellable'],
                    $pi['pi_unsellable'],
                    $pi['pi_reserved'],
                    $pi['pi_shipped'],
                    $pi['pi_update_time'],
                    $p['product_declared_value'],
                    $p['product_weight'],
                );
                $exportIndex=$exportObj->setRowsValue($exportRow, $exportIndex, function($index) {
                    $keys = array(1, 2, 3, 4);
                    if (in_array($index, $keys)) {
                        return Common_ExportForExcel::TYPE_STRING2;
                    }
                    return false;
                });
                $exportRow = array();
                $index++;
            }
        } else {
            $params = $this->_request->getParams();
            Common_Common::trim_blank($params);
            $condition = $this->serviceClass->getMatchFields($params);
            if ($params['product_sku'] || $params['product_title']) {
                $product_array = Service_Product::getByCondition(array('product_sku_keyword' => $params['product_sku'], 'product_title_like' => $params['product_title']), array('product_id', 'product_sku'));
                if ($product_array) {
                    $product_id_array = array();
                    foreach ($product_array as $row) {
                        $product_id_array[] = (int) $row['product_id'];
                    }
                    $condition['product_id_array'] = $product_id_array;
                } else {
                    $condition['product_id_array'] = array('-1');
                }
            }
            if ($params['customerCode'] != "") {
                $customer = Service_Customer::getByField(trim($params['customerCode']), "customer_code", "*");
                if (!empty($customer)) {
                    $condition['customer_id'] = $customer['customer_id'];
                } else {
                    $condition['customer_id'] = '--';
                }
            }
            
            if($params['goods_code'] != ""){
                $condition['goods_id'] = $params['goods_code'];
            }

            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            if ($count) {
                $pageSize = 1;
                $rows = $this->serviceClass->getByCondition($condition, 'pi_id', 300, 1, array('pi_id desc'));
                while (!empty($rows)) {
                    foreach ($rows as $key => $value) {
                        $pi = Service_ProductInventory::getByField($value['pi_id'], "pi_id", "*");
                        $p = Service_Product::getByField($pi['product_id'], "product_id", array('customer_code', 'product_sku', 'product_barcode', 'product_title', 'product_declared_value', 'product_weight', 'goods_id'));
                        $exportRow[$index] = array(
                            $p['customer_code'],
                            $p['product_sku'],
                            $p['product_barcode'],
                            $p['goods_id'],
                            $p['product_title'],
                            $pi['pi_onway'],
                            $pi['pi_pending'],
                            $pi['pi_sellable'],
                            $pi['pi_unsellable'],
                            $pi['pi_reserved'],
                            $pi['pi_shipped'],
                            $pi['pi_update_time'],
                            $p['product_declared_value'],
                            $p['product_weight'],
                        );
                        $exportIndex=$exportObj->setRowsValue($exportRow, $exportIndex, function($index) {
                            $keys = array(1, 2, 3, 4);
                            if (in_array($index, $keys)) {
                                return Common_ExportForExcel::TYPE_STRING2;
                            }
                            return false;
                        });
                        $index++;
                        $exportRow=array();
                    }
                    ++$pageSize;
                    $rows = $this->serviceClass->getByCondition($condition, 'pi_id', 300, $pageSize, array('pi_id desc'));
                }
            }
        }

      $exportObj->save('productInventory'.date('YmdHis'));
    }

    //通过customer_code导出批次库存
    public function exportForCustomerAction()
    {   
        if ($this->_request->isPost()) {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');

        $fileName = $_FILES['uploadXLS']['name'];
        $filePath = $_FILES['uploadXLS']['tmp_name'];
        $pathinfo = pathinfo($fileName);
        if (!isset($pathinfo["extension"]) && $pathinfo["extension"] != "xls") {
            echo '<script>window.parent.alertTip("请选择xls文件");</script>';
            echo '<script>window.location.href="/warehouse/Inventory/index";</script>';
            exit;
        }
        $fileData = Common_Upload::readEXCELAndType($filePath);
        $fileData = $fileData['value'];

        $queryType = $this->_request->getParam('query_type',"0");
        $isTemplate = array_shift($fileData);
        if(!(($isTemplate[0] == '客户代码' && $queryType ==0) || ($isTemplate[0] == '料件号' && $queryType ==1))){
            echo '<script>window.parent.alertTip("请选择合适的模板");</script>';
            echo '<script>window.location.href="/warehouse/Inventory/index";</script>';
            exit;
        }
        if($queryType == 0){
            $condition['customer_codes'] = array_map('array_shift', $fileData);
        }
        if($queryType == 1){
            $goodsIdArr = array_map('array_shift', $fileData);
            //通过料件号查询产品id
            $productIdArr = array();
            foreach($goodsIdArr as $key=>$goodsId){
                $productInfo = Service_Product::getByCondition(array('goods_id'=>(string)$goodsId),'product_id');
                foreach($productInfo as $pik=>$piv){
                    $productIdArr[] = $piv['product_id'];
                }
            }
            $condition['product_id_array'] = $productIdArr;
            if(empty($condition['product_id_array'][0])){
                exit();
            }
        }
        
        $showFields = array(
            'customer.customer_code',
            'product.product_sku',
            'product_barcode',
            'product.product_title',
            'pi_onway',
            'pi_pending',
            'pi_sellable',
            'pi_unsellable',
            'pi_reserved',
            'pi_shipped',
            'pi_update_time',
            'product.product_declared_value',
            'product.product_weight',
        );
        $rows = $this->serviceClass->getLeftJoinByCondition($condition, $showFields, false, false, array('product_inventory.customer_id'));
        $filename    = 'inventoryForCustomer' . date('YmdHis').'.xls';
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';
        $table = new PHPExcel();
        $table->getDefaultStyle()->getFont()->setName('宋体');
        $table->setActiveSheetIndex(0);
        $table->setActiveSheetIndex(0)->setTitle("产品库存列表");
        $objActSheet=$table->setActiveSheetIndex(0);

		$objActSheet->setCellValue('A1','客户代码');
        $objActSheet->setCellValue('B1','产品SKU');
        $objActSheet->setCellValue('C1','产品代码');
        $objActSheet->setCellValue("D1","料件号");
        $objActSheet->setCellValue('E1','产品名称');
        $objActSheet->setCellValue('F1','在途');
        $objActSheet->setCellValue('G1','已收货');
        $objActSheet->setCellValue("H1","可用");
        $objActSheet->setCellValue("I1","问题库存");
        $objActSheet->setCellValue("J1","出货占用");
        $objActSheet->setCellValue("K1","已出货");
        $objActSheet->setCellValue("L1","更新时间");
        $objActSheet->setCellValue("M1","申报价值");
        $objActSheet->setCellValue("N1","重量");

        foreach ($rows as $key => $val) {
            $rowNum = $key+2;
            $objActSheet->setCellValue('A'.$rowNum, $val['customer_code']);
            $objActSheet->setCellValueExplicit('B'.$rowNum, $val['product_sku'], PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->setCellValueExplicit('C'.$rowNum, $val['product_barcode'], PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->setCellValue('D'.$rowNum, $val['goods_id']);
            $objActSheet->setCellValueExplicit('E'.$rowNum, $val['product_title'], PHPExcel_Cell_DataType::TYPE_STRING);
            $objActSheet->setCellValue('F'.$rowNum, $val['pi_onway']);
            $objActSheet->setCellValue('G'.$rowNum, $val['pi_pending']);
            $objActSheet->setCellValue('H'.$rowNum, $val['pi_sellable']);
            $objActSheet->setCellValue('I'.$rowNum, $val['pi_unsellable']);
            $objActSheet->setCellValue('J'.$rowNum, $val['pi_reserved']);
            $objActSheet->setCellValue('K'.$rowNum, $val['pi_shipped']);
            $objActSheet->setCellValue('L'.$rowNum, $val['pi_update_time']);
            $objActSheet->setCellValue('M'.$rowNum, $val['product_declared_value']);
            $objActSheet->setCellValue('N'.$rowNum, $val['product_weight']);
        }

        $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=productInventory".date('YmdHis').'.xls');
        header("Content-Type:APPLICATION/OCTET-STREAM;charset=utf-8");
        $objWriter->save('php://output');
        exit;
        }
    }
    

    //下载导入模板
    public function exportForCustomerTempleteAction()
    {
        $queryType = $this->_request->getParam('type','');
        if($queryType == 0){
            $fullPath = APPLICATION_PATH."/../data/file/inventoryForCustomer.xls";
        }else{
            $fullPath = APPLICATION_PATH."/../data/file/inventoryForMaterialNumber.xls";
        }
        $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;
    }

}