<?php
class Service_CustomsInventoryProcess {
    protected $_error = array();
    protected $_date;
    protected $_type;
    public static $defaultType = array( 'I', 'E','D');//I增加库存，E扣减库存 D下载业务数据
    protected $_file;
    protected $_fileData;
    protected $_mergeData;
    protected $_path;
    protected $_index;
    protected $_session;
    protected $_excel;
    protected $_excelWriter;
    protected $_excelType = 'xlsx';
    protected $_sheet;
    protected $_sysProcNum;
    protected $_chunkSize = 50;
    protected $_wmsNum;
    protected $_totalSheet;
    protected $_header;

    public function __construct( $type, $file = array() ) {
        $this->_date = date( 'Y-m-d H:i:s' );
        $this->_session = Service_User::getLoginUser();
        $this->setType( $type );
        $this->setPath();
        if( $this->_type == 'D' ) {
            $this->setPHPExcel();
        } else {
            $this->setSysProcNum();
            $this->setFile( $file );
            if( $this->_type == 'E' ) {
                $this->setPHPExcel();
            }
        }
    }
    protected function getResponse() {
        $response = array( 'ask' => 0, 'msg' => '失败' );
        if( $this->_error ) {
            $response['msg'] = implode( ';', $this->_error );
        } else {
            $response['ask'] = 1;
            $response['msg'] = '成功';
            if( $this->_type == 'E' || $this->_type == 'D' ) {
                $response['sysProcNum'] = $this->_sysProcNum;
            }
        }
        $this->clean();
        return $response;
    }
    protected function clean() {
        $this->_error = array();
    }
    protected function setSysProcNum( $sysProcNum = '' ) {
        if( $sysProcNum === '' ) {
            $code = new Common_UniqueCode( 'sysProcNum');
            $this->_sysProcNum = $code->getCode();
            if( $this->_sysProcNum === false ) {
                $this->addError( $code->getError() );
            }
        } else {
            $this->_sysProcNum = $sysProcNum;
        }
    }
    protected function setPath() {
        $this->_path = implode( DIRECTORY_SEPARATOR, array( dirname( APPLICATION_PATH ),'data','upload','customs-inventory') );
        if( !file_exists( $this->_path ) ) {
            if( !mkdir( $this->_path, 0755, true ) )
                $this->addError( '创建临时文件夹失败' );
        }
    }
    protected function addError( $error ) {
        $this->_error[] = $error;
    }
    /* @todo:创建PHPExcel对象
     *
     */
    protected function setPHPExcel() {
        $lib = '';
        if( $this->_excelType == 'xls') {
            $lib = 'Excel5';
        } else if( $this->_excelType == 'xlsx') {
            $lib = 'Excel2007';
        } else {
           $this->addError('设置的Excel类型不正确');
            return;
        }
        include_once("PHPExcel.php");
        include_once("PHPExcel/IOFactory.php");
        try {
            $this->_excel = new PHPExcel();
            $this->_excelWriter = PHPExcel_IOFactory::createWriter( $this->_excel, $lib );
        } catch( Exception $e ) {
            $this->addError( $e->getMessage() );
        }
    }
    protected function setType( $type ) {
        if( $type === '' ) {
            $this->addError( '库存操作类型不能为空' );
        } else if( !in_array( $type, self::$defaultType ) ) {
            $this->addError( '库存操作类型不正确' );
        } else {
            $this->_type = $type;
        }
    }
    protected function setFile( $file ) {
        if( isset( $file[0] ) ) {
            if( count( $file ) > 1 ) {
                $this->addError( '一次只能上传一个文件' );
            } else {
                $this->_file = $file[0];
            }
        } else {
            $this->_file = $file;
        }
    }
    protected function isEmpty( $data ) {
        return  is_null( $data ) || ( is_string( $data ) && $data === '' ) || ( is_array( $data ) && empty( $data ) ) ? true :false;
    }
    protected function checkFile() {
        if( !$this->_file ) {
            $this->addError( '请上传文件' );
            return;
        }
        $fileName = time().$this->_file['name'];
        $splitArray = explode( '.', $fileName );
        if( !$splitArray ) {
            $this->addError( '请上传文件' );
            return;
        }

        $extension = strtolower( $splitArray[count($splitArray)-1] );
        if( count( $splitArray ) < 2 || ( $extension != 'xls' && $extension != 'xlsx' ) ) {
            $this->addError( '文件格式只能是xls|xlsx' );
            return;
        }
        if( !@move_uploaded_file( $this->_file['tmp_name'], $this->_path.DIRECTORY_SEPARATOR.$fileName ) ) {
            $this->addError( '无法在服务器上保存文件' );
            return;
        }
        //读取数据
        $file = $this->_path.DIRECTORY_SEPARATOR.$fileName;
        $this->_file['true_file'] = $file;
        $this->_fileData = Common_Upload::readEXCEL( $file, true );
        if( count( $this->_fileData ) < 2 ) {
            $this->addError( '第一个sheet内容不能为空' );
            return;
        }
        $this->checkData();

        if( $this->_type == 'E' ) {
            $header = Common_Upload::readEXCEL( $file, true, 1 );
            $this->setHeader( $header );
        }
    }
    protected function setHeader( $header ) {
        $headerMap = $this->mapForHeader();
        $headerIndex = array();
        foreach( $headerMap as $key => $value ) {
            $tmpKey = array_search( $value, $header[0] );
            $headerIndex[$key] = $tmpKey;
        }
        unset( $header[0] );
        foreach( $header as $value) {
            $wmsNum = isset( $value[ $headerIndex['wms_num'] ] ) && $value[ $headerIndex['wms_num'] ] !== '' ? $value[ $headerIndex['wms_num'] ] : 0;
            foreach( $headerMap as $key => $text ) {
                $this->_header[ $wmsNum ][$key] = @$value[ $headerIndex[$key] ];
            }
        }
    }
    protected function getHeader( $wmsNum ) {
        return Service_CustomsFormData::getByField( $wmsNum, 'wms_num' );
    }
    //检查&合并数据
    protected function checkData() {
        $title = $this->_fileData[0];
        $index = array();
        if( $this->_type == 'I') {
            $map = $this->mapForAdd();
        } else {
            $map = $this->mapForDeduct();
        }
        foreach( $map as $key => $value ) {
            $tmpKey = array_search( $value, $title );
            if( $tmpKey === false ) {
                $this->addError( '缺少['. $value .']');
            } else {
                $index[$key] = $tmpKey;
            }
        }
        if( $this->_error )
            return;

        unset( $this->_fileData[0] );
        $this->_index = $index;
        $data = array();
        $cnt = 0;
        foreach( $this->_fileData as $line => $row ) {
            $error = array();
            foreach( $map as $key => $cnTitle ) {
                $index = $this->_index[$key];
                if( $this->isEmpty( $row[$index] ) ) {
                    //法二可为空
                    if( $key == 'qty_2' ) {
                        $row[$index] = 0;
                    } else if( $key == 'unit_2' ) {
                        $row[$index] = '';
                    }else {
                        $error[] = $cnTitle.'为空';
                    }
                }
                switch( $key ) {
                    case 'type':
                        if( $this->_type != $row[$index] )
                            $error[] = $cnTitle.'不正确';
                        break;
                    case 'g_qty':
                    case 'qty_1':
                    case 'decl_price':
                    case 'decl_total':
                        if( !is_numeric( $row[$index] ) || $row[$index] <= 0 ) {
                            $error[] = $cnTitle.'必须是数字,且大于0';
                        } else if( $this->_type == 'E' && $key == 'g_qty' && !preg_match( '/^\d+$/', $row[$index] ) ) {
                            $error[] = $cnTitle.'必须是整数';
                        }
                        break;
                    case 'qty_2':
                        if( $row[$index] ) {
                            if(  !is_numeric( $row[$index] ) || $row[$index] < 0  ) {
                                $error[] = $cnTitle.'必须是数字,且>=0';
                            }
                        } else {
                            $row[$index] = 0;
                        }
                        break;
                    case 'decl_date':
                        $date = gmdate( 'Y-m-d',PHPExcel_Shared_Date::ExcelToPHP( $row[$index] ) );
                        $time = strtotime( $date );
                        if( $time === false ) {
                            $error[] = $cnTitle.'不是日期';
                        } else {
                            $row[$index] = $date;
                            $this->_fileData[$line][$index] = $date;
                        }
                        break;
                }
                //合并数据
                $tmpIndex = $row[ $this->_index['record_num'] ].$row[ $this->_index['goods_id'] ].$row[ $this->_index['product_sku'] ];
                if( $key == 'g_qty' || $key == 'qty_1' || $key == 'qty_2' ) {
                    if( isset( $data[ $tmpIndex ][$key] ) ) {
                        $data[ $tmpIndex ][$key] += $row[$index];
                    } else {
                        $data[ $tmpIndex ][$key] = $row[$index];
                    }
                } else {
                    if( !isset( $data[ $tmpIndex ][$key] ) ) {
                        $data[ $tmpIndex ][$key] = $row[$index];
                    }
                }
            }
            if( $this->_type == 'I' ) {
                $gUnitIndex = $this->_index['g_unit'];
                $unit1Index = $this->_index['unit_1'];
                $unit2Index = $this->_index['unit_2'];
                $gQtyIndex = $this->_index['g_qty'];
                $qty1Index = $this->_index['qty_1'];
                $qty2Index = $this->_index['qty_2'];
                if( $row[$gUnitIndex] != '千克' && preg_match( '/^\d+\.(\d+)?$/',$row[$gQtyIndex] ) ) {
                    $error[] = '申报单位不是千克，所以申报数量不能是小数';
                }
                if( $row[$unit1Index] != '千克' && preg_match( '/^\d+\.(\d+)?$/',$row[$qty1Index] ) ) {
                    $error[] = '法一单位不是千克，所以法一数量不能是小数';
                }
                if( $row[$unit2Index] != '千克' && preg_match( '/^\d+\.(\d+)?$/',$row[$qty2Index] ) ) {
                    $error[] = '法二单位不是千克，所以法二数量不能是小数';
                }
            }
            if( $error ) {
                ++$cnt;
                $this->addError( '第'.($line + 1).'行:'. implode( ';', $error ) );
            }
            //不用返回这么多错误
            if( $cnt >= 20 ) {
                break;
            }
        }
        $this->_mergeData = array_values( $data );
    }
    //加库存excel模板标题 key请保持跟表的列一样，写入数据和导出数据要用到
    protected function mapForAdd() {
        return array(
            'decl_date'      => '申报日期',
            'type'           => '进出标识',
            'record_num'     => '备案序号',
            'goods_id'       => '料件号',
            'product_sku'    => '商品编码',
            'product_title' => '商品名称',
            'g_model'        => '规格型号',
            'g_qty'          => '申报数量',
            'g_unit'         => '申报计量单位',
            'qty_1'          => '法定数量',
            'unit_1'         => '法定单位名称',
            'qty_2'          => '法二数量',
            'unit_2'         => '法二单位名称',
            'decl_price'    => '申报单价',
            'decl_total'    => '申报总价',
            'currency'      => '币种名称'
        );
    }
    //扣库存excel模板标题 key请保持跟表的列一样，写入数据和导出数据要用到
    protected function mapForDeduct() {
        return array(
            'decl_date'     => '申报日期',
            'type'           => '进出标识',
            'wms_num'        => '仓库工作号',
            'record_num'     => '备案序号',
            'goods_id'       => '料件号',
            'product_sku'    => '商品编码',
            'g_qty'          => '申报数量',
        );
    }
    protected function mapForHeader() {
        return array(
            'wms_num'     => '仓库工作号',
            'piece'           => '件数',
            'net_weight'        => '净重',
            'gross_weight'     => '毛重',
            'remark'       => '备注',
        );
    }
    public function modifyInventory() {
        $this->checkFile();
        if( $this->_error ) {
            return $this->getResponse();
        }
        $adapter = Common_Common::getAdapter();
        $adapter->beginTransaction();
        try {
            $this->dealInventory();
            $this->addLog();
            $adapter->commit();
        } catch( Exception $e ) {
            $this->addError( $e->getMessage() );
            $adapter->rollBack();
        }
        $response = $this->getResponse();
        //删除上传的文件
        if( $response['ask'] == 1 ) {
            @unlink( $this->_file['true_file'] );
        }
        //生成一个业务需要的下载文件
        if( $this->_type == 'E' && $response['ask'] == 1) {
            $this->createCustomsDeclarationList( $this->_sysProcNum );
            $this->addHeader();
        }
        return $response;
    }
    protected function addHeader() {
        foreach( $this->_header as $value ) {
            $add = array(
                'wms_num' => $value['wms_num'],
                'piece' => $value['piece'],
                'net_weight' => $value['net_weight'],
                'gross_weight' => $value['gross_weight'],
                'remark' => $value['remark'],
            );
            Service_CustomsFormData::add( $add );
        }
    }
    protected function dealInventory() {
        foreach( $this->_mergeData as $key => $value ) {
            //先查数据
            $condition = array(
                'record_num' => $value['record_num'],
                'goods_id' => $value['goods_id'],
                'product_sku' => $value['product_sku'],
            );
            $exist = Service_CustomsInventory::getByCondition( $condition );
            if( $exist ) {
                //这个判断要不要都没关系
                if( $this->_type == 'I' && $exist[0]['g_unit'] != $value['g_unit'] )
                    throw new Exception( '更新失败，[备案序号:'.$value['record_num'].' 料件号:'.$value['goods_id'].' 商品编码:'.$value['product_sku'].']的申报单位与系统的不一致' );
                //做一下判断
                if( !$exist[0]['single_qty_1'] || $exist[0]['single_qty_1'] == 0 ) {
                    throw new Exception( '更新失败，[备案序号:'.$value['record_num'].' 料件号:'.$value['goods_id'].' 商品编码:'.$value['product_sku'].']单个法一数量不能为0' );
                }
                //因为扣库存的模板的申报数量的单位是个，如果申报单位是千克的，要把个转换成千克
                $gty = 0;
                if( $this->_type == 'E' && $exist[0]['g_unit'] == '千克') {
                    if( $exist[0]['unit_1'] != '千克' && $exist[0]['unit_2'] != '千克') {
                        throw new Exception( '更新失败，[备案序号:'.$value['record_num'].' 料件号:'.$value['goods_id'].' 商品编码:'.$value['product_sku'].']法一和法二的单位都不是千克，无法转换' );
                    } else if( $exist[0]['unit_1'] != '千克' && $exist[0]['unit_2'] == '千克' && ( !$exist[0]['single_qty_2'] || $exist[0]['single_qty_2'] == 0 ) ) {
                        throw new Exception( '更新失败，[备案序号:'.$value['record_num'].' 料件号:'.$value['goods_id'].' 商品编码:'.$value['product_sku'].']单个法二数量为0，无法转' );
                    }
                    $singleQty = $exist[0]['unit_1'] == '千克' ? $exist[0]['single_qty_1'] : $exist[0]['single_qty_2'];
                    $gty = $singleQty * $value['g_qty'];
                } else {
                    $gty = $value['g_qty'];
                }

                $update = array(
                    'g_qty' => $this->_type == 'I' ? $exist[0]['g_qty'] + $gty : $exist[0]['g_qty'] - $gty,
                    'qty_1' => $this->_type == 'I' ? $exist[0]['qty_1'] + $value['qty_1'] : $exist[0]['qty_1'] - ($value['g_qty'] * $exist[0]['single_qty_1']),
                    'qty_2' => $this->_type == 'I' ? $exist[0]['qty_2'] + $value['qty_2'] : $exist[0]['qty_2'] - ($value['g_qty'] * $exist[0]['single_qty_2']),
                    'sys_update_time' => $this->_date
                );
                /*if( $update['g_qty'] == 0 ) {
                    $id = Service_CustomsInventory::delete( $exist[0]['ci_id'], 'ci_id');
                } else {
                    $id = Service_CustomsInventory::update( $update, $exist[0]['ci_id'], 'ci_id');
                }*/
                //先不删数据，因为后面下载数据可能要用到
                $id = Service_CustomsInventory::update( $update, $exist[0]['ci_id'], 'ci_id');
            } else {
                if( $this->_type == 'E' )
                    throw new Exception( '更新失败，[备案序号:'.$value['record_num'].' 料件号:'.$value['goods_id'].' 商品编码:'.$value['product_sku'].']没有库存数据,请先增加库存再进行扣减' );

                $add = array(
                    'record_num'     => $value['record_num'],
                    'goods_id'       => $value['goods_id'],
                    'product_sku'    => $value['product_sku'],
                    'product_title' => $value['product_title'],
                    'g_model'        => $value['g_model'],
                    'g_qty'          => $this->_type == 'I' ? $value['g_qty'] : -$value['g_qty'],
                    'g_unit'         => $value['g_unit'],
                    'qty_1'          => $value['qty_1'],
                    'single_qty_1'  => sprintf('%.5f', $value['qty_1'] / $value['g_qty'] ),
                    'unit_1'         => $value['unit_1'],
                    'qty_2'          => $value['qty_2'],
                    'single_qty_2'  => $value['qty_2'] ? sprintf('%.5f', $value['qty_2'] / $value['g_qty'] ) : 0,
                    'unit_2'         => $value['unit_2'],
                    'decl_price'    => $value['decl_price'],
                    'currency'      => $value['currency'],
                    'sys_add_time' => $this->_date
                );
                $id = Service_CustomsInventory::add( $add );
            }
            if( !$id )
                throw new Exception( '更新失败，[备案序号:'.$value['record_num'].' 料件号:'.$value['goods_id'].' 商品编码:'.$value['product_sku'].']' );
        }
    }
    protected function addLog() {
        $ip = Common_Common::getIP();
        foreach( $this->_fileData as $key => $value ) {
            $add = array(
                'decl_date'     => $value[ $this->_index['decl_date'] ],
                'type'           => $value[ $this->_index['type'] ],
                'wms_num'        => $this->_type == 'I' ? '' : $value[ $this->_index['wms_num'] ],
                'record_num'     => $value[ $this->_index['record_num'] ],
                'goods_id'       => $value[ $this->_index['goods_id'] ],
                'product_sku'    => $value[ $this->_index['product_sku'] ],
                'g_qty'          => $value[ $this->_index['g_qty'] ],
                'product_title' => $this->_type == 'I' ? $value[ $this->_index['product_title'] ] : '',
                'g_model'        => $this->_type == 'I' ? $value[ $this->_index['g_model'] ] : '',
                'g_unit'         => $this->_type == 'I' ? $value[ $this->_index['g_unit'] ] : '',
                'qty_1'          => $this->_type == 'I' ? $value[ $this->_index['qty_1'] ] : '',
                'unit_1'         => $this->_type == 'I' ? $value[ $this->_index['unit_1'] ] : '',
                'qty_2'          => $this->_type == 'I' ? $value[ $this->_index['qty_2'] ] : '',
                'unit_2'         => $this->_type == 'I' ? $value[ $this->_index['unit_2'] ] : '',
                'decl_price'    => $this->_type == 'I' ? $value[ $this->_index['decl_price'] ] : '',
                'decl_total'    => $this->_type == 'I' ? $value[ $this->_index['decl_total'] ] : '',
                'currency'      => $this->_type == 'I' ? $value[ $this->_index['currency'] ] : '',
                'sys_add_time' => $this->_date,
                'operator_ip'  => $ip,
                'operator_id'  => $this->_session['user_id'],
                'sys_proc_num' => $this->_sysProcNum
            );
            $id = Service_CustomsInventoryLog::add( $add );
            if( !$id )
                throw new Exception( '保存第'. ( $key + 1 ) .'行数据日志失败' );
        }
    }
    //生成报关清单文件
    public function createCustomsDeclarationList( $sysProcNum ) {
        if( $sysProcNum === '' ) {
            $this->addError( '系统处理单号不能为空' );
            return $this->getResponse();
        }

        $this->setSysProcNum( $sysProcNum );

        if( !$this->_mergeData ) {
            $this->_mergeData = $this->getMergeData();
            if( !$this->_mergeData ) {
                $this->addError( '无对应的数据' );
                return $this->getResponse();
            }
        }

        $title = array('序号','入仓单号(料件号)','商品编码','报关品名','规格型号','申报数量','申报单位','法定数量','法定单位','第二数量','第二单位','单价','总价','申报币制','是否尾货','备案序号','原产国','目的国');

        foreach( $this->_mergeData as $value ) {
            $chunkList[$value['wms_num']][] = $value;
        }
        $chunkList = array_values( $chunkList );
        $this->_totalSheet = count($chunkList);

        foreach( $chunkList as $index => $chunk ) {
            $this->_wmsNum = $chunk[0]['wms_num'];
            //设置当前sheet
            if( $index != 0 ) {
                $this->_excel->createSheet();
            }
            $this->_sheet = $this->_excel->getSheet($index);
            $this->_sheet->setTitle('第'.($index+1).'单');
            //写入表头
            if( !isset( $this->_header[ $this->_wmsNum ] ) ) {
                $this->_header[ $this->_wmsNum ] = $this->getHeader( $this->_wmsNum );
            }
            $this->createTableHeader();

            foreach( $title as $key => $value ) {
                $column = Common_Common::getColumnName( $key );
                $columnName = $column.'9';
                $this->_sheet->setCellValue( $columnName, $value );
            }
            $this->_sheet->getStyle( 'A9:R9' )->getAlignment()->setHorizontal( PHPExcel_Style_Alignment::HORIZONTAL_CENTER );
            $this->_sheet->getStyle( 'A9:R9' )->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('FF9900');

            $seq = 10;
            foreach( $chunk as $i => $row ) {
                $condition = array(
                    'record_num' => $row['record_num'],
                    'goods_id' => $row['goods_id'],
                    'product_sku' => $row['product_sku'],
                );
                $exist = Service_CustomsInventory::getByCondition( $condition );

                $gty = 0;
                if( $row['type'] == 'E' && $exist[0]['g_unit'] == '千克') {
                    $singleQty = $exist[0]['unit_1'] == '千克' ? $exist[0]['single_qty_1'] : $exist[0]['single_qty_2'];
                    $gty = $singleQty * $row['g_qty'];
                } else {
                    $gty = $row['g_qty'];
                }

                $this->_sheet->setCellValue( 'A'.$seq, $i+1 );
                $this->_sheet->setCellValue( 'B'.$seq, $row['goods_id'] );
                $this->_sheet->setCellValue( 'C'.$seq, $row['product_sku'] );
                $this->_sheet->setCellValue( 'D'.$seq, $exist ? $exist[0]['product_title'] : '' );
                $this->_sheet->setCellValue( 'E'.$seq, $exist ? $exist[0]['g_model'] : ''  );
                $this->_sheet->setCellValue( 'F'.$seq, $gty );
                $this->_sheet->setCellValue( 'G'.$seq, $exist ? $exist[0]['g_unit'] : ''  );
                $this->_sheet->setCellValue( 'H'.$seq, $exist ? $exist[0]['single_qty_1'] * $row['g_qty'] : ''  );
                $this->_sheet->setCellValue( 'I'.$seq, $exist ? $exist[0]['unit_1'] : ''  );
                $qty2 = $exist && $exist[0]['single_qty_2'] != 0 ? $exist[0]['single_qty_2'] * $row['g_qty'] : '';
                $this->_sheet->setCellValue( 'J'.$seq, $qty2  );
                $this->_sheet->setCellValue( 'K'.$seq, $exist ? $exist[0]['unit_2'] : ''  );
                $this->_sheet->setCellValue( 'L'.$seq, $exist ? $exist[0]['decl_price'] : ''  );
                $this->_sheet->setCellValue( 'M'.$seq, $exist ? sprintf( '%.2f', $exist[0]['decl_price'] * $row['g_qty']): ''  );
                $this->_sheet->setCellValue( 'N'.$seq, $exist ? $exist[0]['currency'] : ''  );
                $this->_sheet->setCellValue( 'O'.$seq, ''  );
                $this->_sheet->setCellValue( 'P'.$seq, $row['record_num']  );
                $this->_sheet->setCellValue( 'Q'.$seq, '中国'  );
                $this->_sheet->setCellValue( 'R'.$seq, '香港'  );
                for( $i = 0; $i < 18; $i++ ) {
                    $column = Common_Common::getColumnName( $i );
                    $columnName = $column.$seq;
                    $this->_sheet->getStyle( $columnName )->getAlignment()->setHorizontal( PHPExcel_Style_Alignment::HORIZONTAL_CENTER );
                }
                $seq++;
            }
            $this->_sheet->getStyle('A9:R'.(--$seq))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        }
        $fileName = $this->_sysProcNum.'.'.$this->_excelType;
        $file = $this->_path.DIRECTORY_SEPARATOR.$fileName;
        $this->_excel->setActiveSheetIndex(0);
        $this->_excelWriter->save( $file );
        $response = $this->getResponse();
        $response['file'] = $file;
        return $response;
    }
    protected function getMergeData() {
        $condition = array(
            'sys_proc_num' => $this->_sysProcNum
        );
        $log = Service_CustomsInventoryLog::getByCondition( $condition );
        $data = array();
        foreach( $log as $line => $row ) {
            //合并数据
            $tmpIndex = $row['record_num'].$row['goods_id'].$row['product_sku'];
            if( isset( $data[ $tmpIndex ] ) ) {
                $data[ $tmpIndex ]['g_qty'] += $row['g_qty'];
            } else {
                $data[ $tmpIndex ] = $row;
            }
        }
        return array_values( $data );
    }

