package cn.com.countrygarden.bi.main.service.personnel.impl;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.dup.MediaResources;
import cn.com.countrygarden.bi.main.model.test.Test;
import cn.com.countrygarden.bi.main.service.project.ProjectJointPlanService;
import cn.com.countrygarden.bi.main.service.test.TestService;
import sun.security.rsa.RSAPadding;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.google.common.primitives.Ints;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.sys.Function;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.com.countrygarden.bi.main.model.personnel.Personnel;
import cn.com.countrygarden.bi.main.model.personnel.PersonnelCampusevaluation;
import cn.com.countrygarden.bi.main.model.personnel.PersonnelTag;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelAdvisorMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelCampusevaluationMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelTagMapper;
import cn.com.countrygarden.bi.main.dto.PersonInfoVO;
import cn.com.countrygarden.bi.main.dto.PersonnelCampusDTO;
import cn.com.countrygarden.bi.main.dto.PersonnelCampusevaluationDTO;
import cn.com.countrygarden.bi.main.dto.PersonnelTgDTO;
import cn.com.countrygarden.bi.main.dto.personnelTagDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelCampusevaluationService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelCommenService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
import cn.com.countrygarden.bi.main.core.Response;

/**
 * 校园评测-业务逻辑层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2018-09-20
 */
@Service
@Transactional
public class PersonnelCampusevaluationServiceImpl implements PersonnelCampusevaluationService{
    @Autowired
    private PersonnelCampusevaluationMapper personnelCampusevaluationMapper;
    
    @Autowired
    private PersonnelAdvisorMapper personnelAdvisorMapper;
    
    @Autowired
    private PersonnelMapper personnelMapper;
    
    @Autowired
    private PersonnelTagMapper personnelTagMapper;
    
    @Autowired
    private PersonnelCommenService personnelCommenService;
    
    @Override
	public Result percamlist(PersonnelCampusevaluationDTO percam, int page, int size,AccessToken accessToken) {
    	
//    	List<String> userIds= personnelCommenService.findRole(accessToken);
//		if(userIds!=null) {
//			if(userIds.size()==0||userIds.get(0).equals("-1")) {
//				//没有匹配的角色或没有查找到数据
//				return Response.response();
//			}		
//		}
    	
    	Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());    	
    	List<String> userquyu=new ArrayList<>();
    	List<DupOrgan> result=null;
    	for (Object obj : rolesMap.keySet()) {
    		String key = (String) obj;
    		if (key.equals("gj_admin")) {
    			 userquyu=null;
    			 rolesMap.put("identitys", null);
    			 break;
    		}else if (key.equals("role")) {
    			return null;
			}else if (key.equals("gj_Area")) {
//				List<String> liuserquyu=personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
//				userquyu=liuserquyu.get(0);
				rolesMap.put("identitys", null);
				
				result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
				for (int i = 0; i < result.size(); i++) {
					userquyu.add(result.get(i).getOrganName());
				}
			}
    		
    	}
//    	List<PersonnelCampusevaluationDTO> dtoper=new ArrayList<PersonnelCampusevaluationDTO>();
//    	Page<Object> pageList=PageHelper.startPage(page, size);
//    	if (result!=null&&result.size()!=0) {
//    		for (int i = 0; i < result.size(); i++) {
//    			
//    			List<PersonnelCampusevaluationDTO> persapper=personnelCampusevaluationMapper.percamlist(percam,rolesMap,result.get(i).getOrganName());
//    			if (persapper.size()!=0) {
//    				dtoper.addAll(persapper);
//				}    		
//    		}
//		}else {
//			
//			dtoper = personnelCampusevaluationMapper.percamlist(percam,rolesMap,null);
//		}
    	if (percam.getUserId()!=null&&!percam.getUserId().equals("")&&percam.getName()!=null&&!percam.getName().equals("")&&
    			percam.getRegionName()!=null&&!percam.getRegionName().equals("")&&percam.getIdentity()!=null&&!percam.getIdentity().equals("")&&
    			percam.getMatchinglevel()!=null&&!percam.getMatchinglevel().equals("")) {
    		userquyu=null;
		}
    	Page<Object> pageList=PageHelper.startPage(page, size);
    	List<PersonnelCampusevaluationDTO> percamlist= personnelCampusevaluationMapper.percamlist(percam,rolesMap,userquyu);
    	  
