package cn.com.countrygarden.bi.main.controller.personnel;
import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.google.common.primitives.Ints;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

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

import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.personnel.PersonnelAssessment;
import cn.com.countrygarden.bi.main.model.review.ReviewEvaluate;
import cn.com.countrygarden.bi.main.model.review.ReviewInvestigated;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaire;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelAssessmentMapper;
import cn.com.countrygarden.bi.main.dto.PersonnelAdvisorDTO;
import cn.com.countrygarden.bi.main.dto.PersonnelAssessmentDTO;
import cn.com.countrygarden.bi.main.dto.ReviewInvestigationVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireEditVo;
import cn.com.countrygarden.bi.main.dto.ReviewScoreProblemDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelAssessmentService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelAssessmentemporaryService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelCommenService;

/**
 * 270评估-控制层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2018-10-08
 */
@RestController("PersonnelAssessmentController")
@RequestMapping("/api/personnelAssessment")
public class PersonnelAssessmentController extends BaseController{
    @Autowired
    private PersonnelAssessmentService personnelAssessmentService;
    
    @Autowired
    private PersonnelAssessmentemporaryService personnelAssessmentemporaryService;
    
    @Autowired
    private PersonnelCommenService personnelCommenService;
    
    @Autowired
    private PersonnelAssessmentMapper personnelAssessmentMapper;


    @GetMapping(value = "/list", produces = "application/json;charset=utf-8")
    public Result list(PersonnelAssessmentDTO personnelAssessment,
                       @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                       @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                       HttpServletRequest request){
        return  personnelAssessmentService.queryPageList(personnelAssessment,page,size,getAccessToken(request));
    }

    @GetMapping(value = "/perscoreone", produces = "application/json;charset=utf-8")
    public Result perscoreone(@RequestParam(value = "investigatedId", required = true)Integer investigatedId,
                            HttpServletRequest request){
        return  personnelAssessmentService.perscoreone(investigatedId);
    }

    @PostMapping(value = "/add")
    public Result add(PersonnelAssessment personnelAssessment,
                      HttpServletRequest request){
        return  personnelAssessmentService.add(personnelAssessment,getAccessToken(request));
    }

    @PutMapping(value = "/perscoreedit")
    public Result perscoreedit(PersonnelAssessment personnelAssessment, HttpServletRequest request){
        return  personnelAssessmentService.edit(personnelAssessment,getAccessToken(request));
    }

    @DeleteMapping(value="/del")
    public Result del(@RequestParam(value = "id", required = true)Integer id){
        return  personnelAssessmentService.del(id);
    }
    
    @DeleteMapping(value="/delpiliang")
    public Result delpiliang(@RequestParam(value = "perid", required = true)String perid){
        return  personnelAssessmentService.delpiliang(perid);
    }
    
    @DeleteMapping(value="/delpiliangreid")
    public Result delpiliangreid(@RequestParam(value = "reid", required = true)String reid){
        return  personnelAssessmentService.delpiliangreid(reid);
    }
    
    
    @GetMapping(value = "/scoreproblem", produces = "application/json;charset=utf-8")
    public Result scoreproblem(ReviewScoreProblemDTO scoreproblem,
            HttpServletRequest request) {
    	
    	return personnelAssessmentService.scoreproblem(scoreproblem);
    }
    
