package com.hhx.manage.controller.yiqi;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.hhx.manage.common.ExeclUtils;
import com.hhx.manage.common.MD5;
import com.hhx.manage.common.Pager;
import com.hhx.manage.common.QueryModel;
import com.hhx.manage.domain.CollegesUser;
import com.hhx.manage.domain.DeclareType;
import com.hhx.manage.domain.Education;
import com.hhx.manage.domain.ExpertUser;
import com.hhx.manage.domain.Industry;
import com.hhx.manage.domain.JobTitle;
import com.hhx.manage.domain.LimitDate;
import com.hhx.manage.domain.Origin;
import com.hhx.manage.domain.Region;
import com.hhx.manage.domain.Territory;
import com.hhx.manage.dto.ExpertUserDTO;
import com.hhx.manage.page.PageResult;
import com.hhx.manage.service.DeclareTypeService;
import com.hhx.manage.service.EducationService;
import com.hhx.manage.service.ExpertUserService;
import com.hhx.manage.service.IndustryService;
import com.hhx.manage.service.JobTitleService;
import com.hhx.manage.service.LimitDateService;
import com.hhx.manage.service.MajorService;
import com.hhx.manage.service.OriginService;
import com.hhx.manage.service.ProAssiginDetailService;
import com.hhx.manage.service.RegionService;
import com.hhx.manage.service.TerritoryService;

@Controller
@RequestMapping("expert")
public class ExpertUserController {

	@Resource
	private ExpertUserService expertUserService; //专家用户
	@Resource
	private JobTitleService jobTitleService; //职称
	@Resource
	private EducationService educationService; //学历
	@Resource
	private OriginService originService; //专家来源
	@Resource
	private RegionService regionService; //地区
	@Resource
	private IndustryService industryService; //行业
	@Resource
	private TerritoryService territoryService; //研究领域
	@Resource
	private DeclareTypeService declareTypeService; //申报类型
	@Resource
	ProAssiginDetailService proAssiginDetailService;
	@Resource
	private LimitDateService limitDateService;
	@Resource
	private MajorService majorService;
	
	@RequestMapping("")
	public String index(Model model){
		List<JobTitle> jobTitles = jobTitleService.queryList(null, null).getRecords();
		List<Education> educations = educationService.queryList(null, null).getRecords();
		List<Origin> origins = originService.queryList(null, null).getRecords();
		List<Region> regions = regionService.queryList(null, null).getRecords();
		List<Industry> industrys = industryService.queryList(null, null).getRecords();
		List<Territory> territorys = territoryService.queryList(null, null).getRecords();
		List<DeclareType> declareTypes = declareTypeService.queryList(null, null).getRecords();
		model.addAttribute("jobTitles", jobTitles);
		model.addAttribute("educations", educations);
		model.addAttribute("origins", origins);
		model.addAttribute("regions", regions);
		model.addAttribute("industrys", industrys);
		model.addAttribute("territorys", territorys);
		model.addAttribute("declareTypes", declareTypes);
		return "expert/index";
	}
	
	@ResponseBody
	@RequestMapping("page")
	public Pager<ExpertUserDTO> page(ExpertUser user, Pager<ExpertUserDTO> page, HttpSession session,
			                         @RequestParam(value="columnIndex",required=false) Integer columnIndex,
			                         @RequestParam(value="sortOrder",required=false) String sortOrder,
			                         @RequestParam(value="opType",required=false) String opType,
			                         @RequestParam(value="sort_rows",required=false) Integer sort_rows,
			                         @RequestParam(value="sort_pageOffset",required=false) Integer sort_pageOffset){
		Integer type = (Integer) session.getAttribute("loginType");
		if(type != null && type == 2){
			CollegesUser collegesUser = (CollegesUser) session.getAttribute("loginUser");
			user.setCollegesId(collegesUser.getId());
		}
		long now=new Date().getTime();
		if(null!=opType&&(now-Long.valueOf(opType))/1000<1){
			page.setPageOffset(sort_pageOffset-1);
			page.setRows(sort_rows);
			page.setOrder(sortOrder);
			user.setIsSort("sort");
			setSortColumn(page,columnIndex);
		}
		Pager<ExpertUserDTO> result=expertUserService.queryList(user, page);
		
		return  result;
	}
	
