package com.jw.app.mapping.action;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;

import com.gaowj.business.action.BasicAction;
import com.gaowj.business.comp.BusinessManager;
import com.gaowj.business.exception.BusinessException;
import com.gaowj.business.util.Encipher;
import com.gaowj.business.util.RequestUtils;
import com.gaowj.business.vfs.FileUtil;
import com.jw.app.business.MappingBusiness;
import com.jw.app.business.UserBusiness;
import com.jw.app.business.utils.QueryParamUtil;
import com.jw.app.business.utils.Status;

public class actAction extends BasicAction {

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

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}
	public String updateMappingUser() throws BusinessException {
		try {
			MappingBusiness business = BusinessManager
			.getBusiness(MappingBusiness.class);
			Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,
					RequestUtils.UPDATEDATAFIELDPREFIX);
			Map<String, Object> userentity = RequestUtils.getUpdateFieldMap(request,
					"USER0_");
			entity.remove("OPETYPE");
			
			//通过UUID获取SOO帐号和应用帐号匹配信息
			String uuid=entity.get("UUID").toString();
			Map<String, Object> ssoQuery = new HashMap<String, Object>();
			ssoQuery.put("tableName", "C_T_SYS_OTHERLOGIN");
			ssoQuery.put("UUID", uuid);
			Map<String, Object> cTSysOtherlogin=business.list_table(ssoQuery).get(0);
			//获取应用帐号表的uuid
			String mappingUuid=cTSysOtherlogin.get("USER_SYS_NAME").toString();
			//更新B_T_UFP_MAPPER_USER表
			userentity.put("tableName", "B_T_UFP_MAPPER_USER");
			userentity.put("UUID", mappingUuid);
			userentity.put("USER_ID", entity.get("USER_SYS_NAME"));
			//判断是否需要修改密码
			Map<String,Object> query=new HashMap<String, Object>();
			query.put("tableName", "B_T_UFP_MAPPER_USER");
			query.put("UUID", mappingUuid);
			String userPwd=business.list_table(query).get(0).get("USER_PWD").toString();
			if(userentity.get("USER_PWD")!=null&&!userentity.get("USER_PWD").toString().equals(userPwd)){
				//如果用户传进来的密码不为空，而且与数据库存储密码不一致，则需要重新加密存储
				userentity.put("USER_PWD", Encipher.EncodePasswd(userentity.get("USER_PWD").toString()));
			}else{
				userentity.remove("USER_PWD");
			}
			
			business.update_table(userentity);
			
			//不需要更新C_T_SYS_OTHERLOGIN表
			/*entity.put("tableName", "C_T_SYS_OTHERLOGIN");
			business.update_table(entity);*/
			jsonObject=new JSONObject();
			jsonObject.putAll(Status.getStatus(Status.UPDATE_OK));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jsonObject.putAll(Status.getStatus(Status.UPDATE_ERR));
		}
		return "json";
	}
	public String insertMappingUser() throws BusinessException {

		MappingBusiness business = BusinessManager
				.getBusiness(MappingBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);
		String userSysNames = RequestUtils.getString(request, "uuids");
		String s[] = StringUtils.split((String) userSysNames, ",");
		try {
			for (String uuids : s) {
				String data[] = StringUtils.split((String) uuids, "+");
				String username = data[0];
				String appid = data[1];
				// 映射用户的详细信息
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("tableName", "B_T_UFP_MAPPER_USER");
//				map.put("UUID", username);
//				map.put("APP_ID", appid);
//				List<Map<String, Object>> list = business.list_table(map);
//				if (list != null && list.size() > 0) {
//					Map<String, Object> userMap = list.get(0);
//					entity.put("USER_SYS_NAME", username);
//					entity.put("USER_NAME", userMap.get("USER_NAME"));
//					if (userMap.get("USER_PWD") != null)
//					entity.put("USER_PWD", userMap.get("USER_PWD"));
//				}
				// 映射应用的详细信息
				// map = new HashMap<String, Object>();
				// map.put("tableName", "B_T_UFP_APPS");
				// map.put("UUID", appid);
				// List<Map<String, Object>> apps = business.list_table(map);
				// if (apps != null && apps.size() > 0) {
				// Map<String, Object> appsMap = apps.get(0);
				// entity.put("YIYONG_ID", appid);
				// entity.put("YIYONG_NAME", appsMap.get("APP_NAME"));
				// entity.put("URL", appsMap.get("URL"));
				// }
				entity.put("USER_SYS_NAME", username);
				entity.put("YIYONG_ID", appid);
				entity.put("tableName", "C_T_SYS_OTHERLOGIN");
				entity.put("IS_DELETE", 0);
				entity = QueryParamUtil.StringToDate(entity);
				int count =business.listCount_table(entity);
				if(count==0)
					business.insert_table(entity);
			}
			jsonObject.putAll(Status.getStatus(Status.INSERT_OK));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatus(Status.INSERT_ERR));
			e.printStackTrace();
		}

		return "json";
	}

	public String insertTable() throws BusinessException {

		MappingBusiness business = BusinessManager
				.getBusiness(MappingBusiness.class);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);
		try {
			entity.remove("OPETYPE");
			entity = QueryParamUtil.StringToDate(entity);
			if(entity.get("USER_PWD") != null){
				entity.put("USER_PWD", Encipher.EncodePasswd((String)entity.get("USER_PWD")));
			}
			entity.put("UUID", UUID.randomUUID().toString());
			/*
			 * if(entity.get("UUID")!=null) { int
			 * count=business.listCount_table(entity); //记录已经存在 if(count>0) {
			 * entity.put("IS_DELETE", 0);
			 * count=business.listCount_table(entity); //记录未删除 if(count>0) {
			 * jsonObject.putAll(Status.getStatus(Status.INSERT_ERR_ID)); } else
			 * { jsonObject.putAll(Status.getStatus(Status.INSERT_ERR_DELETE));
			 * } } } else { business.insert_table(entity);
			 * jsonObject.putAll(Status.getStatus(Status.INSERT_OK)); }
			 */
			entity.put("IS_DELETE", 0);
			business.insert_table(entity);
			jsonObject.putAll(Status.getStatus(Status.INSERT_OK));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatus(Status.INSERT_ERR));
			e.printStackTrace();
		}
		return "json";
	}

	public String updateTable() throws BusinessException {

		MappingBusiness business = BusinessManager
				.getBusiness(MappingBusiness.class);
		Map<String, Object> entity = getUpdateFieldMapJw(
				request, RequestUtils.UPDATEDATAFIELDPREFIX);
		try {
			entity.remove("OPETYPE");
			entity = QueryParamUtil.StringToDate(entity);
			
			//如果修改b_t_ufp_mapper_user表，需要验证密码是否修改
			if("b_t_ufp_mapper_user".equalsIgnoreCase(entity.get("tableName").toString())){
				//更新前查看数据库存储的密码是否和用户传过来的一致，如果一致说明未修改，不一致则需要重新加密
				Map<String, Object> query=new HashMap<String, Object>();
				query.put("tableName", "b_t_ufp_mapper_user");
				//联合主键
				query.put("APP_ID", entity.get("APP_ID"));
				query.put("UUID", entity.get("UUID"));
				Map<String, Object> account =business.list_table(query).get(0);
				if(account.get("USER_PWD")!=null&&account.get("USER_PWD").toString().equals(entity.get("USER_PWD"))){
					//如果用户传过来的密码和数据库中加密后的密码一致，则不进行修改
					entity.remove("USER_PWD");
				}else{
					entity.put("USER_PWD", Encipher.EncodePasswd((String)entity.get("USER_PWD")));
				}
			}
			business.update_table(entity);
			jsonObject.putAll(Status.getStatus(Status.UPDATE_OK));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatus(Status.UPDATE_ERR));
			e.printStackTrace();
		}
		return "json";
	}

	public String deleteTable() throws BusinessException {

		MappingBusiness business = BusinessManager
				.getBusiness(MappingBusiness.class);
		String deletekey = RequestUtils.getString(request, "deletekey");
		List<String> ListKey = QueryParamUtil.StringToList(deletekey);
		Map<String, Object> entity = RequestUtils.getUpdateFieldMap(request,
				RequestUtils.UPDATEDATAFIELDPREFIX);
		entity.put("deletekey", ListKey);
		try {
			business.delete_table(entity);
			jsonObject.putAll(Status.getStatus(Status.DELETE_OK));
		} catch (Exception e) {
			jsonObject.putAll(Status.getStatus(Status.DELETE_ERR));
			e.printStackTrace();
		}
		return "json";
	}

	public String uploadUser() throws BusinessException {
		String upPath = request.getSession().getServletContext().getRealPath(
				"/uploadFile/apps/mappingUser");
		super.setUserUploadFilePath(upPath);
		return super.upload();
	}

	public String ImpUser() throws BusinessException {
		MappingBusiness business = BusinessManager
				.getBusiness(MappingBusiness.class);
		Map<String, Object> file = RequestUtils.getUpdateFieldMap(request,
				"FILED_");
		if (file.get("FILE_PATH") != null
				&& !file.get("FILE_PATH").toString().equals("")) {
			String filePath = file.get("FILE_PATH").toString();
			Workbook book = null;
			try {
				book = Workbook.getWorkbook(new File(filePath));
				int sheetCount = book.getNumberOfSheets();
				String data = "";
				System.out.println("-----------------共"+sheetCount+"条数据开始导入----------------------");
				// 获得第一个工作表对象(人员导入表)
				Sheet sheet = book.getSheet(0);
				int rows = sheet.getRows();
				//应用无法匹配错误的文本内容
				StringBuffer appErrorText=new StringBuffer();
				// 遍历每行每列的单元格
				for (int i = 1; i < rows; i++) {
					Map<String, Object> userMap = new HashMap<String, Object>();
					// 判断是否要新增数据，要是0 1 2 5 没有数据 则不更新数据
					int flag = 0;
					// 整列为空值
					int flag1 = 0;
					for (int j = 0; j < 6; j++) {
						if (sheet.getCell(j, i).getContents() == null
								|| sheet.getCell(j, i).getContents().equals(
										"null")
								|| sheet.getCell(j, i).getContents().equals(""))
							flag1++;
					}
					//主键设置
					userMap.put("UUID", UUID.randomUUID().toString());
					for (int j = 0; j < 6; j++) {
						Cell cell = sheet.getCell(j, i);
						String result = cell.getContents();
						if (result != null && !result.equals("null")
								&& !result.equals("")) {
							switch (j) {
							case 0:// 账号
								userMap.put("USER_ID", result);
								break;
							case 1:// 用户名
								userMap.put("USER_NAME", result);
								break;
							case 2:// 密码
								userMap.put("USER_PWD", Encipher.EncodePasswd(result));
								break;
							case 3:// 部门
								userMap.put("DEPT_NAME", result);
								break;
							case 4:// SORT
								userMap.put("SORT", result);
								break;
							case 5:// 应用编号
								//通过APP编码，查询到该APP的主键id
								Map<String,Object> query=new HashMap<String, Object>();
								query.put("tableName", "B_T_UFP_APPS");
								query.put("APP_ID", result);
								List<Map<String,Object>> list=business.list_table(query);
								if(list.size()>=2){
									appErrorText.append(String.format("第{0}行的应用ID不唯一，请咨询管理员。", i));
								}else if(list.size()==0){
									appErrorText.append(String.format("第{0}行的应用ID不存在，请咨询管理员。", i));
								}else{
									userMap.put("APP_ID", list.get(0).get("UUID"));
								}
								
								break;
							default:
								break;
							}
						} else {
							if (j == 0 || j == 1 || j == 5) {
								flag = 1;
								if (flag1 != 6)
									data = data + "第" + (i + 1) + "行,";
								break;
							}

						}
					}
					userMap.put("tableName", "B_T_UFP_MAPPER_USER");
					// 新增
					if (flag == 0) {
						int count = business.listCount_table(userMap);
						if (count > 0)
							business.update_table(userMap);
						else
							business.insert_table(userMap);
					}
				}
				if (data.equals("")&&appErrorText.length()==0)
					jsonObject.putAll(Status.getStatus(Status.UPDATE_OK));
				else {
					Map<String, Object> m = new HashMap<String, Object>();
					data = data.substring(0, data.length() - 1);
					data = data + "由于必填项未填写，未能导入到数据库，请重新填写后导入。";
					if(appErrorText.length()>0){
						data+=appErrorText.toString();
					}
					m.put("VALUE", data);
					jsonObject.putAll(m);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				jsonObject.putAll(Status.getStatus(Status.UPDATE_ERR));
			}
			System.out.println("-----------------数据导入结束----------------------");
		}
		return "json";
	}

	public String ImpMapper() throws BusinessException {
		MappingBusiness business = BusinessManager
				.getBusiness(MappingBusiness.class);
		UserBusiness userBusiness = BusinessManager.getBusiness(UserBusiness.class);
		Map<String, Object> file = RequestUtils.getUpdateFieldMap(request,
				"FILED_");
		if (file.get("FILE_PATH") != null
				&& !file.get("FILE_PATH").toString().equals("")) {
			String filePath = file.get("FILE_PATH").toString();
			Workbook book = null;
			try {
				book = Workbook.getWorkbook(new File(filePath));
				int sheetCount = book.getNumberOfSheets();
				String data = "";
				System.out.println("-----------------共"+sheetCount+"条数据开始导入----------------------");
				// 获得第一个工作表对象(人员导入表)
				Sheet sheet = book.getSheet(0);
				int rows = sheet.getRows();
				// 遍历每行每列单元格，判断数据是否可以导入
				for (int i = 1; i < rows; i++) {
					// 映射账号
					String userId = sheet.getCell(2, i).getContents();
					// 统一用户账号
					String unifiedUserId = sheet.getCell(0, i).getContents();
					String appId = sheet.getCell(5, i).getContents();
					
					// 判断必填项是否全部填写好
					/*int flag = 0;
					for (int j = 0; j < 7; j++) {
						if (sheet.getCell(j, i).getContents() == null
								|| sheet.getCell(j, i).getContents().equals(
										"null")
								|| sheet.getCell(j, i).getContents().equals("")) {
							flag++;
						}
					}*/
					for (int j = 0; j < 7; j++) {
						if (sheet.getCell(j, i).getContents() == null
								|| sheet.getCell(j, i).getContents().equals(
										"null")
								|| sheet.getCell(j, i).getContents().equals("")) {
							if ((j == 0 || j == 1 || j == 2 || j == 3 || j == 5)
									//&& flag != 7
									) {
								Map<String, Object> m = new HashMap<String, Object>();
								data = "第" + (i + 1)
										+ "行必填项未填写，表格不符合条件，请重新校对填写后导入。";
								m.put("VALUE", data);
								jsonObject.putAll(m);
								return "json";
							}
						}
					}

					Map<String, Object> userMap = new HashMap<String, Object>();
					userMap.put("tableName", "UICM_USER");
					userMap.put("USER_ID", unifiedUserId);
					int count1 = userBusiness.listCount_user(userMap);
					if (count1 == 0) {
						Map<String, Object> m = new HashMap<String, Object>();
						data = "第" + (i + 1) + "行的统一用户账号在系统中不存在，请先添加账号后导入。";
						m.put("VALUE", data);
						jsonObject.putAll(m);
						return "json";
					}
					for (int j = 5; j < 6; j++) {
						Map<String, Object> appMap = new HashMap<String, Object>();
						String appid = sheet.getCell(j, i).getContents();
						appMap.put("tableName", "B_T_UFP_APPS");
						appMap.put("APP_ID", appid);
						int count = business.listCount_table(appMap);
						if (count == 0) {
							Map<String, Object> m = new HashMap<String, Object>();
							data = "第" + (i + 1) + "行的应用在映射应用表中不存在，请先添加应用后导入。";
							m.put("VALUE", data);
							jsonObject.putAll(m);
							return "json";
						}

					}
					for (int j = i + 1; j < rows; j++) {
						if (unifiedUserId.equals(sheet.getCell(0, j)
								.getContents())
								&& appId.equals(sheet.getCell(5, j)
										.getContents())) {
							if (!userId.equals(sheet.getCell(2, j)
									.getContents())) {
								Map<String, Object> m = new HashMap<String, Object>();
								data = "统一用户账号"
										+ sheet.getCell(1, j).getContents()
										+ "映射同一系统内的多个账号，表格不符合条件，请重新校对填写后导入。";
								m.put("VALUE", data);
								jsonObject.putAll(m);
								return "json";
							}
						}
					}
				}
				//应用无法匹配错误的文本内容
				StringBuffer appErrorText=new StringBuffer();
				// 遍历每行每列的单元格
				for (int i = 1; i < rows; i++) {
					Map<String, Object> userMap = new HashMap<String, Object>();
					Map<String, Object> mapperMap = new HashMap<String, Object>();
					Map<String, Object> appMap = new HashMap<String, Object>();
					//设置主键id
					userMap.put("UUID", UUID.randomUUID().toString());
					for (int j = 0; j < 7; j++) {
						Cell cell = sheet.getCell(j, i);
						String result = cell.getContents();
						if (result != null && !result.equals("null")
								&& !result.equals("")) {
							switch (j) {
							case 0:// 统一用户账号
								mapperMap.put("USER_ID", result);
								break;
							case 2:// 账号
								userMap.put("USER_ID", result);
								mapperMap.put("USER_SYS_NAME", result);
								break;
							case 3:// 用户名
								userMap.put("USER_NAME", result);
								// mapperMap.put("USER_NAME", result);
								break;
							case 4:// 密码
								userMap.put("USER_PWD", Encipher.EncodePasswd(result));
								// mapperMap.put("USER_PWD", result);
								break;
							case 5:// 应用编码
								Map<String,Object> query=new HashMap<String, Object>();
								query.put("tableName", "B_T_UFP_APPS");
								query.put("APP_ID", result);
								List<Map<String,Object>> list=business.list_table(query);
								if(list.size()>=2){
									appErrorText.append(String.format("第{0}行的应用ID不唯一，请咨询管理员。", i));
								}else if(list.size()==0){
									appErrorText.append(String.format("第{0}行的应用ID不存在，请咨询管理员。", i));
								}else{
									mapperMap.put("YIYONG_ID", list.get(0).get("UUID"));
									userMap.put("APP_ID", list.get(0).get("UUID"));
									userMap.put("UUID", list.get(0).get("UUID"));
									userMap.put("APP_ID", result);
								}
								break;
							case 6:// 应用名称
								// mapperMap.put("YIYONG_NAME", result);
								break;
							default:
								break;
							}
						}
					}
					userMap.put("tableName", "B_T_UFP_MAPPER_USER");
					mapperMap.put("tableName", "C_T_SYS_OTHERLOGIN");
					appMap.put("tableName", "B_T_UFP_APPS");
					List<Map<String, Object>> apps = business
							.list_table(appMap);
					String appUrl = apps.get(0).get("URL").toString();
					// mapperMap.put("URL", appUrl);
					// mapperMap.put("YIYONG_NAME",
					// apps.get(0).get("APP_NAME").toString());
					// 新增
					int count = business.listCount_table(userMap);
					if (count > 0)
						business.update_table(userMap);
					else
						business.insert_table(userMap);
					// 新增
					count = business.listCount_table(mapperMap);
					if (count > 0)
						business.update_table(mapperMap);
					else
						business.insert_table(mapperMap);
				}
				jsonObject.putAll(Status.getStatus(Status.UPDATE_OK));
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				jsonObject.putAll(Status.getStatus(Status.UPDATE_ERR));
			}
			System.out.println("-----------------数据导入结束----------------------");
		}
		return "json";
	}

//	public String mapperdownLoad() {
//		FileUtil fileUtil = new FileUtil();
//		String uploadnew = "ExpMappingUser.xls";
//		String uploadold = "映射导入模板.xls";
//		String uploadpath = request.getSession().getServletContext()
//				.getRealPath("/uploadFile/apps/mappingUser");
//		FileObject baseDir = fileUtil.getFile(uploadpath);
//
//		FileObject file = null;
//		try {
//			file = baseDir.resolveFile(uploadnew);
//		} catch (FileSystemException e) {
//			e.printStackTrace();
//		}
//		try {
//			uploadold = new String(uploadold.getBytes("gbk"), "iso8859-1");
//		} catch (UnsupportedEncodingException e1) {
//			e1.printStackTrace();
//		}
//		this.response.setContentType("application/octet-stream");
//		this.response.addHeader("Content-Disposition",
//				"attachment; filename=\"" + uploadold + "\"");
//
//		fileUtil.download(file, this.response);
//
//		return null;
//	}

	public String download() throws BusinessException{
		String ret_download ="";
    	String uuid = request.getParameter("uuid");
		String uploadnew=request.getParameter("uploadnew");
		String uploadpath=request.getParameter("uploadpath");
		String uploadold=request.getParameter("uploadold");
		if(new File(uploadpath+File.separator+uploadnew).exists()==false){
			uploadpath = request.getSession().getServletContext().getRealPath(uploadpath);
			try {
//				uploadold = new String(uploadold.getBytes("iso8859-1"), "utf-8");
				uploadold = new String((uploadold).getBytes("gbk"),"iso8859-1");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			FileUtil fileUtil = new FileUtil();
			
			//文件存放目录
			FileObject baseDir = fileUtil.getFile(uploadpath);
			
			//获取下载文件
			FileObject file = null;
			try {
				file = baseDir.resolveFile(uploadnew);
			} catch (FileSystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//设置response
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=\""+uploadold+"\"");
			
			//下载，写入response
			fileUtil.download(file, response); 
			
			ret_download =  null;
		}else{
			ret_download = super.download();
		}
		return ret_download;	
	}
	
	/**
	   * 不去掉空值
	   * @param request
	   * @param prefix
	   * @return
	   */
	  public Map<String, Object> getUpdateFieldMapJw(HttpServletRequest request, String prefix)
	  {
	    Map Fields = new HashMap();

	    Enumeration paramNames = request.getParameterNames();
	    while (paramNames.hasMoreElements()) {
	      String paramName = (String)paramNames.nextElement();
	      if ((paramName.indexOf(prefix) != -1) && 
	        (paramName.substring(0, 6).equalsIgnoreCase(prefix))) {
	        String[] paramValues = request.getParameterValues(paramName);
	        if (paramValues.length == 1) {
	          String paramValue = paramValues[0];
	          if (paramValue.length() != 0) {
	            Fields.put(paramName.substring(6), paramValue);
	          }else {
	        	  Fields.put(paramName.substring(6), "");
			}
	        }
	      }
	    }
	    return Fields;
	  }

}