    	  PageData data=new PageData(pageList);
          data.setData(pageList.getResult());
          return Response.response(data);
	}


    @Override
    public Result queryPageList(PersonnelCampusevaluation personnelCampusevaluation, int page, int size,AccessToken accessToken) {
    	
    	

    	
    	
        Page<Object> pageList = PageHelper.startPage(page, size);
        Condition condition=new Condition(PersonnelCampusevaluation.class);
        Criteria criteria = condition.createCriteria();
        
		personnelCampusevaluationMapper.selectByCondition(condition);
        PageData data=new PageData(pageList);
        data.setData(pageList.getResult());
        return Response.response(data);
    }

    @Override
    public Result queryById(Integer id) {
    	
        return Response.response(personnelCampusevaluationMapper.perone(id));
    }

    @Override
    public Result add(PersonnelCampusevaluationDTO personnelCampu, AccessToken accessToken) {
    	   
    	//System.out.println(personnelCampu.getAdditionTime());
    	DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //HH表示24小时制；
//    	Date dateAdditionTime=null;
//    	try {
//			 dateAdditionTime=dFormat.parse(personnelCampu.getAdditionTime());
//		} catch (ParseException e) {		
//			e.printStackTrace();
//		}
    	PersonnelCampusevaluationDTO perdto=personnelCampusevaluationMapper.addone(personnelCampu.getUserId(), personnelCampu.getPersonneltagId());
    	        if (perdto==null) {
    	        	PersonnelCampusevaluation perelCampuln=new PersonnelCampusevaluation();
        			perelCampuln.setPersonnelId(personnelCampu.getPersonnelId());
        			perelCampuln.setPersonneltagId(personnelCampu.getPersonneltagId());
        			perelCampuln.setMatchinglevel(personnelCampu.getMatchinglevel());
        			perelCampuln.setFlag(0);
        			//perelCampuln.setAdditionTime(dateAdditionTime);
        			perelCampuln.setCreatedDate(new Date());
        			perelCampuln.setFiles(personnelCampu.getFiles());
        			perelCampuln.setFilesame(personnelCampu.getFilesame());
        			perelCampuln.setCreatedName(personnelCampu.getCreatedName());
        			perelCampuln.setCreatedBy(accessToken.getUserCode());
        	        personnelCampusevaluationMapper.insertSelective(perelCampuln);
		       }else {
		    	   PersonnelCampusDTO personn=new PersonnelCampusDTO();
		    	   personn.setId(personnelCampu.getId());
		    	   personn.setFiles(personnelCampu.getFiles());
		    	   personn.setFilesame(personnelCampu.getFilesame());
		    	   personn.setMatchinglevel(personnelCampu.getMatchinglevel());
		    	   personn.setUpdatedBy(accessToken.getUserCode());
		    	   personn.setUpdatedDate(new Date());
		           personnelCampusevaluationMapper.editpeca(personn);
			   }
    			
    		
		
    	
        return Response.response();
    }

    @Override
    public Result edit(PersonnelCampusDTO personnelCampusevaluation, AccessToken accessToken) {
    	
    	
    	personnelCampusevaluation.setUpdatedBy(accessToken.getUserCode());
    	personnelCampusevaluation.setUpdatedDate(new Date());
        personnelCampusevaluationMapper.editpeca(personnelCampusevaluation);
        return Response.response();
    }

    @Override
    public Result del(Integer id) {
        //int count = personnelCampusevaluationMapper.deleteByPrimaryKey(id);
    	
    	int count = personnelCampusevaluationMapper.delupdate(id);
        return Response.response(count);
    }



	@Override
	public Result excelToxls(Integer radio,MultipartFile multipartFile,String fileName,String usname,String userCode,AccessToken accessToken) {
		//List<String> liuserquyu=personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
		 Workbook xwb = null;
       BufferedInputStream bf = null;
       Sheet sheet = null;
       try {
      	 CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
           bf = new BufferedInputStream(commonsMultipartFile.getInputStream());
           //String fileName = commonsMultipartFile.getOriginalFilename();
           if (fileName.endsWith("xls")) { // Excel&nbsp;2003
               xwb = new HSSFWorkbook(bf);
           } else if (fileName.endsWith("xlsx")) { // Excel 2007/2010
               xwb = new XSSFWorkbook(bf);
           }
           sheet = xwb.getSheetAt(0);//获取第几个页面0开始
           Row row =null;
           Personnel personnel=null;
           PersonnelTag personnelTag=null;
           PersonnelCampusevaluation personnelCampusevaluation=null;
           XSSFCell cell;
           for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {        	   
        	        row = sheet.getRow(i+3);
        	        if(row==null) {
		            	   break;
		             }
        	         
        		   for(int j =0;j<sheet.getRow(i+1).getPhysicalNumberOfCells();j++) {
        			  
        			    cell = (XSSFCell) row.getCell(0);
        			    if(StringUtils.isBlank(cell.toString())) {
	        	    		   break;
	        	    	   }
        			   cell.setCellType(CellType.STRING);
        			   
        			   String urid=cell.getStringCellValue();
        			   
        			   cell = (XSSFCell) row.getCell(1);
        			   cell.setCellType(CellType.STRING);
        			   String name=cell.getStringCellValue();
        			   
        			   cell = (XSSFCell) row.getCell(2);
        			   cell.setCellType(CellType.STRING);
        			   String identity=cell.getStringCellValue();
        			   
        			   cell = (XSSFCell) row.getCell(3);
        			   cell.setCellType(CellType.STRING);
        			   String mathin=cell.getStringCellValue();
        			   
//        			   List<String> userIds= personnelCommenService.findRole(accessToken);
//        				if(userIds!=null) {
//        					if(userIds.size()==0||userIds.get(0).equals("-1")) {
//        						//没有匹配的角色或没有查找到数据
//        						//continue;
//        						//return Response.response();
//        						throw new ServiceException("没有权限添加");
//        					}		
//        				}
        				//Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());
//        			   String userquyu=liuserquyu.get(0);
//        			   String findboolean=personnelCommenService.findboolean(accessToken,urid,null,userquyu);
//                      
//        			   if (findboolean.equals("role")) {                	
//        				   throw new ServiceException("添加此用户编号："+urid+",权限不足，请检查确认好再导入");                   
//          			
//   				       }else if (findboolean.equals("gj_admin")) {
//   				    	   userquyu=null; 
//					   }else if (findboolean.equals("gj_Area")) {
//						   userquyu=liuserquyu.get(0);
//					    }else if (personnelCommenService.findboolean(accessToken,null,identity,null).equals("identitys")) {
//						   userquyu=null; 
//						  
//					    }
        			   
        			   Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());    	
        		    	//String userquyu=null;
        		    	List<String> userquyu= new ArrayList<>();
        		    	
        		    	List<DupOrgan> result=null;
        		    	for (Object obj : rolesMap.keySet()) {
        		    		String key = (String) obj;
        		    		if (key.equals("gj_admin")) {
        		    			 List<PersonInfoVO> personInfoCodeOrId=personnelAdvisorMapper.selectByPersonInfoByCodeOrName(urid,null,null);
        		    			 if (personInfoCodeOrId.size()==0) {
                        				throw new ServiceException("用户编号" + personnel.getUserId() + "有误或权限不足，无法添加");
     							}
        		    			 rolesMap.put("identitys", null);
        		    			 break;
        		    		}else if (key.equals("role")) {
        		    			throw new ServiceException("当前账号权限不足，请检查确认好再导入"); 
        					}else if (key.equals("gj_Area")) {
        						rolesMap.put("identitys", null);
        						
        						 result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
        						for (int q = 0; q < result.size(); q++) {
        							userquyu.add(result.get(q).getOrganName());
        						}
        						 List<PersonInfoVO> personInfoCodeOrId=personnelAdvisorMapper.selectByPersonInfoByCodeOrName(urid,null,userquyu);   
        						 if (personInfoCodeOrId.size()==0) {
        							 throw new ServiceException("用户编号" +urid + "有误或权限不足，无法添加");
        						 }
        						
        					}
        		    		
        		    	}
        		 
        			   List<PersonnelTgDTO> personneltag=personnelCampusevaluationMapper.personneltag(urid,identity);
        			   Personnel perone=personnelMapper.perone(urid);
        			   PersonnelCampusevaluationDTO personnelCampus=personnelCampusevaluationMapper.percamlione(urid,identity);
        			  
        			          if (radio==0) {
        			        	  
        			        	  if(personneltag.size()==0) {
        			        		  throw new ServiceException("第"+(i+4)+"行"+"用户编号："+row.getCell(0).getStringCellValue()+"的标签"+ row.getCell(2).getStringCellValue()+",不存在,请检查确认好再导入");
        			        	  }
        			        	  personnelTag=new PersonnelTag();
          					      personnelTag.setId(personneltag.get(0).getPersonneltagId());
//        			        	  if(personneltag.size()>0) {
//               					   personnelTag=new PersonnelTag();
//               					   personnelTag.setId(personneltag.get(0).getPersonneltagId());
//        			        	  }else {
//        			        		  personnelTag=new PersonnelTag();
//                  				       personnelTag.setUserId(urid);
//                  				       personnelTag.setIdentity(identity);
//                  				       personnelTag.setCreatedBy(userCode);            				       
//                  				       personnelTagMapper.insertSelective(personnelTag);
//								  }
//                   			   
//                   				   if(perone==null){
//                   					   personnel=new Personnel();
//                       				   personnel.setUserId(urid);
//                       				   personnel.setName(personInfoCodeOrId.get(0).getName());
//                       				   personnel.setCreatedBy(userCode);               				  
//                       				   personnelMapper.insertSelective(personnel);                       				                         				 
//                   				   }
                   				   
                   				if(personnelCampus==null) {
             					   personnelCampusevaluation=new PersonnelCampusevaluation();
             					   if(perone!=null) {
             						   personnelCampusevaluation.setPersonnelId(perone.getId());
             					   }
             					   
//             					   else {
//             						   personnelCampusevaluation.setPersonnelId(personnel.getId());
//     							   }
             					  
             					   personnelCampusevaluation.setPersonneltagId(personnelTag.getId());
             					   personnelCampusevaluation.setMatchinglevel(mathin);
             					   personnelCampusevaluation.setFlag(0);
             					   personnelCampusevaluation.setCreatedName(usname);
             					   personnelCampusevaluation.setCreatedBy(userCode);
             					   personnelCampusevaluationMapper.insertSelective(personnelCampusevaluation);
             					   
             				   }
                   				                         			     
					           }else if (radio==1) {
					        	   if(personneltag.size()==0) {
	        			        		  throw new ServiceException("第"+(i+4)+"行"+"用户编号："+row.getCell(0).getStringCellValue()+"的标签"+ row.getCell(2).getStringCellValue()+",不存在,请检查确认好再导入");
	        			        	  }
					        	   personnelTag=new PersonnelTag();
	        					   personnelTag.setId(personneltag.get(0).getPersonneltagId());
//					        	   if(personneltag.size()>0) {
//		        					   personnelTag=new PersonnelTag();
//		        					   personnelTag.setId(personneltag.get(0).getPersonneltagId());
//		            			     }else {
//		            			    	 personnelTag=new PersonnelTag();
//		            				       personnelTag.setUserId(urid);
//		            				       personnelTag.setIdentity(identity);
//		            				       personnelTag.setCreatedBy(userCode);            				       
//		            				       personnelTagMapper.insertSelective(personnelTag);
//									}   
//		            				   if(perone==null){
//		            					   personnel=new Personnel();
//		                				   personnel.setUserId(urid);
//		                				   personnel.setName(personInfoCodeOrId.get(0).getName());
//		                				   personnel.setCreatedBy(userCode);               				  
//		                				   personnelMapper.insertSelective(personnel);
//		                				   
//		                			
//		            				   }
		            				       
		            			   
		        				   if(personnelCampus==null) {
		        					   personnelCampusevaluation=new PersonnelCampusevaluation();
		        					   if(perone!=null) {
		        						   personnelCampusevaluation.setPersonnelId(perone.getId());
		        					   }
		        					   
//		        					   else {
//		        						   personnelCampusevaluation.setPersonnelId(personnel.getId());
//									   }
		        					  
		        					   personnelCampusevaluation.setPersonneltagId(personnelTag.getId());
		        					   personnelCampusevaluation.setMatchinglevel(mathin);
		        					   personnelCampusevaluation.setFlag(0);
		        					   personnelCampusevaluation.setCreatedName(usname);
		        					   personnelCampusevaluation.setCreatedBy(userCode);
		        					   personnelCampusevaluationMapper.insertSelective(personnelCampusevaluation);
		        					   
		        				   }else {
		        					   personnelCampusevaluation=new PersonnelCampusevaluation();
		        					   personnelCampusevaluation.setId(personnelCampus.getId());
		        					   personnelCampusevaluation.setPersonnelId(perone.getId());
		        					   personnelCampusevaluation.setPersonneltagId(personnelTag.getId());
		        					   personnelCampusevaluation.setMatchinglevel(mathin);
		        					   personnelCampusevaluation.setUpdatedBy(userCode);
		        					   personnelCampusevaluation.setUpdatedDate(new Date());
		        					   personnelCampusevaluationMapper.edit(personnelCampusevaluation);
								   }					        	   								
							}        			          			           			   			           			
   				    j+=3;        	   				
        		   }
           }
           return Response.response("导入成功");
       } catch (IOException e1) {
           e1.printStackTrace();
           throw new ServiceException("导入失败！请稍后重试！");
       }
		
	}


	@Override
	public Result personInfoCodeOrId(String search) {
		List<PersonInfoVO> personInfoCodeOrId=personnelCampusevaluationMapper.personInfoCodeOrId(search);
		 List<String> result=new LinkedList<>();
		 for (PersonInfoVO psndoc : personInfoCodeOrId) {
			 result.add(psndoc.getId()+" - "+psndoc.getCode()+" - "+psndoc.getName());
		}
		
		 return Response.response(result);
	}


	@Override
	public Result queryadByUid(String search,AccessToken accessToken) {
//		List<String> userIds= personnelCommenService.findRole(accessToken);
//		if(userIds!=null) {
//			if(userIds.size()==0||userIds.get(0).equals("-1")) {
//				//没有匹配的角色或没有查找到数据
//				return Response.response();
//			}		
//		}
		Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());
        List<String> userquyu=new ArrayList<>();
        List<DupOrgan> resuaslt=null;
    	for (Object obj : rolesMap.keySet()) {
    		String key = (String) obj;
    		if (key.equals("gj_admin")) {
    			 userquyu=null;    			
    			 break;
    		}else if (key.equals("role")) {
    			return null;
			}else if (key.equals("gj_Area")) {
//				List<String> liuserquyu=personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
//				userquyu=liuserquyu.get(0);
				resuaslt = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
				for (int i = 0; i < resuaslt.size(); i++) {
					userquyu.add(resuaslt.get(i).getOrganName());
				}
			}
    		
    	}
    	
