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.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.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

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

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.PersonnelAdvisor;
import cn.com.countrygarden.bi.main.model.personnel.PersonnelAssessmentemporary;
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.PersonnelAssessmentemporaryMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelCampusevaluationMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelMapper;
import cn.com.countrygarden.bi.main.dto.PersonInfoVO;
import cn.com.countrygarden.bi.main.dto.PersonnelAdvisorDTO;
import cn.com.countrygarden.bi.main.dto.PersonnelTgDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelAssessmentemporaryService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelCommenService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;
import cn.com.countrygarden.bi.main.core.Response;

/**
 * 270评估导入临时表-业务逻辑层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2018-11-21
 */
@Service
public class PersonnelAssessmentemporaryServiceImpl implements PersonnelAssessmentemporaryService{
    @Autowired
    private PersonnelAssessmentemporaryMapper personnelAssessmentemporaryMapper;
    
    @Autowired
    private PersonnelCommenService personnelCommenService;
    
    @Autowired
    private PersonnelCampusevaluationMapper personnelCampusevaluationMapper;
    
    @Autowired
    private PersonnelAdvisorMapper personnelAdvisorMapper;

    @Override
    public Result queryPageList(PersonnelAssessmentemporary personnelAssessmentemporary, int page, int size) {
        Page<Object> pageList = PageHelper.startPage(page, size);
        Condition condition=new Condition(PersonnelAssessmentemporary.class);
        Criteria criteria = condition.createCriteria();
//		TODO 添加条件
		personnelAssessmentemporaryMapper.selectByCondition(condition);
        PageData data=new PageData(pageList);
        data.setData(pageList.getResult());
        return Response.response(data);
    }

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

    @Override
    public Result add(PersonnelAssessmentemporary personnelAssessmentemporary, AccessToken accessToken) {
        personnelAssessmentemporaryMapper.insert(personnelAssessmentemporary);
        return Response.response();
    }

    @Override
    public Result edit(PersonnelAssessmentemporary personnelAssessmentemporary, AccessToken accessToken) {
        personnelAssessmentemporaryMapper.updateByPrimaryKey(personnelAssessmentemporary);
        return Response.response();
    }

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

