package com.gaowj.uploadfile;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import oracle.sql.BLOB;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONObject;

import com.gaowj.business.SystemOpeBusiness;
import com.gaowj.business.UploadfileBusiness;
import com.gaowj.business.action.BasicAction;
import com.gaowj.business.comp.BusinessManager;
import com.gaowj.business.exception.BusinessException;
import com.gaowj.business.util.PropUtil;
import com.gaowj.business.util.QueryParamUtil;
import com.gaowj.business.util.RequestUtils;
import com.gaowj.business.util.SessionUtil;
import com.gaowj.business.util.Status;
import com.gaowj.business.vfs.FileUtil;
import com.gaowj.util.AuthenticateUtil;
import com.gaowj.util.ServiceUtil;

public class actAction extends BasicAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5113335237311018661L;
	
	private JSONObject jsonObject = new JSONObject();

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}
	
	/**
	 * 插入
	 * @param entity
	 * @throws BusinessException
	 */
	public String insertUploadfile() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		jsonObject = new JSONObject();
		try {
			entity = QueryParamUtil.StringToDate(entity);
				
			//去除不要更新的字段
			entity.remove("OPETYPE");
			boolean is_save2db = Boolean.parseBoolean(PropUtil.getValue("uploadfile_savetodb", "quartz_service", "true"));
			if(is_save2db){
				//处理上传文件保存到数据库
				if(entity.get("FILE_SAVE_PATH")!=null && entity.get("FILE_SVAE_NAME")!=null){
					String uploadFile  = (String)entity.get("FILE_SAVE_PATH")+File.separator+(String)entity.get("FILE_SVAE_NAME");
					FileUtil fileUtil = new FileUtil();
					File f = new File(uploadFile);
					if(f.isFile()){
						entity.put("BINARY_DATA", fileUtil.getBytes(fileUtil.getInputStream(uploadFile)));
					}
				}
			}
			
			//新增
			business.insert_uploadfile(entity);
			
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
				sysbusiness.insert_logBusiness("insertUploadfile", "" + entity,
						"增加文件数据", (String) entity.get("UUID"), (String) entity
								.get("FILE_NAME"), "uploadfile");
			//	
			jsonObject.putAll(Status.getStatusSuccessMessage("保存成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("保存失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	/**
	 * 更新
	 * @param entity
	 * @throws BusinessException
	 */
	public String updateUploadfile() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		try {
			
			//去除不要更新的字段
			entity.remove("OPETYPE");
			//修改
			entity = QueryParamUtil.StringToDate(entity);
			business.update_uploadfile(entity);
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("updateUploadfile", "" + entity, 
					"修改文件数据",(String) entity.get("UUID"), (String) entity
					          .get("FILE_NAME"),"uploadfile");
			//
			jsonObject.putAll(Status.getStatusSuccessMessage("修改成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("修改失败"));
			e.printStackTrace();
		}
		return "json";
	}

	/**
	 * 软删除
	 * @param entity
	 * @throws BusinessException
	 */
	public String deleteUploadfile() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String deletekey = (String) entity.get("CODE");
		List<String> ListKey = QueryParamUtil.StringToList(deletekey);
		
		try {
			business.delete_uploadfile(ListKey);
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("deleteUploadfile", "" + ListKey,
					"软删除文件数据", deletekey, "多个流水号","uploadfile");
			//
			
			jsonObject.putAll(Status.getStatusSuccessMessage("软删除成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("软删除失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	/**
	 * 恢复删除
	 * @param entity
	 * @throws BusinessException
	 */
	public String resumeUploadfile() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String deletekey = (String) entity.get("CODE");
		List<String> ListKey = QueryParamUtil.StringToList(deletekey);
		
		try {
			business.resume_uploadfile(ListKey);
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("resumeUploadfile", "" + ListKey,
					"恢复文件数据", deletekey, "多个流水号","uploadfile");
			//
			
			jsonObject.putAll(Status.getStatusSuccessMessage("恢复成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("恢复失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	/**
	 * 在软删除基础上删除记录
	 * @param entity
	 * @throws BusinessException
	 */
	public String deleteTrueUploadfile() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String deletekey = (String) entity.get("CODE");
		List<String> ListKey = QueryParamUtil.StringToList(deletekey);
		
		//获取需删除的记录
		Map<String, Object> v_query = new HashMap<String,Object>();
		v_query.put("UUIDLIST", ListKey);
		List<Map<String, Object>> listData = business.list_uploadnofile(v_query);
		//
		
		try {
			business.delete_true_uploadfile(ListKey);
			
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			//sysbusiness.insert_logBusiness(具体方法，操作内容，操作描述，操作记录ID，操作记录中文描述，分类)
			sysbusiness.insert_logBusiness("deleteTrueUploadfile", "" + ListKey,
					"清除文件数据", deletekey, "多个流水号","uploadfile");
			//
			
			boolean delete_true_and_delete_disk_file = Boolean.parseBoolean(PropUtil.getValue("delete_true_and_delete_disk_file", "quartz_service", "false"));
			if(delete_true_and_delete_disk_file){
				//删除相应的目录上文件
				for(Map<String, Object> delete_m:listData){
					if(delete_m.get("FILE_SAVE_PATH")!=null && delete_m.get("FILE_SVAE_NAME")!=null){
						String ls_file = delete_m.get("FILE_SAVE_PATH").toString()+File.separator+delete_m.get("FILE_SVAE_NAME").toString();
						File dFile = new File(ls_file);
						if(dFile.exists()){
							boolean tf = dFile.delete();
							String tf_name = "";
							if(tf){
								tf_name = "清除目录文件成功";
							}else{
								tf_name = "清除目录文件失败,可能文件被占";
							}
							sysbusiness.insert_logBusiness("deleteTrueUploadfile", "" + ls_file,
									tf_name, delete_m.get("UUID").toString(), (String)delete_m.get("FILE_NAME"),"uploadfile");
							
						}
					}
				}
				//
			}
			jsonObject.putAll(Status.getStatusSuccessMessage("删除成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("删除失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	/**
	 * 根据条件清空大字段文件和加载大字段文件
	 * @param entity
	 * @throws BusinessException
	 */
	public String setUploadfile() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		String deletekey = (String) entity.get("CODE");
		List<String> ListKey = QueryParamUtil.StringToList(deletekey);
		List<String> setKeySuccess = new ArrayList<String>();
		String ls_setname = "";
		try {
			Map<String, Object> v_query = new HashMap<String,Object>();
			v_query.put("UUIDLIST", ListKey);
			List<Map<String, Object>> listData = business.list_uploadnofile(v_query);
			String ls_set = (String) entity.get("SETKEY");
			
			if(listData.size()>0){
				if(StringUtils.isNotEmpty(ls_set) && ls_set.equals("0")){
					ls_setname = "清空大数据字段文件";
					for(Map<String, Object> m:listData){
						String exist_file = (String)m.get("EXIST_FILE");
						if(exist_file.equals("1")){//清空大数据字段文件并写到文件上
							setKeySuccess.add((String)m.get("UUID"));
							String uuid = (String)m.get("UUID");
					    	String uploadnew = (String)m.get("FILE_SVAE_NAME");
							String uploadpath= (String)m.get("FILE_SAVE_PATH");
							db2file(uuid,uploadpath,uploadnew,false);
						}
					}
					if(setKeySuccess.size()>0){
						business.setnull_binary_data(setKeySuccess);
					}
				}else if(StringUtils.isNotEmpty(ls_set) && ls_set.equals("1")){
					ls_setname = "往大数据字段保存文件";
					for(Map<String, Object> m:listData){
						String exist_file = (String)m.get("EXIST_FILE");
						if(exist_file.equals("1")) continue;
						//处理上传文件保存到数据库
						if(m.get("FILE_SAVE_PATH")!=null && m.get("FILE_SVAE_NAME")!=null){
							String uploadFile  = (String)m.get("FILE_SAVE_PATH")+File.separator+(String)m.get("FILE_SVAE_NAME");
							FileUtil fileUtil = new FileUtil();
							File f = new File(uploadFile);
							if(f.isFile()){
								m.put("BINARY_DATA", fileUtil.getBytes(fileUtil.getInputStream(uploadFile)));
								m.remove("CREATE_NAME");
								m.remove("UPDATE_NAME");
								m.remove("EXIST_FILE");
								setKeySuccess.add((String)m.get("UUID"));
								business.update_uploadfile(m);
							}
						}
						
					}
				}
			}
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("setUploadfile"+ls_set, "" + ListKey+",处理("+setKeySuccess+")",
					ls_setname, deletekey, "多个流水号","uploadfile");
			//
			jsonObject.putAll(Status.getStatusSuccessMessage(ls_setname+"成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage(ls_setname+"失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	
	public String upload() throws BusinessException{
		String savePath = "";
		if(StringUtils.isEmpty(savePath)) savePath =  AuthenticateUtil.getEndpoint("uploadPath");
		if(StringUtils.isEmpty(savePath))savePath = request.getSession().getServletContext().getRealPath("/uploadFile/file/");
		try {
			savePath = setFilepath(savePath, true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.setUserUploadFilePath(savePath);
		super.upload();
		String ret = super.getUserUploadFileResult();
		// 操作日志
		SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
		sysbusiness.insert_logBusiness("uploadFile", "用户["+SessionUtil.getEmname()+"]上传文件:"+ret,
				"上传文件", ret, "上传文件："+super.getUserFileFileName(),"uploadfile");
		//
		return null;
    }
	
	/**
	 * 路径下有文件从路径中下载，没有则从库里写到路径中再下载
	 * @param entity
	 * @throws BusinessException
	 */
	public String download() throws BusinessException{
    	String ret_download ="";
    	String uuid = request.getParameter("uuid");
    	String uploadnew=request.getParameter("uploadnew");
		String uploadpath=request.getParameter("uploadpath");
		String downloadFilenameEncode1 = PropUtil.getValue("downloadFilenameEncode1", "quartz_service", "gbk");
		String downloadFilenameEncode2 = PropUtil.getValue("downloadFilenameEncode2", "quartz_service", "iso8859-1");
		super.setEncoding1(downloadFilenameEncode1);
		super.setEncoding2(downloadFilenameEncode2);
		if(new File(uploadpath+"/"+uploadnew).exists()==false){
			db2file(uuid,uploadpath,uploadnew,false);
			ret_download = super.download();
		}else{
			ret_download = super.download();
		}
		// 操作日志
		SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
		sysbusiness.insert_logBusiness("uploadFile", "用户["+SessionUtil.getEmname()+"]下载文件："+ uploadpath+"/"+uploadnew,
				"下载文件",uploadpath+"/"+uploadnew, request.getParameter("uploadold"),"uploadfile");
		//
    	return ret_download;
    }
	
	/**---------------供其它模块接口使用-------------------**/
	
	/**
	 * 软删除
	 * @param entity
	 * @throws BusinessException
	 */
	public String deleteUploadfileCommon() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
		Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		
		if(query.get("MAINDATA_ID")==null || query.get("MODULE_ID")==null){
			jsonObject.putAll(Status.getStatusErrorMessage("参数错误"));
			return "json";
		}
		//批处理MAINDATA_ID和MODULE_ID
		if(query.get("MAINDATA_ID")!=null){
			query.put("MAINDATA_IDLIST", QueryParamUtil.StringToList(query.get("MAINDATA_ID").toString()));
			query.remove("MAINDATA_ID");
		}
		if(query.get("MODULE_ID")!=null){
			query.put("MODULE_IDLIST", QueryParamUtil.StringToList(query.get("MODULE_ID").toString()));
			query.remove("MODULE_ID");
		}
		//
		
		try {
			query = QueryParamUtil.StringToDate(query);
			business.delete_uploadfile_common(query);
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("deleteUploadfile", "" + query,
					"软删除文件数据", query.get("MAINDATA_ID")+""+query.get("MODULE_ID"), "多个（模块+主表ID）","uploadfile");
			//
			
			jsonObject.putAll(Status.getStatusSuccessMessage("软删除成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("软删除失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	/**
	 * 恢复删除
	 * @param entity
	 * @throws BusinessException
	 */
	public String resumeUploadfileCommon() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
        Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		
		if(query.get("MAINDATA_ID")==null || query.get("MODULE_ID")==null){
			jsonObject.putAll(Status.getStatusErrorMessage("参数错误"));
			return "json";
		}
		//批处理MAINDATA_ID和MODULE_ID
		if(query.get("MAINDATA_ID")!=null){
			query.put("MAINDATA_IDLIST", QueryParamUtil.StringToList(query.get("MAINDATA_ID").toString()));
			query.remove("MAINDATA_ID");
		}
		if(query.get("MODULE_ID")!=null){
			query.put("MODULE_IDLIST", QueryParamUtil.StringToList(query.get("MODULE_ID").toString()));
			query.remove("MODULE_ID");
		}
		//
		
		try {
			query = QueryParamUtil.StringToDate(query);
			business.resume_uploadfile_common(query);
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			sysbusiness.insert_logBusiness("resumeUploadfile", "" + query,
					"恢复文件数据", query.get("MAINDATA_ID")+""+query.get("MODULE_ID"), "多个（模块+主表ID）","uploadfile");
			//
			
			jsonObject.putAll(Status.getStatusSuccessMessage("恢复成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("恢复失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	/**
	 * 在软删除基础上删除记录
	 * @param entity
	 * @throws BusinessException
	 */
	public String deleteTrueUploadfileCommon() throws BusinessException {

		UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
        Map<String, Object> query = RequestUtils.getUpdateFieldMap(request,RequestUtils.UPDATEDATAFIELDPREFIX);
		
		if(query.get("MAINDATA_ID")==null || query.get("MODULE_ID")==null){
			jsonObject.putAll(Status.getStatusErrorMessage("参数错误"));
			return "json";
		}
		//获取需删除的记录
		Map<String, Object> v_query = new HashMap<String,Object>();
		v_query.put("MAINDATA_IDLIST", QueryParamUtil.StringToList(query.get("MAINDATA_ID").toString()));
		v_query.put("MODULE_IDLIST", QueryParamUtil.StringToList(query.get("MODULE_ID").toString()));
		List<Map<String, Object>> listData = business.list_uploadnofile(v_query);
		//
		
		//批处理MAINDATA_ID和MODULE_ID
		if(query.get("MAINDATA_ID")!=null){
			query.put("MAINDATA_IDLIST", QueryParamUtil.StringToList(query.get("MAINDATA_ID").toString()));
			query.remove("MAINDATA_ID");
		}
		if(query.get("MODULE_ID")!=null){
			query.put("MODULE_IDLIST", QueryParamUtil.StringToList(query.get("MODULE_ID").toString()));
			query.remove("MODULE_ID");
		}
		//
		
		try {
			query = QueryParamUtil.StringToDate(query);
			business.delete_true_uploadfile_common(query);
			
			// 操作日志
			SystemOpeBusiness sysbusiness = BusinessManager.getBusiness(SystemOpeBusiness.class);
			//sysbusiness.insert_logBusiness(具体方法，操作内容，操作描述，操作记录ID，操作记录中文描述，分类)
			sysbusiness.insert_logBusiness("deleteTrueUploadfile", "" + query,
					"清除文件数据", query.get("MAINDATA_ID")+""+query.get("MODULE_ID"), "多个（模块+主表ID）","uploadfile");
			//
			boolean delete_true_and_delete_disk_file = Boolean.parseBoolean(PropUtil.getValue("delete_true_and_delete_disk_file", "quartz_service", "false"));
			if(delete_true_and_delete_disk_file){
				//删除相应的目录上文件
				for(Map<String, Object> delete_m:listData){
					if(delete_m.get("FILE_SAVE_PATH")!=null && delete_m.get("FILE_SVAE_NAME")!=null){
						String ls_file = delete_m.get("FILE_SAVE_PATH").toString()+File.separator+delete_m.get("FILE_SVAE_NAME").toString();
						File dFile = new File(ls_file);
						if(dFile.exists()){
							boolean tf = dFile.delete();
							String tf_name = "";
							if(tf){
								tf_name = "清除目录文件成功";
							}else{
								tf_name = "清除目录文件失败,可能文件被占";
							}
							sysbusiness.insert_logBusiness("deleteTrueUploadfile", "" + ls_file,
									tf_name, delete_m.get("UUID").toString(), (String)delete_m.get("FILE_NAME"),"uploadfile");
							
						}
					}
				}
				//
			}
			jsonObject.putAll(Status.getStatusSuccessMessage("删除成功"));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatusErrorMessage("删除失败"));
			e.printStackTrace();
		}
		return "json";
	}
	
	public void db2file(String uuid,String uploadpath,String uploadnew,boolean isDelete){
	    UploadfileBusiness business = BusinessManager.getBusiness(UploadfileBusiness.class);
	    Map<String, Object> mapquery = new HashMap<String, Object>();
        mapquery.put("UUID", uuid);
        List<Map<String, Object>> list = business.list_uploadfile(mapquery);
        byte[] b = null;
        BufferedInputStream bis = null;       
		try {
			if(list.get(0).get("BINARY_DATA") instanceof oracle.sql.BLOB){
	        	oracle.sql.BLOB filedata = (BLOB) list.get(0).get("BINARY_DATA");
	        	bis = new BufferedInputStream(filedata.getBinaryStream());
	        }else{
	        	b = (byte[]) list.get(0).get("BINARY_DATA");
	        	bis = new BufferedInputStream(new ByteArrayInputStream(b));
	        }
			File dir = new File(uploadpath);
			if (!dir.exists()) {
			    dir.mkdirs();
			}
			File tempfile = new File(uploadpath+"/"+uploadnew);
			FileOutputStream fio =new FileOutputStream(tempfile);
			IOUtils.copy(bis, fio);
			IOUtils.closeQuietly(bis);
			IOUtils.closeQuietly(fio);
			if(isDelete)tempfile.delete();
		}catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String setFilepath(String sourcepath,boolean tf)throws Exception{
		String destpath = "";
		if(StringUtils.isEmpty(sourcepath)||StringUtils.equalsIgnoreCase(sourcepath, "UUID"))
			sourcepath = PropUtil.getValue("uploadPath","quartz_service","");
		Calendar date=Calendar.getInstance();
		SimpleDateFormat format1=new SimpleDateFormat("yyyy"); 
		SimpleDateFormat format2=new SimpleDateFormat("MM");
		SimpleDateFormat format3=new SimpleDateFormat("dd");
		String name1=format1.format(date.getTime());
		String name2=format2.format(date.getTime());
		String name3=format3.format(date.getTime());
		destpath = sourcepath+name1+File.separator+name2+File.separator+name3;
		if(tf){
			File fileDir=new File(destpath);
			if(!fileDir.exists()){
				fileDir.mkdirs();
			}
		}
		return destpath;
	}

}