//    	List<PersonInfoVO> dtoper=new ArrayList<PersonInfoVO>();
//    	if (resuaslt!=null&&resuaslt.size()!=0) {
//    		for (int i = 0; i < resuaslt.size(); i++) {
//    			List<PersonInfoVO> persapper=personnelCampusevaluationMapper.selectByPersonInfoByCodeOrName(search,rolesMap,resuaslt.get(i).getOrganName());
//    				dtoper.addAll(persapper);
//				}    		
//    		}else {
//			dtoper = personnelCampusevaluationMapper.selectByPersonInfoByCodeOrName(search,rolesMap,null);
//		}

		List<PersonInfoVO> personInfoCodeOrId=personnelCampusevaluationMapper.selectByPersonInfoByCodeOrName(search,rolesMap,userquyu);
		 List<String> result=new LinkedList<>();
		 for (PersonInfoVO psndoc : personInfoCodeOrId) {
			 result.add(psndoc.getCode()+" - "+psndoc.getWorkdept()+" - "+psndoc.getName());
		}
		
		 return Response.response(result);
	}


	@Override
	public Result personneltag(String userId,String identity) {
		 List<PersonnelTgDTO> perseltag=personnelCampusevaluationMapper.personneltag(userId,identity);
		return Response.response(perseltag);
	}


	@Override
	public Result addone(String userId,Integer personneltagId) {
		PersonnelCampusevaluationDTO addone=personnelCampusevaluationMapper.addone(userId,personneltagId);
		return Response.response(addone);
	}


	@Override
	public Result delpiliang(String perid) {
//		String[] idIntegers;
//		int[] idArry = null;
//		if (perid!=null&&!perid.equals("")) {
//			idIntegers=perid.split(",");
//		    idArry = new int[idIntegers.length];
//		    for (int i = 0; i < idIntegers.length; i++) {
//		    	idArry[i]=Integer.parseInt(idIntegers[i]);
//			}
//
//		}
		//List<Integer> id=new ArrayList<>();
		List<String> peronid = JSONArray.parseArray(perid, String.class);
//		for (int i = 0; i < peronid.size(); i++) {
//			id.add(Integer.parseInt(peronid.get(i)));
//		}
		
		personnelCampusevaluationMapper.delupdatepiliang(peronid);
		
		
		return Response.response("删除成功");
	}

	
}