package com.cpic.telsale.uploadData;

/**
 * Created by Kane on 2017/3/27.
 */

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.io.IOException;
import java.util.*;

import com.cpic.telsale.DataImport.*;

public class uploadDataProcessor extends HttpServlet
{
    private String tempPathRoot; //临时文件目录
    private String oracleURL;
    private String oracleUserName;
    private String oraclePassword;
    private String informixURL;
    private String telsalePolicyOperatorListTableName; //informix库电销转介绍表名

    @Override
    public void init( ServletConfig config ) throws ServletException
    {
        //获取参数
        oracleURL = ( String )config.getServletContext().getInitParameter( "oracleURL" );
        oracleUserName = ( String )config.getServletContext().getInitParameter( "oracleUserName" );
        oraclePassword = ( String )config.getServletContext().getInitParameter( "oraclePassword" );

        //informix
        informixURL = ( String )config.getServletContext().getInitParameter( "informixURL" );
        telsalePolicyOperatorListTableName = (String)config.getServletContext().getInitParameter( "telsalePolicyOperatorListTableName" );
    }

    @Override
    public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
    {
        tempPathRoot = ( String )request.getSession().getAttribute( "临时文件根目录" );
        String importMessage = null;

        try
        {
            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setRepository( new File( tempPathRoot ) );

            ServletFileUpload upload = new ServletFileUpload( factory );

            List<FileItem> uploadFiles = upload.parseRequest( request );
            Iterator iterFiles = uploadFiles.iterator();

            while ( iterFiles.hasNext() )
            {
                FileItem fileItem = ( FileItem )iterFiles.next();

                if ( !fileItem.isFormField() )
                {
                    //保存上传的文件，返回文件完整路径。
                    String upLoadedFileName = saveUploadedFile( fileItem );

                    importMessage = DataImport.importTelsalePolicyDataFromXlsx( upLoadedFileName,
                                                                                telsalePolicyOperatorListTableName,
                                                                                informixURL );
                }
            }
        }
        catch( FileUploadException error )
        {
            //文件上传有异常，包装一下重新抛出
            throw new ServletException( error.getMessage() );
        }
        catch( XlsFileFormatException error )
        {
            //文件格式异常
            importMessage = error.getMessage();
        }
        catch( IOException error )
        {
            //包装一下重新抛出
            throw new ServletException( error.getMessage() );
        }
        catch( Exception error )
        {
            throw new ServletException( error.getMessage() );
        }
        finally
        {
            request.getSession().setAttribute( "保存日志", importMessage );
        }

        response.sendRedirect( "uploadPolicyData/uploadPolicyData.jsp" );
    }

    /**
     * 保存上传文件
     *
     * @param item
     * @return
     * @throws Exception
     */
    private String saveUploadedFile( FileItem item ) throws Exception
    {
        String fileName = item.getName();

        int fileNameIndex = 0;
        long fileSize = item.getSize();

        //文件路径中可能有使用\和/作为目录分隔符，要分别判断
        fileNameIndex = fileName.lastIndexOf( "\\" );

        if ( fileNameIndex == 0 )
        {
            fileNameIndex = fileName.lastIndexOf( "/" );
        }

        //把文件名从路径中提取出来
        fileName = fileName.substring( fileNameIndex + 1, fileName.length() );

        if ( fileName.equals( "" ) && fileSize == 0 )
        {
            throw new Exception( "上传文件错误！" );
        }

        //生成最终的路径
        fileName = tempPathRoot + "/" + String.valueOf( Calendar.getInstance().getTimeInMillis() ) + fileName;

        File uploadedFile = new File( fileName );

        item.write( uploadedFile );

        return fileName;
    }
}
