<?php
class Service_Location extends Common_Service
{
    /**
     * @var null
     */
    public static $_modelClass = null;

    /**
     * @return Table_Location|null
     */
    public static function getModelInstance()
    {
        if (is_null(self::$_modelClass)) {
            self::$_modelClass = new Table_Location();
        }
        return self::$_modelClass;
    }

    /**
     * @param $row
     * @return mixed
     */
    public static function add($row)
    {
        $model = self::getModelInstance();
        return $model->add($row);
    }


    /**
     * @param $row
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function update($row, $value, $field = "lc_id")
    {
        $model = self::getModelInstance();
        return $model->update($row, $value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function delete($value, $field = "lc_id")
    {
        $model = self::getModelInstance();
        return $model->delete($value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @param string $colums
     * @return mixed
     */
    public static function getByField($value, $field = 'lc_id', $colums = "*")
    {
        $model = self::getModelInstance();
        return $model->getByField($value, $field, $colums);
    }
    
    public static function getByWhere($where) {
    	$model = self::getModelInstance();
    	return $model->getByWhere($where);
    }

    /**
     * @return mixed
     */
    public static function getAll()
    {
        $model = self::getModelInstance();
        return $model->getAll();
    }

    /**
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getByCondition($condition, $type, $pageSize, $page, $order);
    }

    public static function getLeftJoinWarehouseAreaByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getLeftJoinWarehouseAreaByCondition($condition, $type, $pageSize, $page, $order);
    }

    public static function getLeftJoinInventoryBatchByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getLeftJoinInventoryBatchByCondition($condition, $type, $pageSize, $page, $order);
    }

    public static function getLcationAndWaCodeByCondition($condition,$type,$pageSize = 0, $page = 1, $order = ""){
        $model = self::getModelInstance();
        return $model->getLocationAndWaCodeByCondition($condition, $type, $pageSize, $page, $order);
    }

    public static function joinArea($condition = array(), $type = '*',$columns='*',$pageSize = 0, $page = 1, $order = ""){
        $model = self::getModelInstance();
        return $model->joinArea($condition, $type, $columns,$pageSize, $page, $order);
    }

    /**
     * @param $val
     * @return array
     */
    public static function validator($val)
    {
        $validateArr = $error = array();
        
        $validateArr[] = array("name" =>EC::Lang('lc_code'), "value" =>$val["lc_code"], "regex" => array("require",));
        $validateArr[] = array("name" =>EC::Lang('status'), "value" =>$val["lc_status"], "regex" => array("positive"));
        $validateArr[] = array("name" =>EC::Lang('warehouse'), "value" =>$val["warehouse_id"], "regex" => array("positive"));
        $validateArr[] = array("name" =>EC::Lang('locationTypeCode'), "value" =>$val["lt_code"], "regex" => array("require",));
        $validateArr[] = array("name" =>EC::Lang('waCode'), "value" =>$val["wa_code"], "regex" => array("require",));
        $validateArr[] = array("name" =>EC::Lang('putawaySort'), "value" =>$val["lc_sort"], "regex" => array("positive"));
        return  Common_Validator::formValidator($validateArr);
    }


    /**
     * @param array $params
     * @return array
     */
    public  function getFields()
    {
        $row = array(
        
              'E0'=>'lc_id',
              'E1'=>'lc_code',
              'E2'=>'lc_note',
              'E3'=>'lc_status',
              'E4'=>'warehouse_id',
              'E5'=>'lt_code',
              'E6'=>'wa_code',
              'E7'=>'lc_sort',
              'E8'=>'lc_add_time',
              'E9'=>'lc_update_time',
              'E06'=>'warehouse_area.wa_name',
        );
        return $row;
    }

    public function getXLSData($uploadFile,$field){

        $path = APPLICATION_PATH.'/../data/upload/location';

        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|csv';
        $config['max_size']			= '10000';
        $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;
        }
        switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":
                $resultArray = Common_Upload::readEXCEL($full_path);
                break;
            case ".csv":
                $resultArray = Common_Upload::readCSV($full_path);
                break;
            default:
                $resultArray = array();
                break;
        }
        if(empty($resultArray) || !is_array($resultArray)){
            $result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
            //echo json_encode($result);
            //exit;
        }
        @unlink($full_path);
        return $resultArray;

    }

    public function addProcess($row,$rowIndex){
        $DB = Common_Common::getAdapter();
        $DB->beginTransaction();
        $result = array('ask'=>'0','message'=>'');
        try{
            $lc_code = trim($row[0]);
            if($lc_code=="") throw new Exception("行".$rowIndex."货架号为空");
            $existLocation = Service_Location::getByField($lc_code,"lc_code","*");
            if(!empty($existLocation)){
                throw new Exception("行".$rowIndex."货架号".$lc_code."已存在");
            }
            $lc_note = $row[6]==""?"":$row[6];
            $lc_status = 1;
            if($row[1]=="不可用"){
                $lc_status = 0;
            }
            if($row[2]=="") throw new Exception("行".$rowIndex."仓库为空");
            $warehouse = Service_Warehouse::getByField($row[2],'warehouse_code',"*");
            if(empty($warehouse)) throw new Exception("行".$rowIndex."仓库".$row[2]."不存在");
            $warehouse_id = $warehouse['warehouse_id'];
            $lt_code = $row[3];
            if($lt_code=="") throw new Exception("行".$rowIndex."货架类型代码为空");
            // if(!in_array($lt_code , array('A','B','C')))throw new Exception("行".$rowIndex."的货架类型代码只能是A、B、C中的某一种");
            $ltRow = Service_LocationType::getByField($lt_code,'lt_code',"*");
            if(empty($ltRow)) throw new Exception("行".$rowIndex."货架类型代码".$lt_code."不存在");
            if ($ltRow['lt_status']=='0') {
              throw new Exception("行".$rowIndex."货架类型代码".$lt_code."不可用");
            }
            $wa_code = $row[4];
            if($wa_code=="") throw new Exception("行".$rowIndex."分区代码".$wa_code."为空");
            $warehouseArea = Service_WarehouseArea::getByField($wa_code,'wa_code',"*");
            if(empty($warehouseArea)) throw new Exception("行".$rowIndex."分区代码".$wa_code."不存在");
            $lc_sort = $row[5]==""?'0':$row[5];
            $lc_add_time = date("Y-m-d H:i:s");
            $lc_update_time = date("Y-m-d H:i:s");
            $location = array(
                'lc_code'=>$lc_code,
                'lc_status'=>$lc_status,
                'warehouse_id'=>$warehouse_id,
                'lt_code'=>$lt_code,
                'wa_code'=>$wa_code,
                'lc_sort'=>$lc_sort,
                'lc_note'=>$lc_note,
                'lc_add_time'=>$lc_add_time,
                'lc_update_time'=>$lc_update_time
            );
            Service_Location::add($location);
            $DB->commit();
            $result['ask'] = "1";
            $result['message'] = "货架号".$lc_code."新增成功!";
        }catch (Exception $e){
            $DB->rollBack();
            $result['ask'] = "0";
            $result['message'] = "货架号".$lc_code."新增失败:".$e->getMessage();
        }
        return $result;
    }

}