<?php
class Warehouse_LocationController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "warehouse/views/default/";
        $this->serviceClass = new Service_Location();
    }

    public function listAction()
    {
        $status=Common_Type::status('auto');
        $wh=Common_DataCache::getWarehouseSimple();
        $warehouseArea=Common_DataCache::getWarehouseArea();
        $locationType=Common_DataCache::getLocationType();
        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();

            $condition = $this->serviceClass->getMatchFields($params);

            $count = $this->serviceClass->getLeftJoinWarehouseAreaByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    
                'lc_code',
                'lc_note',
                'lc_status',
                'warehouse_id',
                'lt_code',
                'wa_code',
                'lc_sort',
                'lc_update_time',
                'lc_id',
                'warehouse_area.wa_name',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getLeftJoinWarehouseAreaByCondition($condition,$showFields, $pageSize, $page, array('lc_code asc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['warehouse'] = $wh;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->status=$status;
        $this->view->warehouseArea=$warehouseArea;
        $this->view->locationType=$locationType;
        echo Ec::renderTpl($this->tplDirectory . "location_index.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                
              'lc_id'=>'',
              'lc_code'=>'',
              'lc_note'=>'',
              'lc_status'=>'',
              'warehouse_id'=>'',
              'lt_code'=>'',
              'wa_code'=>'',
              'lc_sort'=>'',
            );
            $row=$this->serviceClass->getMatchEditFields($params,$row);
            $paramId = $row['lc_id'];
            if (!empty($row['lc_id'])) {
                unset($row['lc_id']);
            }
            $errorArr = $this->serviceClass->validator($row);

            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message'=>'',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }

            if (!empty($paramId)) {
                $oldRow=$this->serviceClass->getByField($paramId);
                if($oldRow['lc_code']!=$row['lc_code']){
                    $batch=Service_InventoryBatch::getByField($oldRow['lc_code'],'lc_code');
                    if(!empty($batch)){
                        $return['errorMessage']=array(Ec::Lang('notEdit'));
                        die(Zend_Json::encode($return));
                    }
                    if($this->serviceClass->getByField($row['lc_code'],'lc_code')){
                        $return['errorMessage']=array(Ec::Lang('lc_code').Ec::Lang('exist'));
                        die(Zend_Json::encode($return));
                    }
                }
                $result = $this->serviceClass->update($row, $paramId);
            } else {
                if($this->serviceClass->getByField($row['lc_code'],'lc_code')){
                    $return['errorMessage']=array(Ec::Lang('lc_code').Ec::Lang('exist'));
                    die(Zend_Json::encode($return));
                }
                $result = $this->serviceClass->add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('Success.');
            }

        }
        die(Zend_Json::encode($return));
    }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'lc_id')) {
            $rows=$this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    public function deleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                $row=$this->serviceClass->getByField($paramId);
                if($row){
                    $batch=Service_InventoryBatch::getByField($row['lc_code'],'lc_code');
                    if(!empty($batch)){
                        $result['message']=Ec::Lang('notDelete');
                        die(Zend_Json::encode($result));
                    }
                }
                if ($this->serviceClass->delete($paramId)) {
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }
            }
        }
        die(Zend_Json::encode($result));
    }

    public function printAction(){
        $shelfCodes = $this->_request->getParam('shelfCodes',"");
        //echo "shelfCodes=".$shelfCodes;
        $shelfArr = explode(",",$shelfCodes);
        foreach($shelfArr as $key=>$value){
            if($value=="") unset($shelfArr[$key]);
        }
        //$shelfArr[] = "jm-lin-sky-967";
        $this->view->shelfCodes = array_chunk($shelfArr,5);
        echo Ec::renderTpl($this->tplDirectory . "shelf-print.tpl", 'layout');
    }

    public function batchImportAction(){
        $result = array("ask"=>1,"message"=>"",'error'=>array());
        $xlsData = Service_Location::getXLSData($_FILES,'filename');

        if(count($xlsData[0])!=7||($xlsData[0][0]!="货架号"||$xlsData[0][1]!="状态"||$xlsData[0][2]!="仓库"||$xlsData[0][3]!="货架类型代码"||$xlsData[0][4]!="分区代码"||$xlsData[0][5]!="上架优先级"||$xlsData[0][6]!="描述")){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照货架号,状态,仓库,货架类型代码,分区代码,上架优化级,描述!";
            die(json_encode($result));
        }
        $totalMessage = "";
        $total = 0;
        $success = 0;
        $fail = 0;
        $index = 2;
        foreach($xlsData as $key=>$row){
            if($key==0) continue;
            $total++;
            $return = Service_Location::addProcess($row,$index);
            $index++;
            if($return['ask']=="1"){
                $success++;
            }else{
                $fail++;
                $result['error'][] = $return['message'];
            }
        }
        $result['message'] = "本次批量导入".$total."个,成功".$success."个,失败".$fail."个";
        die(json_encode($result));
    }

    public function batchImportTemplateAction(){
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        $fullPath = APPLICATION_PATH."/../data/xls".'/batchImportLocation.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);
        if(!file_exists($fullPath))
            echo '文件不存在！';
        else
            echo file_get_contents($fullPath);
        exit;
    }
}