	@Override
	public Result excelToxls(MultipartFile multipartFile, String fileName, String usname, String userCode,
			AccessToken accessToken) {
    	

		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;
	           Row rowpe =null;
	          	           
	           XSSFCell cell;
	                  
	           SimpleDateFormat dFormat = new SimpleDateFormat("yyyy/MM/dd");
	       	   Date dAdditionTime=null;
	       	  
	       	   
	       	     personnelAssessmentemporaryMapper.delcreatedby(userCode);
	           for (int a = 0; a < sheet.getPhysicalNumberOfRows(); a++) { 
	        	   rowpe = sheet.getRow(a+3);
	        	       if(rowpe==null) {
	            	        break;
	                   }
	        	       for(int b =0;b<sheet.getRow(a+1).getPhysicalNumberOfCells();b++) {
	        	    	   cell = (XSSFCell) rowpe.getCell(0);
	        	    	   if(StringUtils.isBlank(cell.toString())) {
	        	    		   break;
	        	    	   }
	        			   cell.setCellType(CellType.STRING);	        			   
	        			   String urid=cell.getStringCellValue();
	        			   
	        			   cell = (XSSFCell) rowpe.getCell(1);
	        			   cell.setCellType(CellType.STRING);	        			   
	        			   String name=cell.getStringCellValue();
	        			   
	        			   
	        			   cell = (XSSFCell) rowpe.getCell(2);
	        			   cell.setCellType(CellType.STRING);	        			   
	        			   String identity=cell.getStringCellValue();
	        			   
	        			   cell = (XSSFCell) rowpe.getCell(3);
	        			   //cell.setCellType(CellType.STRING);	        			   
//	        			   String additionTime=cell.getStringCellValue();
	        			   
	        			   cell = (XSSFCell) rowpe.getCell(4);
	        			   cell.setCellType(CellType.STRING);	        		   
	        			   String gradename=cell.getStringCellValue();
	        			   
	        			   cell = (XSSFCell) rowpe.getCell(5);
	        			   cell.setCellType(CellType.STRING);	        		   
	        			   String rjname=cell.getStringCellValue();
	        			   
	        			   cell = (XSSFCell) rowpe.getCell(6);
	        			   cell.setCellType(CellType.STRING);	        		   
	        			   String tel=cell.getStringCellValue();
	        			   
	        			   
	        			  /* List<String> userIds= personnelCommenService.findRole(accessToken);
	        				if(userIds!=null) {
	        					if(userIds.size()==0||userIds.get(0).equals("-1")) {
	        						throw new ServiceException("没有权限添加");
	        						//没有匹配的角色或没有查找到数据
	        						//return Response.response();
	        						//throw new ServiceException("第"+(a+3)+"行"+"用户编号："+rowpe.getCell(0).getStringCellValue()+",没有权限添加");	       
	        					}		
	        				}
	        				
*/
	        			  // 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+",权限不足，请检查确认好再导入");             
//		         			
//		  				 }
//	                  	 
//	                  	 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());
	                       List<String> userquyu=new ArrayList<>();
	                      
	                       List<PersonInfoVO> persono=null;
	        			   List<DupOrgan> result=null;
	                      	for (Object obj : rolesMap.keySet()) {
	                      		String key = (String) obj;
	                      		if (key.equals("gj_admin")) {
	                      			userquyu=null;
	                      			 	persono=personnelAdvisorMapper.selectByPersonInfoByCodeOrName(urid,null,null);
	                      			 if (persono.size()==0) {
	                      				throw new ServiceException("用户编号："+urid+",有误或权限不足，无法添加");	       
									}
	                      			 rolesMap.put("identitys", null);
	                      			 break;
	                      		}else if (key.equals("role")) {
	                      			throw new ServiceException("当前账号权限不足，请检查确认好再导入");                
	                  			}else if (key.equals("gj_Area")) {
	                  				
	                  				result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
	                  				for (int i = 0; i < result.size(); i++) {
	            						userquyu.add(result.get(i).getOrganName());
	            					}
	                  				persono=personnelAdvisorMapper.selectByPersonInfoByCodeOrName(urid,null,userquyu);
	                  				if (persono.size()==0) {
	                      				throw new ServiceException("用户编号："+urid+",有误或权限不足，无法添加");	       
									}
	                  				
	                  			}
	                      		
	                      	}
	                  	 
	        			   List<PersonnelTgDTO> personneltag=personnelCampusevaluationMapper.personneltag(urid,identity);
	        			   
	        			   if(personneltag.size()==0) {
	        				   throw new ServiceException("第"+(a+4)+"行"+"用户编号："+rowpe.getCell(0).getStringCellValue()+"的标签"+ rowpe.getCell(2).getStringCellValue()+",不存在,请检查确认好再导入");
	        			   }
	        			   
	        			   try {
	        					 dAdditionTime=dFormat.parse(getDate((XSSFCell) rowpe.getCell(3)));
	        					
	        				} catch (ParseException e) {
	        					throw new ServiceException("第" + (a+4) + "行时间格式不符合规范，导入失败,请按(yyyy/MM/dd)方式填写日期，或者把xlsx单元格设置日期类型");
	        					//e.printStackTrace();
	        				}
	        			   
	        			   
	        			   PersonnelAssessmentemporary perassessmenteary=new PersonnelAssessmentemporary();
	        			   
	       			       perassessmenteary.setUserId(urid);
	       			       perassessmenteary.setUserName(persono.get(0).getName());
	       			       perassessmenteary.setIdentity(identity);
	       			       if (gradename.equals("上级")) {
	       			    	perassessmenteary.setGradeId(1);
						   }else if (gradename.equals("同级")) {
							   perassessmenteary.setGradeId(2);
						   }else if (gradename.equals("下级")) {
							   perassessmenteary.setGradeId(3);
						   }
	       			       perassessmenteary.setName(rjname);
	       			       perassessmenteary.setTel(tel);
	       			       perassessmenteary.setCreatedBy(userCode);
	       			       perassessmenteary.setCreatedDate(new Date());
	       			       personnelAssessmentemporaryMapper.insertSelective(perassessmenteary);
	        			   b+=6; 	       
	        	       }
	           }
	           return Response.response("导入成功");
	       }catch (IOException e1) {
                 e1.printStackTrace();
                  throw new ServiceException("导入失败！请稍后重试！");
        }
	}
	
	private String getDate(XSSFCell cell) {
		DecimalFormat df = new DecimalFormat("#");
		if (cell == null) {
			return "";
		}
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

				return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
			}
			return df.format(cell.getNumericCellValue());
		case HSSFCell.CELL_TYPE_STRING:
			return cell.getStringCellValue();
		case HSSFCell.CELL_TYPE_FORMULA:
			return cell.getCellFormula();
		case HSSFCell.CELL_TYPE_BLANK:
			return "";

		}
		return "";

	}

	@Override
	public Result listemporary(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;
    			 rolesMap.put("identitys", null);
    			 break;
    		}else if (key.equals("role")) {
    			 return null;
			}else if (key.equals("gj_Area")) {
				rolesMap.put("identitys", null);
				
				 resuaslt = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
				 for (int i = 0; i < resuaslt.size(); i++) {
						userquyu.add(resuaslt.get(i).getOrganName());
					}
			}
    		
    	}
    	
