package com.ced.sip.expert.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.sip.common.BaseDataInfosUtil;
import com.ced.sip.common.DictStatus;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.ExcelUtil;
import com.ced.sip.common.utils.PasswordUtil;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.expert.biz.IExpertBiz;
import com.ced.sip.expert.biz.IExpertMajorBiz;
import com.ced.sip.expert.entity.Expert;
import com.ced.sip.expert.entity.ExpertMajor;
import com.ced.sip.system.biz.IMajorBiz;
import com.ced.sip.system.entity.Major;

public class ExpertAction extends BaseAction {
	
	//专家基本信息表服务类
	private IExpertBiz iExpertBiz;
	
	private IExpertMajorBiz iExpertMajorBiz;
	
	//专业服务类
	private IMajorBiz iMajorBiz  ;
	
	//专家基本信息表实例
	private Expert expert ;
	
	//专家评标专业表实例
	private ExpertMajor expertMajor; 
	
	//专家专业
	private Major major;

	//专家学历Map
	private Map degreeMap;
	
	//专家职称Map
	private Map titleTechMap;
	
	//临时变量
	private String tempExpertMajor;
	/**
	 * 查看专家信息列表
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String viewExpert() throws BaseException {
		
		try{
			
		} catch (Exception e) {
			log.error("查看专家信息列表错误！", e);
			throw new BaseException("查看专家信息列表错误！", e);
		}
		
		return VIEW ;
		
	}
	/**
	 * 查看专家信息列表
	 * @return
	 * @throws BaseException 
	 * @Action
	 */
	public String findExpert() throws BaseException {
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			expert=new Expert();
			String expertName=this.getRequest().getParameter("expertName");
			expert.setExpertName(expertName);
			String expertMajor=this.getRequest().getParameter("expertMajor");
			expert.setExpertMajor(expertMajor);
			String status=this.getRequest().getParameter("status");
			expert.setStatus(status);
			expert.setComId(comId);
			this.setListValue(this.iExpertBiz.getExpertList(this.getRollPageDataTables(), expert));
			this.getPagejsonDataTables(this.getListValue());
		} catch (Exception e) {
			log.error("查看专业信息列表错误！", e);
			throw new BaseException("查看专业信息列表错误！", e);
		}
		