	private void setSortColumn(Pager<ExpertUserDTO> pager,Integer columnIndex){
		
		switch (columnIndex) {
		case 3:
			pager.setSort("eu.username");
			break;
        case 4:
        	pager.setSort("eu.name");
			break;
        case 5:
        	pager.setSort("eu.sex");
			break;
        case 6:
        	pager.setSort("eu.position");
			break;
        case 7:
        	pager.setSort("eu.audit_status");
			break;
        case 8:
        	pager.setSort("cu.name");
			break;
        case 9:
        	pager.setSort("eu.research_area");
			break;
		default:
			pager.setSort("eu.create_time");
			break;
		}
		
	}
	
	@RequestMapping("list")
	public ModelAndView list(@ModelAttribute QueryModel.ExportQueryModel query,
			                 @RequestParam(value="code",required=false) String code,
			                 @RequestParam(value="type",required=false) String type){
		
		List<JobTitle> jobTitles = jobTitleService.queryList(null, null).getRecords();
		List<DeclareType> declareTypes = declareTypeService.queryList(null, null).getRecords();
		ModelAndView mav=new ModelAndView("/expert/list");
		if(null!=code&&!"".equals(code)&&null!=type&&"link".equals(type)){
			query.setCollegeCode(code);
		}
		mav.addObject("query",query);
		mav.addObject("jobTitles", jobTitles);
		mav.addObject("declareTypes", declareTypes);
		mav.addObject("pageSize", query.getPageSize());
		mav.addObject("pageIndex", query.getPageIndex());
		query.setPageIndex((query.getPageIndex()-1)*query.getPageSize());
		PageResult<ExpertUserDTO> pageResult=expertUserService.queryListDTOByParam(query);		
		mav.addObject("totalCount", pageResult.getTotalCount());
		mav.addObject("expertUsers", pageResult);
		return mav;
	}
	
	@RequestMapping("score/list")
	public ModelAndView scoreList(){
		ModelAndView mav=new ModelAndView("/expert/score/list");
		mav.addObject("pageSize", 300);
		mav.addObject("pageIndex", 1);
		mav.addObject("totalCount",0);
		return mav;
	}

	@ResponseBody
	@RequestMapping("add")
	public int add(ExpertUser user, HttpServletRequest request) {
		HttpSession session = request.getSession();
		Integer loginType = (Integer) session.getAttribute("loginType");
		String code = "";
		if (loginType != null && loginType == 2) {
			CollegesUser loginUser = (CollegesUser) session.getAttribute("loginUser");
			if(loginUser != null){
				user.setCollegesId(loginUser.getId());
				code = loginUser.getCode();
			} else {
				return 1;
			}
		} else {
			return 2;
		}
		ExpertUser para = new ExpertUser();
		para.setIdCard(user.getIdCard());
		int count = expertUserService.queryCount(para);
		if(count > 0){
			return 3; //身份证号重复
		}
		String pwd = MD5.encipher("123456");
		user.setPassword(pwd);
		user.setAuditStatus(3);
		expertUserService.add(user, code);
		return 0;
	}
	
	@RequestMapping("editPage")
	public String editPage(Model model, Integer id){
		List<JobTitle> jobTitles = jobTitleService.queryList(null, null).getRecords();
		List<Education> educations = educationService.queryList(null, null).getRecords();
		List<Origin> origins = originService.queryList(null, null).getRecords();
		List<Region> regions = regionService.queryList(null, null).getRecords();
		List<Industry> industrys = industryService.queryList(null, null).getRecords();
		List<Territory> territorys = territoryService.queryList(null, null).getRecords();
		List<DeclareType> declareTypes = declareTypeService.queryList(null, null).getRecords();
		model.addAttribute("jobTitles", jobTitles);
		model.addAttribute("educations", educations);
		model.addAttribute("origins", origins);
		model.addAttribute("regions", regions);
		model.addAttribute("industrys", industrys);
		model.addAttribute("territorys", territorys);
		model.addAttribute("declareTypes", declareTypes);
		if(id == null){
			model.addAttribute("user", null);
		} else {
			model.addAttribute("user", expertUserService.queryById(id));
		}
		return "expert/edit";
	}
	