//    	List<PersonnelAssessmentemporary> dtoper=new ArrayList<PersonnelAssessmentemporary>();
//    	if (resuaslt!=null&&resuaslt.size()!=0) {
//    		for (int i = 0; i < resuaslt.size(); i++) {
//    			List<PersonnelAssessmentemporary> persapper=personnelAssessmentemporaryMapper.listemporaryper(search,rolesMap,resuaslt.get(i).getOrganName());
//    				dtoper.addAll(persapper);
//				}    		
//    		}else {
//			dtoper = personnelAssessmentemporaryMapper.listemporaryper(search,rolesMap,null);
//		}
    	
		List<PersonnelAssessmentemporary> temporary=personnelAssessmentemporaryMapper.listemporaryper(search,rolesMap,userquyu);
		 List<String> result=new LinkedList<>();
		 if (temporary.size()>0) {
			 for (PersonnelAssessmentemporary psndoc : temporary) {
				 result.add(psndoc.getUserId()+" - "+psndoc.getUserName());
			}
		}else {
			
			List<PersonInfoVO> dtoperinfo=new ArrayList<PersonInfoVO>();
	    	if (resuaslt!=null&&resuaslt.size()!=0) {
	    		for (int i = 0; i < resuaslt.size(); i++) {
	    			List<PersonInfoVO> persapper=personnelCampusevaluationMapper.selectByPersonInfoByCodeOrName(search,rolesMap,userquyu);
	    			dtoperinfo.addAll(persapper);
					}    		
	    		}else {
	    			dtoperinfo = personnelCampusevaluationMapper.selectByPersonInfoByCodeOrName(search,rolesMap,null);
			}
			
			
			List<PersonInfoVO> personInfoCodeOrId=new ArrayList<PersonInfoVO>(dtoperinfo);
			 for (PersonInfoVO psndoc : personInfoCodeOrId) {
				 result.add(psndoc.getCode()+" - "+psndoc.getName()+" - "+psndoc.getWorkdept());
			}
		}
		 
		
		 return Response.response(result);
	}

	@Override
	public Result getlist(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<PersonnelAssessmentemporary> temporary=personnelAssessmentemporaryMapper.getlist(search,rolesMap);
		
		
		
		return Response.response(temporary);
	}

}