    //问卷管理列表
	@GetMapping(value = "/ReviewQuestionnairelistVo", produces = "application/json;charset=utf-8")
	public Result list(@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "id", required = false) Integer id,
			@RequestParam(value = "size", required = false, defaultValue = "10") int size,
			@RequestParam(value = "page", required = false, defaultValue = "1") int page, 
			@RequestParam(value = "investigationmanagementId", required = false) int investigationmanagementId,
			HttpServletRequest request) {
		
		boolean hasRole = hasRole("270admin");
		System.out.println("+++++++++++++++++++++++"+hasRole+"  "+getAccessToken().getUserCode());
       return personnelAssessmentService.ReviewQuestionnairelistVo(id,name,hasRole,page, size,getAccessToken().getUserCode(),investigationmanagementId);
		
	}
	
	// 问卷编辑前返回的数据
	@GetMapping(value = "/questionnaireAndproblem", produces = "application/json;charset=utf-8")
	public Result queryQuestionnaireAndproblemOne(@RequestParam(value = "id", required = true) Integer id,
			HttpServletRequest request) {

		return personnelAssessmentService.queryQuestionnaireAndproblem(id);
	}
	
	 //添加问卷前返回的数据
		@GetMapping(value = "/problemTypeAndProblemClassList", produces = "application/json;charset=utf-8")
		public Result queryProblemTypeAndProblemClassList(
				@RequestParam(value = "investigationmanagementId") int investigationmanagementId) {
			return personnelAssessmentService.queryProblemTypeAndProblemClass(investigationmanagementId);
		}
		
		@PostMapping(value = "/270add")
		public Result addAssessment(ReviewQuestionnaire reviewQuestionnaire,
				@RequestParam(value = "str", required = false) String str,
				@RequestParam(value = "qclassAryNew") String qclassAryNew, HttpServletRequest request) {

			return personnelAssessmentService.addAssessment(reviewQuestionnaire, str, qclassAryNew, getAccessToken(request));

		}
		
	    //问卷及问题逻辑删除
		@GetMapping(value = "/questionnaireParamVoOne", produces = "application/json;charset=utf-8")
		public Result questionnaireParamVoOne(@RequestParam(value = "id", required = true) Integer id,
				HttpServletRequest request) {
			return personnelAssessmentService.questionnaireParamVoOne(id);
		}
		
		// 编辑问题
		@PutMapping(value = "/270edit")
		public Result editAssessment(ReviewQuestionnaireEditVo reviewQuestionnaireEditVo,
				@RequestParam(value = "str", required = false) String str,
				@RequestParam(value = "qclassAryNew") String qclassAryNew, HttpServletRequest request)
				throws ParseException {

			return personnelAssessmentService.editAssessment(reviewQuestionnaireEditVo, str, qclassAryNew,
					getAccessToken(request));
		}
		
		//发起调查
		  @PostMapping(value = "/appAssessment")
		  public Result appAssessment(ReviewInvestigated reviewInvestigated,String upJsonStr,String sameJsonStr,String downJsonStr 
		                    ,HttpServletRequest request){
		  	
		      return  personnelAssessmentService.appAssessment(reviewInvestigated,upJsonStr,sameJsonStr,downJsonStr,getAccessToken(request));
		  }
		  		
		// 调查列表
			@GetMapping(value = "/investigationVoList", produces = "application/json;charset=utf-8")
			public Result InvestigationVoList(ReviewInvestigationVo reviewinvesti,@RequestParam(value = "size", required = false, defaultValue = "10") int size,
					@RequestParam(value = "page", required = false, defaultValue = "1") int page, HttpServletRequest request) {

				boolean haseole=hasRole("270admin");
				return personnelAssessmentService.selectInvestigationVoList(reviewinvesti,haseole,page, size,getAccessToken().getUserCode(),getAccessToken(request));
			}
			
			//短信重发
			@PostMapping(value = "/resendSms")
			public Result resendSms(@RequestParam(value = "investigatedId", required = true) int investigatedId,
					@RequestParam(value = "investigatedName", required = true) String investigatedName,
					@RequestParam(value="questionnaireId", required = true)int questionnaireId,
					@RequestParam(value="questionnaireName", required = true)String questionnaireName
					) {
				
				return personnelAssessmentService.resendSms(investigatedId, investigatedName,questionnaireId,questionnaireName);
			}
			
			//结束调查
			@PutMapping(value = "/270Investigationlistedit")
			public Result investigationlistedit(ReviewInvestigated reviewInvestigated, HttpServletRequest request) {
				return personnelAssessmentService.investigationlistedit(reviewInvestigated, getAccessToken(request));
			}
			
			//答题界面数据
			@GetMapping(value="/getreviewquestionnaireanswer",produces = "application/json;charset=utf-8")
			 public Result investigatedId(@RequestParam int  investigatedId,@RequestParam int reviewJudgeId,@RequestParam int questionnaireId
			    		) {
			    	
			    
			    return personnelAssessmentService.selectAnswerBeforeVo(investigatedId,reviewJudgeId,questionnaireId);
		    }
			
			   @PostMapping(value = "/updataflag")
			    public Result updataflag(@RequestParam(value="id",required=true)Integer id,@RequestParam(value="questionnaireId",required=true)Integer questionnaireId,
			    		@RequestParam(value="judgeId",required=true)Integer judgeId
			    		,HttpServletRequest request) {
			    	
			    	return personnelAssessmentService.updataflag(id, judgeId, questionnaireId);
			    	
			    }
			   //提交分数
			@PostMapping(value = "/addScoreAssessment")
		    public Result addScoreAssessment(String answer,String answenwer,
			                     HttpServletRequest request){
			     
			    return  personnelAssessmentService.addScoreAssessment(answer,answenwer,getAccessToken(request));
			     
			 }  
			
		 @GetMapping(value = "/scoredtos", produces = "application/json;charset=utf-8")
		 public Result scoredtos(@RequestParam(value="investigatedid",required=true)Integer investigatedid,
			    		@RequestParam(value="gradeid",required=true)Integer gradeid,@RequestParam(value="questionnaireId",required=false)Integer questionnaireId,
			            HttpServletRequest request) {
			    	//hasRole(roleCode)
			    	return personnelAssessmentService.scoredtos(investigatedid,gradeid,questionnaireId);
		 }
		 
		 @GetMapping(value = "/scoredtosrj", produces = "application/json;charset=utf-8")
		 public Result scoredtosrj(@RequestParam(value="investigatedid",required=true)Integer investigatedid,
			    		@RequestParam(value="gradeid",required=true)Integer gradeid,@RequestParam(value="questionnaireId",required=false)Integer questionnaireId,
			            HttpServletRequest request) {
			    	//hasRole(roleCode)
			    	return personnelAssessmentService.scoredtosrj(investigatedid,gradeid,questionnaireId);
		 }
		 
		//综合评价
		@GetMapping(value = "/evaluationproblem", produces = "application/json;charset=utf-8")
		public Result evaluationproblem(@RequestParam(value="investigatedid",required=true)Integer investigatedid,
				@RequestParam(value="questionnaireId",required=false)Integer questionnaireId,
		            HttpServletRequest request) {   	    	
		    	
		    	return personnelAssessmentService.evaluationproblem(investigatedid,questionnaireId);
		}
		
		 @PostMapping(value = "/evaluateadd")
		    public Result evaluateadd(ReviewEvaluate reviewEvaluate,
		                      HttpServletRequest request){

		        return  personnelAssessmentService.evaluateadd(reviewEvaluate,getAccessToken(request));
		 }
		 
		 @PutMapping(value = "/updateedit")
		 public Result updateedit(ReviewEvaluate rewet,HttpServletRequest request){
		    	 return  personnelAssessmentService.updateedit(rewet,getAccessToken(request));
		    	
		       
		}
		 
		 //答题问题导出数据
		    @RequestMapping(value = "/evaluationproblemexport", produces = "multipart/form-data",  method = RequestMethod.GET)
		    public void evaluationproblemexport(@RequestParam(value="investigatedid",required=true)Integer investigatedid, 
		    		@RequestParam(value="questionnaireId",required=true)Integer questionnaireId,
		    		@RequestParam(value="investigationmanagementId",required=false)Integer investigationmanagementId,
		    		HttpServletRequest request, HttpServletResponse response) throws ParseException {
		    	
		    	Workbook workbook = new XSSFWorkbook();
		        Sheet sheet = workbook.createSheet();
		        ExcelHelper helper = new ExcelHelper();
		        //helper.createreviewscore(workbook,sheet);//创建表头
		        //helper.createproblemexport(reviewScoreService.evaluationproblemexport(investigatedid),workbook,sheet);
		        helper.perassexport(personnelAssessmentService.reviewjudgegrade(investigatedid,questionnaireId),
		        		personnelAssessmentService.reviewrinqu(investigatedid,questionnaireId),personnelAssessmentService.questionoblemsex(questionnaireId,3),
		        		personnelAssessmentService.scoreproblemexcl(investigatedid,questionnaireId),
		        		personnelAssessmentService.questionoblemswenex(questionnaireId,3),personnelAssessmentService.scoreproblemwenexcl(investigatedid,questionnaireId)
		        		,workbook,sheet);
		        
		        response.setContentType("multipart/form-data");
		        String fileName = "problemexport.xlsx";
		        try {
		            fileName = URLEncoder.encode("导出评价.xlsx","UTF-8");
		        } catch (UnsupportedEncodingException e) {
		            e.printStackTrace();
		        }
		        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
		        OutputStream outputStream =null;
		        try{
		            outputStream = response.getOutputStream();
		            workbook.write(outputStream);
		        } catch (Exception ex){

		        } finally {
		            try{
		                workbook.close();
		            } catch (Exception ex){

		            }
		        }
		    	
		    }
		    
		    @GetMapping(value = "/scoredtost", produces = "application/json;charset=utf-8")
		    public Result scoredtost(@RequestParam(value="investigatedid",required=true)Integer investigatedid,
		    		@RequestParam(value="gradeid",required=true)Integer gradeid,@RequestParam(value="questionnaireId",required=false)Integer questionnaireId,
		            HttpServletRequest request) {
		    	//hasRole(roleCode)
		    	return personnelAssessmentService.scoredtost(investigatedid,gradeid,questionnaireId);
		    }
		    
		    @GetMapping(value = "/scoredtosx", produces = "application/json;charset=utf-8")
		    public Result scoredtostx(@RequestParam(value="investigatedid",required=true)Integer investigatedid,
		    		@RequestParam(value="gradeid",required=true)Integer gradeid,@RequestParam(value="questionnaireId",required=false)Integer questionnaireId,
		            HttpServletRequest request) {
		    	//hasRole(roleCode)
		    	return personnelAssessmentService.scoredtosx(investigatedid,gradeid,questionnaireId);
		    }
		    
		    @GetMapping(value = "/getlistlishi", produces = "application/json;charset=utf-8")
		    public Result getlistlishi(@RequestParam(value="investigatedid",required=false)Integer investigatedid,
		    		@RequestParam(value="gradeid",required=false)Integer gradeid,@RequestParam(value="questionnaireId",required=false)Integer questionnaireId,
		            HttpServletRequest request) {
		    	//hasRole(roleCode)
		    	return personnelAssessmentService.getlistlishi(investigatedid);
		    }
		    
		    @GetMapping(value = "/scoreraid", produces = "application/json;charset=utf-8")
		    public Result scoreraid(ReviewScoreProblemDTO scoreproblem,
					       HttpServletRequest request) {
		    	

		    	return personnelAssessmentService.scoreraid(scoreproblem);
		    }
		    
		    @GetMapping(value = "/reviewevaluate", produces = "application/json;charset=utf-8")
		    public Result reviewevaluate(@RequestParam(value="investigatedid",required=true)Integer investigatedid,
		    		@RequestParam(value="questionnaireid",required=true)Integer questionnaireid,
		            HttpServletRequest request) {   	    	
		    	
		    	return personnelAssessmentService.reviewevaluate(investigatedid,questionnaireid);
		    }
		    
		    
		    /**
		     * 270xls导入
		     */
		    @ResponseBody
		    @RequestMapping(value = "/importXlsx", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
		    public Result importXlsx(@RequestParam(value = "usname", defaultValue = "", required = false) String usname,
		    		HttpServletRequest request,@RequestParam(value = "file", defaultValue = "", required = true) MultipartFile multipartFile) throws ServiceException {
		    	
		        if (multipartFile == null) {
		            throw new ServiceException("请选择需要上传的文件");
		        }
		        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
		        if (commonsMultipartFile.isEmpty()) {
		            return Response.responseFail("上传文件为空文件");
		        }
		        String fileName = commonsMultipartFile.getOriginalFilename();
		        if (fileName.indexOf(".xlsx") != -1) {
		        	
		        	   return Response.response(personnelAssessmentemporaryService.excelToxls(multipartFile,fileName,usname,getAccessToken().getUserCode(),getAccessToken(request)));
		           
		        }
		        if (fileName.indexOf(".xls") != -1) {
		        	
		        	   return Response.response(personnelAssessmentemporaryService.excelToxls(multipartFile,fileName,usname,getAccessToken().getUserCode(),getAccessToken(request)));
		           
		        }
		       
		        return Response.responseFail("上传文件应为excel文件格式为：xlsx或xls");
		 
		    }
		    
		    
		    //270导出
		    @RequestMapping(value = "/evaluatperAssessment", produces = "multipart/form-data",  method = RequestMethod.GET)
		    public void evaluatperAssessment(@RequestParam(value="is_all",required=false)Integer is_all,@RequestParam(value="userId",required=false)String userId,
		    		@RequestParam(value="name",required=false)String name,@RequestParam(value="regionName",required=false) String regionName,@RequestParam(value="personneluserid",required=false)String personneluserid,
		    		AccessToken accessToken,HttpServletRequest request, HttpServletResponse response) throws ParseException {
		    	
		    	PersonnelAssessmentDTO personnelAssessment=new PersonnelAssessmentDTO();
		    	personnelAssessment.setName(name);
		    	personnelAssessment.setUserId(userId);
		    	personnelAssessment.setRegionName(regionName);
		    	
		    	Workbook workbook = new XSSFWorkbook();
		        Sheet sheet = workbook.createSheet();
		        ExcelHelper helper = new ExcelHelper();
//		        
//		        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(getAccessToken().getUserCode());    	
		    	List<String> userquyu=new ArrayList<>();
		    	List<DupOrgan> result=null;
		    	for (Object obj : rolesMap.keySet()) {
		    		String key = (String) obj;
		    		if (key.equals("gj_admin")) {
		    			 
		    			 rolesMap.put("identitys", null);
		    			 break;
		    		}else if (key.equals("role")) {
		    			 
		    			 rolesMap.put("identitys", null);
		    			 break;
					}else if (key.equals("gj_Area")) {
						//List<String> liuserquyu=personnelCommenService.findErpRegionByUserCode(getAccessToken().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());
							}
					}
		    		
		    	}

				String[] idIntegers;
				String[] idArry = null;
				if (personneluserid!=null&&!personneluserid.equals("")) {
					idIntegers=personneluserid.split(",");
				    idArry = new String[idIntegers.length];
				    for (int i = 0; i < idIntegers.length; i++) {
				    	idArry[i]=idIntegers[i];
					}

				}
				 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				 String dacreateddate=null;				
				List<String> perseluserid=Arrays.asList(idArry);
		        
		      // is_all==1  全部  is_all==0 最新
		        	
				if (personnelAssessment.getUserId()!=null&&!personnelAssessment.getUserId().equals("")&&personnelAssessment.getName()!=null&&!personnelAssessment.getName().equals("")&&
						personnelAssessment.getRegionName()!=null&&!personnelAssessment.getRegionName().equals("")) {
					userquyu=null;
				}
				
		        helper.exxlspersonnelAssessment(personnelAssessmentService.exxlspersonnelAssessment(personnelAssessment,is_all,perseluserid,rolesMap,accessToken,userquyu),workbook,sheet);
		        	
		        response.setContentType("multipart/form-data");
		        String fileName = "problemexport.xlsx";
		        try {
		            fileName = URLEncoder.encode("270测评.xlsx","UTF-8");
		        } catch (UnsupportedEncodingException e) {
		            e.printStackTrace();
		        }
		        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
		        OutputStream outputStream =null;
		        try{
		            outputStream = response.getOutputStream();
		            workbook.write(outputStream);
		        } catch (Exception ex){

		        } finally {
		            try{
		                workbook.close();
		            } catch (Exception ex){

		            }
		        }
		    	
		    	
		    	
		    }
}