	@RequestMapping("conciseEdit")
	public String conciseEdit(Model model, Integer id){
		List<DeclareType> declareTypes = declareTypeService.queryList(null, null).getRecords();
		model.addAttribute("declareTypes", declareTypes);
		if(id == null){
			model.addAttribute("user", null);
		} else {
			model.addAttribute("user", expertUserService.queryById(id));
		}
		return "expert/conciseEdit";
	}
	
	@ResponseBody
	@RequestMapping("edit")
	public int edit(ExpertUser user){
		ExpertUser byId = expertUserService.queryById(user.getId());
		if(byId.getIdCard() == null || (byId.getIdCard() != null && !byId.getIdCard().equals(user.getIdCard()))){
			ExpertUser para = new ExpertUser();
			para.setIdCard(user.getIdCard());
			int count = expertUserService.queryCount(para);
			if(count > 0){
				return 3; //身份证号重复
			}
		}
		expertUserService.update(user);
		return 0;
	}
	
	@ResponseBody
	@RequestMapping("del")
	public boolean del(Integer id){
		expertUserService.delete(id);
		return true;
	}
	
	@ResponseBody
	@RequestMapping("batchDel")
	public boolean batchDel(Integer[] ids){
		if(ids != null){
			for (int i = 0; i < ids.length; i++) {
				expertUserService.delete(ids[i]);
			}
		}
		return true;
	}
	
	@ResponseBody
	@RequestMapping("audit")
	public boolean audit(Integer[] ids, int auditStatus, String auditOpinion){
		if(ids != null){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ids", ids);
			map.put("auditStatus", auditStatus);
			map.put("auditOpinion", auditOpinion);
			expertUserService.audit(map);
		}
		return true;
	}
	
	@ResponseBody
	@RequestMapping("get")
	public ExpertUser get(Integer id){
		return expertUserService.queryById(id);
	}
	
	@RequestMapping("show")
	public String show(Model model, Integer id){
//		List<JobTitle> jobTitles = jobTitleService.queryList(null, null).getRecords();
//		List<Education> educations = educationService.queryList(null, null).getRecords();
//		List<Origin> origins = originService.queryList(null, null).getRecords();
//		List<Region> regions = regionService.queryList(null, null).getRecords();
//		List<Industry> industrys = industryService.queryList(null, null).getRecords();
//		List<Territory> territorys = territoryService.queryList(null, null).getRecords();
//		List<DeclareType> declareTypes = declareTypeService.queryList(null, null).getRecords();
//		model.addAttribute("jobTitles", jobTitles);
//		model.addAttribute("educations", educations);
//		model.addAttribute("origins", origins);
//		model.addAttribute("regions", regions);
//		model.addAttribute("industrys", industrys);
//		model.addAttribute("territorys", territorys);
//		model.addAttribute("declareTypes", declareTypes);
		if(id == null){
			model.addAttribute("user", null);
		} else {
			model.addAttribute("user", expertUserService.queryDTOById(id));
		}
		return "expert/show";
	}
	
	@ResponseBody
	@RequestMapping("uppwd")
	public int uppwd(String oldPwd, String pwd, HttpServletRequest request){
		HttpSession session = request.getSession();
		ExpertUser expertUser = (ExpertUser) session.getAttribute("loginUser");
		if(expertUser != null && expertUser.getPassword().equals(MD5.encipher(oldPwd))){
			expertUser.setPassword(MD5.encipher(pwd));
			expertUserService.update(expertUser);
			session.setAttribute("loginUser", expertUser);
			return 0;
		} else {
			return 1;
		}
	}
	
