/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:project
 * File Name:MetadataController.java
 * Package Name:ccpit.base.metadataManage
 * Date:2015年9月25日上午10:24:53
 * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
 *
*/

package org.ccpit.base.metadataManage;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.user.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * ClassName:MetadataController <br/>
 * Function: TODO 数据字典管理控制类. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2015年9月25日 上午10:24:53 <br/>
 * @author   dingwei
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
@Controller
@RequestMapping("/admin/metadataManage")
public class MetadataController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(MetadataController.class);
	@Autowired
	private MetadataService metadataService;
	/*
	 * 进入机构管理列表界面
	 */
	@RequestMapping("/goinMetadataListPage")
	public Object goinOrgListPage() {
		ModelAndView mv = new ModelAndView("admin/metadataManage/metadataListPage");
		return mv;
	}
	
	@RequestMapping("/getAllMetadatas")
    @ResponseBody
    public Object getAllMetadatas(HttpServletRequest request){
        PageRequest pageRequest = getPage(request);
        String dataType = request.getParameter("dataType");
        String dataName = request.getParameter("dataName");
        StringBuffer hql = new StringBuffer("from Metadata where 1=1");
        if(null != dataName && null != dataType){
        	if(null != dataName && !"".equals(dataName)){
        		hql.append(" and dataName like '%"+ dataName +"%'");
        	}
        	if(null != dataType && !"".equals(dataType)){
        		hql.append(" and dataType ='"+ dataType +"'");
        	}
        }
        hql.append(" order by createDate desc");
        Page<Metadata> pageRole = metadataService.queryPage(pageRequest,hql.toString());
        return metadataService.convert(pageRole);
    }

	@RequestMapping("/addOrUpdateMetadata")
	@ResponseBody
	public Object addOrUpdateMetadata(HttpServletRequest request,HttpServletResponse response, Metadata metadata) {
		Map map = new HashMap();
		User user = (User) request.getSession().getAttribute("user_in_session");
		String metadataId = request.getParameter("metadataId");
		String languageType = request.getParameter("languageType");
		//判断操作类别  新增或修改
		String operate = request.getParameter("operate");
		metadata.setLanguageType(languageType);
		if ("add".equals(operate)) {
			metadata.setCreateDate(new Date());
			metadata.setCreator(user.getUsername());
			metadata.setCreatorId(user.getId());
			metadataService.addMetadata(metadata);
			map.put("flag", true);
			map.put("info", "信息保存成功！");
		}else if("edit".equals(operate)) {
			Metadata metadata1 = metadataService.getMetadataById(Long.valueOf(metadataId));
			if(null != metadata.getDataName()){
				metadata1.setDataName(metadata.getDataName());
			}
			if(null != metadata.getDataType()){
				metadata1.setDataType(metadata.getDataType());
			}
			if(null != metadata.getDataLevel()){
				metadata1.setDataLevel(metadata.getDataLevel());
			}
			if(null != metadata.getDescription()){
				metadata1.setDescription(metadata.getDescription());
			}
			if(null != metadata.getDataNameId()){
				metadata1.setDataNameId(metadata.getDataNameId());
			}
			if(null != metadata.getLanguageType()){
				metadata1.setLanguageType(metadata.getLanguageType());
			}
			metadataService.updateMetadata(metadata1);
			map.put("flag", true);
			map.put("info", "信息保存成功！");
		}else {
			map.put("flag", false);
		}
		return map;
	}

	/**
	 * 根据id删除
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/deleteMetadata")
	@ResponseBody
	public Object deleteMetadata(HttpServletRequest request){
		Map result = new HashMap();
		String jsonIds = request.getParameter("ids");
		JSONArray jsonArray = JSONArray.fromObject(jsonIds);
		Object[] ids = jsonArray.toArray();
		boolean flag = false;
		for(Object metadataId : ids){
			flag = metadataService.delMetadata((Integer)metadataId);
		}
		result.put("flag", flag);
		return result;
	}

	@RequestMapping("/queryMetadataById")
	@ResponseBody
	public Object queryMetadataById(HttpServletRequest request) {
		String metadataId = request.getParameter("metadataId");
		Metadata metadata = metadataService.getMetadataById(Long.valueOf(metadataId));
		return metadata;
	}
	
	@RequestMapping("/getMetadatasList")
	@ResponseBody
	public Object getMetadatasList(HttpServletRequest request){
		String dataType = request.getParameter("dataType"); 
		String hql = "";
		List<Metadata> listBo = new ArrayList<Metadata>();
		try {
			if(null != dataType){
				dataType = java.net.URLDecoder.decode(dataType, "UTF-8");
				String[] dt = dataType.split(",");
				if(dt.length<=1){
					hql = "from Metadata where dataType ='"+ dataType +"'";
					listBo = metadataService.getAllMetadatas(hql);
				}else {
					for(int i=0;i<dt.length;i++){
						hql = "from Metadata where dataType ='"+ dt[i] +"'";
						List<Metadata> mList = metadataService.getAllMetadatas(hql);
						for(Metadata m : mList){
							listBo.add(m);
						}
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		List list = new ArrayList();
		if(null != listBo){
			for(int i=0;i<listBo.size();i++){
				Map result = new HashMap();
				result.put("id", listBo.get(i).getDataNameId());
				result.put("text", listBo.get(i).getDataName());
				list.add(result);
			}
		}
		return list;
	}
	
	@RequestMapping("/getMetadatasList_front")
	@ResponseBody
	public Object getMetadatasList_front(HttpServletRequest request){
		String dataType = request.getParameter("dataType"); 
		try {
			if(null != dataType){
				dataType = java.net.URLDecoder.decode(dataType, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String hql = "from Metadata where dataType ='"+ dataType +"'";
		List<Metadata> listBo = metadataService.getAllMetadatas(hql);
		List list = new ArrayList();
		if(null != listBo){
			for(int i=0;i<listBo.size();i++){
				Map result = new HashMap();
				result.put("id", listBo.get(i).getDataNameId());
				result.put("text", listBo.get(i).getDataName());
				list.add(result);
			}
		}
		request.setAttribute("industrySmall", list);
		Map map = new HashMap();
		map.put("industrySmall", list);
		return map;
	}
	
	@RequestMapping("/getMetadatasIdList")
	@ResponseBody
	public Object getMetadatasIdList(HttpServletRequest request){
		String dataType = request.getParameter("dataType"); 
		try {
			if(null != dataType){
				dataType = java.net.URLDecoder.decode(dataType, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String hql = "from Metadata where dataType ='"+ dataType +"'";
		List<Metadata> listBo = metadataService.getAllMetadatas(hql);
		List list = new ArrayList();
		if(null != listBo){
			for(int i=0;i<listBo.size();i++){
				Map result = new HashMap();
				result.put("id", listBo.get(i).getId());
				result.put("text", listBo.get(i).getDataName());
				list.add(result);
			}
		}
		return list;
	}
	
	@RequestMapping("/getMetadatasListAll")
	@ResponseBody
	public Object getMetadatasListAll(HttpServletRequest request){
		String dataLevel = request.getParameter("dataLevel");
		int level = 0;
		String hql = "";
		if("all".equals(dataLevel)){
			hql = "from Metadata where dataLevel between 0 and 3";
		}else {
			if(null != dataLevel){
				level = Integer.valueOf(dataLevel) - 1;
			}
			hql = "from Metadata where dataLevel ="  + level;
		}
		List<Metadata> listBo = metadataService.getAllMetadatas(hql);
		List list = new ArrayList();
		if(null != listBo){
			for(int i=0;i<listBo.size();i++){
				Map result = new HashMap();
				result.put("id", listBo.get(i).getDataNameId());
				result.put("text", listBo.get(i).getDataName());
				list.add(result);
			}
		} 
		return list;
	}
	
	/**
	 * 导入excel
	 */
	@RequestMapping("/importExcel")
	@ResponseBody
	public void importExcel(HttpServletRequest request,HttpServletResponse response){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String result = "";
		String fileName = "";
		InputStream is = null;
		boolean flag = false;
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user_in_session");
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();  
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(request);
			for(FileItem item : items){
				String type = item.getContentType();
				 if(type == null) {
					 continue;
				 }
				 //文件参数
				 fileName = item.getName(); 
				 String fileFormat = fileName.split("[.]")[1];
				 if("xls".equals(fileFormat) || "xlsx".equals(fileFormat)){
					 is = item.getInputStream();
				 }
			}
			XSSFWorkbook hSSFWorkbook = new XSSFWorkbook(is);
			List<Metadata> infosList = new ArrayList<Metadata>();
			Metadata metadata = null;
			//得到第一个工作表   
            XSSFSheet sheet = hSSFWorkbook.getSheetAt(0);  
            XSSFRow row = null;
            if(null != user){
            	//遍历该表格中所有的工作表，i表示工作表的数量 getNumberOfSheets表示工作表的总数
                for(int i=0; i<hSSFWorkbook.getNumberOfSheets();i++){
                	sheet = hSSFWorkbook.getSheetAt(i);
                	//遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数
                	for(int j=0; j<sheet.getPhysicalNumberOfRows()-1;j++){
                		row = sheet.getRow(j+1);
                		metadata = new Metadata();
                		if(null != row){
                			if(null != row.getCell(0)){
                				if("".equals(row.getCell(0).toString())){
                					System.out.println("第"+j+"行数据为空----");
                				}
                				metadata.setDataLevel(Integer.valueOf(row.getCell(0).toString()));
                			}if(null != row.getCell(1)){
                				metadata.setDataType(row.getCell(1).toString());
                			}if(null != row.getCell(2)){
                				metadata.setDataName(row.getCell(2).toString());
                			}if(null != row.getCell(3)){
                				metadata.setDataNameId(row.getCell(3).toString());
                			}
                			metadata.setCreator(user.getUsername());
                			metadata.setCreateDate(new Date());
                			if(null != row.getCell(1) && !"".equals(row.getCell(1).toString().trim())){
                				infosList.add(metadata);
                			}
                		}
                	}
                }
                for(Metadata metadata1 : infosList){
                	flag = metadataService.addMetadata(metadata1);
                }
                if(flag){
        			result = "{ \"flag\": "+ flag  +", \"info\": \"数据导入成功！\" }";
        		}else {
        			result = "{ \"flag\": "+ flag  +", \"info\": \"数据导入失败！\" }";
        		}
            }else {
            	result = "{ \"flag\": "+ false  +", \"info\": \"用户登录信息失效，请重新登录...\" }";
            }
		} catch (FileNotFoundException e) {
			log.debug("导入数据字典文件失败，找不到文件...");
		} catch (IOException e) {
			log.debug("导入数据字典文件失败，io异常...");
		} catch (FileUploadException e) {
			log.debug("导入数据字典文件失败，找不到文件...");
		}
		try { 
			response.setContentType("text/html");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
} 