		return null ;
		
	}
	/**
	 * 保存专家信息初始化
	 * @return
	 * @throws BaseException 
	 */
	public String saveExpertInit() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			degreeMap = BaseDataInfosUtil.getDictInfoToMap(DictStatus.COMMON_DICT_TYPE_1706);
			titleTechMap = BaseDataInfosUtil.getDictInfoToMap(DictStatus.COMMON_DICT_TYPE_1704);
			this.getRequest().setAttribute("degreeMap", degreeMap);
			this.getRequest().setAttribute("titleTechMap", titleTechMap);
			this.getRequest().setAttribute("comId", comId);
		} catch (Exception e) {
			log("保存专家信息初始化错误！", e);
			throw new BaseException("保存专家信息初始化错误！", e);
		}
		
		return ADD_INIT;
		
	}
	
	/**
	 * 保存专家信息
	 * @return
	 * @throws BaseException 
	 */
	public String saveExpert() throws BaseException {
		
		try{
			Long comId=UserRightInfoUtil.getComId(getRequest());
			// 保存专家信息
			if (expert!=null) {
				//当前状态中文
				if ("0".equals(expert.getStatus())) {
					expert.setStutusCn("有效");
				}else
				{
					expert.setStutusCn("无效");
				}
				//最后修改时间
				expert.setLastEditTime(DateUtil.getCurrentDateTime());
				//注销时间
				expert.setCancleDate(DateUtil.getCurrentDateTime());
				//登记人
				expert.setWriter(UserRightInfoUtil.getChineseName(this.getRequest()));
				//登记时间
				expert.setWriteDate(DateUtil.getCurrentDateTime());
				//是否有效
				expert.setIsUsable("0");
				
				expert.setExpertPassword(PasswordUtil.encrypt("123456"));
				
				expert.setComId(comId);
				
				this.iExpertBiz.saveExpert(expert);
			
				//保存专家评标专业
				String ids =this.getRequest().getParameter("expertMajorId");
				
				if(StringUtil.isNotBlank(ids)){
					String[] idArr = ids.split(",");
					for(int i=0;i<idArr.length;i++){
						expertMajor = new ExpertMajor();
						Long id = Long.parseLong(idArr[i]);
						expertMajor.setExpertId(expert.getExpertId());
						expertMajor.setEjId(id);
						this.iExpertMajorBiz.saveExpertMajor(expertMajor);
					}
				}
			}
			
			this.getRequest().setAttribute("message", "新增成功");
			this.saveExpertInit();
		} catch (Exception e) {
			log("保存专家信息错误！", e);
			throw new BaseException("保存专家信息错误！", e);
		}
		
		return ADD_INIT;
		
	}
	
	/**
	 * 修改专家信息初始化
	 * @return
	 * @throws BaseException 
	 */
	public String updateExpertInit() throws BaseException {
		
		try{
			degreeMap = BaseDataInfosUtil.getDictInfoToMap(DictStatus.COMMON_DICT_TYPE_1706);
			titleTechMap = BaseDataInfosUtil.getDictInfoToMap(DictStatus.COMMON_DICT_TYPE_1704);
			// 取得专家表信息
			expert = this.iExpertBiz.getExpert(expert.getExpertId());
			
			String expertMajorId="";
			expertMajor=new ExpertMajor();
			expertMajor.setExpertId(expert.getExpertId());
			List<ExpertMajor> list=this.iExpertMajorBiz.getExpertMajorList(expertMajor);
			int i =0;
			for(ExpertMajor expertMajor:list){
				if(i==0) expertMajorId=expertMajor.getEjId()+"";
				else  expertMajorId+=","+expertMajor.getEjId()+"";
				i++;
			}
			this.getRequest().setAttribute("expertMajorId", expertMajorId);
			this.getRequest().setAttribute("degreeMap", degreeMap);
			this.getRequest().setAttribute("titleTechMap", titleTechMap);
		} catch (Exception e) {
			log("修改专家信息初始化错误！", e);
			throw new BaseException("修改专家信息初始化错误！", e);
		}
		
		return MODIFY_INIT;
		
	}
	
	/**
	 * 修改专家信息
	 * @return
	 * @throws BaseException 
	 */
	public String updateExpert() throws BaseException {
		
		try{
			// 修改专家信息
			if (expert!=null) {
				//当前状态中文
				if ("0".equals(expert.getStatus())) {
					expert.setStutusCn("有效");
				}else
				{
					expert.setStutusCn("无效");
				}
				//最后修改时间
				expert.setLastEditTime(DateUtil.getCurrentDateTime());
				//注销时间
				expert.setCancleDate(DateUtil.getCurrentDateTime());
				//登记人
				expert.setWriter(UserRightInfoUtil.getChineseName(this.getRequest()));
				//登记时间
				expert.setWriteDate(DateUtil.getCurrentDateTime());
				//是否有效
				expert.setIsUsable("0");
				
				this.iExpertBiz.updateExpert(expert);
				
				String majorIdUpdate=this.getRequest().getParameter("majorIdUpdate");
				
				if(StringUtil.isNotBlank(majorIdUpdate)){
				
					//*********删除专家评标专业***********//
					
					expertMajor = new ExpertMajor();
					expertMajor.setExpertId(expert.getExpertId());
					List list = this.iExpertMajorBiz.getExpertMajorList(this.getRollPageDataTables(), expertMajor);
						
					for (int i = 0; i < list.size(); i++) {
						ExpertMajor ep = (ExpertMajor) list.get(i);
						String id = ep.getEjId().toString();
						this.iExpertMajorBiz.deleteExpertMajor(id);
					}
						
					//*********保存专家评标专业***********//
					
					String ids = this.getRequest().getParameter("expertMajorId");
					
					if(!ids.equals("")){
						String[] idArr = ids.split(",");
						for(int i=0;i<idArr.length;i++){
							expertMajor = new ExpertMajor();
							Long id = Long.parseLong(idArr[i]);
							expertMajor.setExpertId(expert.getExpertId());
							expertMajor.setEjId(id);
							this.iExpertMajorBiz.saveExpertMajor(expertMajor);
						}
					}
				}
				this.getRequest().setAttribute("message", "修改成功");
				this.updateExpertInit();
			}
		} catch (Exception e) {
			log("修改专家信息错误！", e);
			throw new BaseException("修改专家信息错误！", e);
		}
		
		return MODIFY_INIT;
		
	}
	
	/**
	 * 删除专家信息
	 * @return
	 * @throws BaseException 
	 */
	public String deleteExpert() throws BaseException {
		
		try{
			PrintWriter out = this.getResponse().getWriter();
			String ids =this.getRequest().getParameter("ids");
			
			if(ids!=null){
			String[] idArr = ids.split(",");
				for(int i=0;i<idArr.length;i++){
					Long id = Long.parseLong(idArr[i]);
					expert = this.iExpertBiz.getExpert(id);
					expert.setIsUsable("1");
					this.iExpertBiz.updateExpert(expert);
				}
			}
			String message="删除成功";
  			out.print(message);
		} catch (Exception e) {
			log("删除专家信息错误！", e);
			throw new BaseException("删除专家信息错误！", e);
		}
		return null;
		
	}
	
	/**
	 * 查看专家明细信息
	 * Ushine 2014-11-11
	 * @return
	 * @throws BaseException
	 */
	public String viewExpertDetail() throws BaseException {
		
		try{
			expert = this.iExpertBiz.getExpert(expert.getExpertId());
			expert.setDegreeCn(BaseDataInfosUtil.convertDictCodeToName(expert.getDegree(), DictStatus.COMMON_DICT_TYPE_1706));
			expert.setTitleTechCn(BaseDataInfosUtil.convertDictCodeToName(expert.getTitleTech(), DictStatus.COMMON_DICT_TYPE_1704));
		} catch (Exception e) {
			log("查看专家明细信息错误！", e);
			throw new BaseException("查看专家明细信息错误！", e);
		}
		return DETAIL;
		
	}
	
	/**
	 * 导出EXCEL
	 * Ushine 2014-11-11
	 * @return
	 * @throws BaseException
	 */
	public void exportExpertExcel() throws BaseException {
		
		try {
			List<String> titleList = new ArrayList<String>();
			 titleList.add("专家姓名");
			 titleList.add("专家性别");
			 titleList.add("系统内外");
			 titleList.add("专家类型");
			 titleList.add("专家专业");
			 titleList.add("状态");
			List list = this.iExpertBiz.getExpertList(expert); // 获取数据集合,非分页
			List<Object[]> objList = new ArrayList<Object[]>();
			for (int i = 0; i < list.size(); i++) {
				Expert expert = (Expert) list.get(i);
				expert.setExpertSex(expert.getExpertSex()=="0"?"男":"女");
				expert.setInOut(expert.getInOut()=="0"?"系统内":"系统内");
				expert.setExpertType(expert.getExpertType()=="0"?"正式":"临时");
				expert.setStatus(expert.getStatus()=="0"?"有效":"无效");
				Object[] obj = new Object[] { expert.getExpertName(),
						expert.getExpertSex(), expert.getInOut(),
						expert.getExpertType(),
						expert.getExpertMajor(), expert.getStatus() };
				objList.add(obj);
			}
			// 输出的excel文件名
			String file = "专家信息.xls";
			String targetfile = this.getServletContext().getRealPath(file);

			
			// 输出的excel文件工作表名
			List<Map<String,Object>> excelList=new ArrayList<Map<String,Object>>();
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("worksheet", "专家信息");
			map.put("titleList", titleList);
			map.put("valueList", objList);
			excelList.add(map);
			// 调用JXL方法
			new ExcelUtil().expCommonExcel(targetfile, excelList);
			this.getResponse().setContentType("application/octet-stream; charset=utf-8");
			this.getResponse().setHeader("Content-Disposition", "attachment; filename="+new String(file.getBytes("gbk"),"iso-8859-1") );
			//this.getResponse().setHeader( "Set-Cookie", "name=value; HttpOnly"); 
			File files = new File(targetfile);
			FileInputStream is = new FileInputStream(files);
			OutputStream os = this.getResponse().getOutputStream();
			byte[] buff = new byte[1024];
			int readCount = 0;
			int i = 0;
			readCount = is.read(buff);
			while (readCount != -1) {
				os.write(buff, 0, readCount);
				readCount = is.read(buff);
			}
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		} catch (Exception e) {
			log("导出专家信息错误！", e);
			throw new BaseException("导出专家信息错误！", e);
		}
		
	}	
	/**
	 * 选择专业信息
	 * @return
	 * @throws BaseException
	 */
	public String viewMajorWindow() throws BaseException{
		String ul=this.getRequest().getParameter("ul");
		this.getRequest().setAttribute("ul", ul);
		return "majorIndex";
	}
	/**
	 * 专业树
	 * @return
	 * @throws BaseException
	 */
	public String viewMajorWithTree() throws BaseException{
		try {
			Long comId=UserRightInfoUtil.getComId(getRequest());
			String id = this.getRequest().getParameter("id");
			if(StringUtil.isBlank(id)) id="0";
			major=new Major();
			major.setParentId(Long.parseLong(id));
			major.setComId(comId);
			List<Major> mjList = this.iMajorBiz.getMajorList(major);
			JSONArray jsonArray = new JSONArray();
			for (Major mj:mjList) {
				JSONObject subJsonObject = new JSONObject();
				subJsonObject.element("id", mj.getMjId());
				subJsonObject.element("pid", mj.getParentId());
				subJsonObject.element("name",mj.getMjName());
				
				if("0".equals(mj.getIsHaveChild()))
				{
					subJsonObject.element("isParent", true);
					
				}
				
				jsonArray.add(subJsonObject);
			}
			PrintWriter writer = getResponse().getWriter();  
			//System.out.println(jsonArray);
	        writer.print(jsonArray);  
	        writer.flush();  
	        writer.close(); 
	        
		} catch (Exception e) {
			log.error("选择品类树错误！", e);
			throw new BaseException("选择品类树错误！", e);
		}
		return null;
		
	}
	
	public IExpertBiz getiExpertBiz() {
		return iExpertBiz;
	}
	public void setiExpertBiz(IExpertBiz iExpertBiz) {
		this.iExpertBiz = iExpertBiz;
	}
	public IMajorBiz getiMajorBiz() {
		return iMajorBiz;
	}
	public void setiMajorBiz(IMajorBiz iMajorBiz) {
		this.iMajorBiz = iMajorBiz;
	}
	public Expert getExpert() {
		return expert;
	}

	public void setExpert(Expert expert) {
		this.expert = expert;
	}
	public String getTempExpertMajor() {
		return tempExpertMajor;
	}
	public void setTempExpertMajor(String tempExpertMajor) {
		this.tempExpertMajor = tempExpertMajor;
	}
	public ExpertMajor getExpertMajor() {
		return expertMajor;
	}
	public void setExpertMajor(ExpertMajor expertMajor) {
		this.expertMajor = expertMajor;
	}
	public IExpertMajorBiz getiExpertMajorBiz() {
		return iExpertMajorBiz;
	}
	public void setiExpertMajorBiz(IExpertMajorBiz iExpertMajorBiz) {
		this.iExpertMajorBiz = iExpertMajorBiz;
	}
	
}