	@ResponseBody
	@RequestMapping("toload")
	public int toload(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException, Exception{
		CollegesUser logUser = (CollegesUser) session.getAttribute("loginUser");
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		if("xls".equals(suffix) || "xlsx".equals(suffix)){
			List<String[]> rows = ExeclUtils.readExecl(file.getInputStream(), 3);
			ExpertUser user = new ExpertUser();
			for (int i = 0; i < rows.size(); i++) {
				ExpertUser para = new ExpertUser();
				para.setIdCard(rows.get(i)[1]);
				int count = expertUserService.queryCount(para);
				if(count > 0){
					continue; //身份证号重复，跳过此次添加
				}
				user.setCollegesId(logUser.getId());
				user.setName(rows.get(i)[0]);
				user.setIdCard(rows.get(i)[1]);
				user.setDeclareTypeId(Integer.parseInt(rows.get(i)[2]));
				String pwd = MD5.encipher("123456");
				user.setPassword(pwd);
				user.setAuditStatus(3);
				expertUserService.add(user, logUser.getCode());
			}
		} else {
			return 1; //文件类型不对
		}
		return 0;
	}
	
	@RequestMapping("view")
	public String view(Model model, Integer e, HttpSession session){
		if(e != null){
			model.addAttribute("isShow", false);
			model.addAttribute("user", expertUserService.queryDTOById(e));
		} else {
			Integer type = (Integer) session.getAttribute("loginType");
			if(type != null && type == 3){
				ExpertUser expertUser = (ExpertUser) session.getAttribute("loginUser");
				model.addAttribute("isShow", true);
				model.addAttribute("user", expertUserService.queryDTOById(expertUser.getId()));
				 Map<String,String> param=new HashMap<>();
	       	     param.put("username", expertUser.getUsername());
	       	     Map<String,String> certInfo=majorService.queryCertificateByParam(param);
	       	     if(!CollectionUtils.isEmpty(certInfo)){
	       	    	model.addAttribute("isHire", certInfo);
	       	     }
			}
		}
		return "expert/view";
	}
	
	@RequestMapping("download")
	public void download(HttpServletResponse response, HttpSession session) throws IOException{
		CollegesUser logUser = (CollegesUser) session.getAttribute("loginUser"); 
		response.setCharacterEncoding("UTF-8");
		//1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
        response.setContentType("multipart/form-data");  
        //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)  
        response.setHeader("Content-Disposition", "attachment;fileName="+"file.xlsx");  
        OutputStream os = response.getOutputStream();
        expertUserService.createExecl(logUser.getId(), os);
//		byte[] b = new byte[2048];
//		int length;
//		while ((length = in.read(b)) > 0) {
//			os.write(b, 0, length);
//		}
		os.close();
	}
	
	@RequestMapping("download1")
	public void download1(HttpServletResponse response, HttpSession session) throws IOException{
		CollegesUser logUser = (CollegesUser) session.getAttribute("loginUser"); 
		response.setCharacterEncoding("UTF-8");
		//1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		response.setContentType("multipart/form-data");  
		//2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)  
		response.setHeader("Content-Disposition", "attachment;fileName="+new String(("【"+logUser.getName()+"】专家信息列表").getBytes("gb2312"), "ISO8859-1" )+".xlsx"); 
		OutputStream os = response.getOutputStream();
		expertUserService.createExecl(logUser.getId(), os);
//		byte[] b = new byte[2048];
//		int length;
//		while ((length = in.read(b)) > 0) {
//			os.write(b, 0, length);
//		}
		os.close();
	}

	@RequestMapping("export")
	public void export(ExpertUser param, HttpServletResponse response, HttpSession session) throws IOException{
		response.setCharacterEncoding("UTF-8");
		//1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		response.setContentType("multipart/form-data");  
		//2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)  
		response.setHeader("Content-Disposition", "attachment;fileName="+"export.xlsx");  
		OutputStream os = response.getOutputStream();
		expertUserService.export(param, os);
//		byte[] b = new byte[2048];
//		int length;
//		while ((length = in.read(b)) > 0) {
//			os.write(b, 0, length);
//		}
		os.close();
	}
	
	@RequestMapping("scoreView")
	public ModelAndView scoreView(@RequestParam(value="pageIndex",required=false) Integer pageIndex,
			                      @RequestParam(value="pageSize",required=false) Integer pageSize,
			                      HttpServletRequest request){
		ModelAndView mav=new ModelAndView("/expert/scoreView");
		if(null==pageIndex){
			pageIndex=1;
		}
		if(null==pageSize){
			pageSize=300;
		}
		mav.addObject("pageIndex", pageIndex);
		mav.addObject("pageSize", pageSize);
		ExpertUser user=(ExpertUser) request.getSession().getAttribute("loginUser");
		int expId=user.getId();
		PageResult<Map<String,Object>> pageResult=proAssiginDetailService.getNeedScoreProByExpId(expId, pageIndex, pageSize);
		List<Map<String,Object>> list=pageResult.getItems();
		String btnShow="NO";
		if(!CollectionUtils.isEmpty(list)){
			for(Map<String,Object> map:list){
				if(null==map.get("is_sure")||"0".equals(map.get("is_sure").toString())){
					btnShow="YES";
					break;
				}
			}
		}
		mav.addObject("btnShow", btnShow);
		mav.addObject("totalCount", pageResult.getTotalCount());
		mav.addObject("scoreProDataList", pageResult.getItems());
		LimitDate limitDate=limitDateService.queryLimitDateById(3);
		mav.addObject("canScore", limitDate.isLimit()?"NO":"YES");
		mav.addObject("scoreSummaryInfo", proAssiginDetailService.getExpertAccountProSummaryInfo(expId));
		return mav;
	}
	
	@RequestMapping("doScore")
	@ResponseBody
	public Object doScore(@RequestParam(value="score") Double score,@RequestParam(value="proId") Long proId,@RequestParam("type") Integer type,HttpServletRequest request){
		
		Map<String, Object> param=new HashMap<>();
		param.put("proId", proId);
		param.put("score", score);
		param.put("type", type);
		ExpertUser user=(ExpertUser) request.getSession().getAttribute("loginUser");
		int expId=user.getId();
		param.put("expId", expId);
		try{
			proAssiginDetailService.insertScoreForProByExp(param);
			param.clear();
			param.put("success", true);
		}catch(Exception e){
			param.put("success", false);
			param.put("message", e.getMessage());
		}
      return param;		
	}
	
	@ResponseBody
	@RequestMapping("getScanResult")
	public Object getScanResult(HttpServletRequest request){
		Map<String, Object> param=new HashMap<>();
		try{
			StringBuilder html=new StringBuilder();
			Map<Double,Integer> checkMap=new HashMap<>();
			Map<Double,Boolean> firstCheckMap=new HashMap<>();
			ExpertUser user=(ExpertUser) request.getSession().getAttribute("loginUser");
			PageResult<Map<String,Object>> pageResult=proAssiginDetailService.getNeedScoreProByExpId(user.getId(), 1, 3000);
			boolean disabled=false;
			if(null!=pageResult&&!CollectionUtils.isEmpty(pageResult.getItems())){
				pageResult.getItems().forEach(map->{
					Double score=0d;
					if(null!=map.get("score")){
						score=Double.valueOf(map.get("score").toString());
					}
					if(checkMap.containsKey(score)){
						int time=checkMap.get(score);
						checkMap.put(score, time+1);
					}else{
						checkMap.put(score, 1);
					}
				});
				for(Map<String,Object> map:pageResult.getItems()){
					Double score=0d;
					if(null!=map.get("score")){
						score=Double.valueOf(map.get("score").toString());
					}
					if(!disabled&&null!=checkMap.get(score)){
						int time=checkMap.get(score);
						if(time>1){
							disabled=true;
						}
					}
					boolean red=false;
					if(null!=checkMap.get(score)){
						int time=checkMap.get(score);
						if(time>1){
							if(firstCheckMap.containsKey(score)){
								firstCheckMap.put(score, false);
							}else{
								firstCheckMap.put(score, true);
							}
							red=!firstCheckMap.get(score);
						}
					}
				    Object realScore=map.get("score");
				    if(realScore==null){
				    	disabled=true; 
				    }
					html.append("<tr").append((null==realScore||red)?"  style='background-color: red;'":"").append(">")
								       .append("<td>")
								           .append(map.get("proId"))
								       .append("</td>")
								       .append("<td>")
								           .append(map.get("proName"))
								        .append("</td>")
								        .append("<td>")
								           .append(map.get("schoolGroup"))
								        .append("</td>")
								        .append("<td>")
								           .append(null!=realScore?realScore:"")
								        .append("</td>")
					    .append("</tr>");			        
				}
			}
			param.put("success", true);
			param.put("result", html.toString());
			param.put("disabled", disabled);
		}catch(Exception e){
			param.put("success", false);
			param.put("message", e.getMessage());
		}
		return param;
	}
}