    protected function createTableHeader() {
        $headers = array(
            array( '项目名称:', 'CSCM-OWNEX', '订单号:', ' ', '截重时间:', ' ', 'S/O:', '', '收货人', 'TINTO SUPPLY CHAIN LIMITED', '收货人国家', ' ', '', '' ),
            array( '装箱单号（客户作业号）:', $this->_wmsNum, '出口口岸:', '深圳湾关', '目的港:', '', '目的国:', '香港', '收货人地址', "Unit A3, G/F Wing Loi Ind.,\nNo.8-14 Wing Kei Road,\nKwai Chung , N.T. Hong Kong", '收货人通讯方式', '00852-55729936', '', '' ),
            array( '船名/航次:', ' ', '柜号/柜型:', ' ', '仓库使用企业', '000/招海', '是否仓转仓', '否', '通知人', '', '发货人简称', 'CMBL', '', '' ),
            array( '包装种类:', '其它', '总毛重:', @$this->_header[ $this->_wmsNum ]['gross_weight'], '总净重:', @$this->_header[ $this->_wmsNum ]['net_weight'], '总件数', @$this->_header[ $this->_wmsNum ]['piece'], '通知人地址', ' ', '发货人通讯方式', ' ', '通知人国家', ' ' ),
            array( '备注栏：', @$this->_header[ $this->_wmsNum ]['remark'], '', '', '是否二次转关', ' ', '拼数：', $this->_totalSheet, '收货人代码', ' ', '通知人代码', ' ', '通知人通讯方式', ' ', ),
            array( '运输方式', ' ', '运输工具名称', ' ', '结转方手册号', ' ', '结转方核注清单号', ' ', '装货港区', '', '箱属', '', '', '', ),
        );
        foreach( $headers as $line => $header ) {
            foreach( $header as $i => $value ) {
                $column = Common_Common::getColumnName( $i );
                $columnName = $column.($line+2);
                $this->_sheet->setCellValue( $columnName, $value );
                $this->_sheet->getStyle( $columnName )->getAlignment()->setHorizontal( PHPExcel_Style_Alignment::HORIZONTAL_CENTER );
                //设置背景色
                if( ($i+1) % 2 != 0 ) {
                    $this->_sheet->getStyle( $columnName )->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('C4D79B');
                }
            }
        }
        //设置边框
        $this->_sheet->getStyle('A2:N7')->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        $this->_sheet->mergeCells('A1:N1');
        $this->_sheet->mergeCells('B6:D6');
    }

}