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.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
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.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.primitives.Ints;

import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
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.PersonnelAdvisor;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelAdvisorMapper;
import cn.com.countrygarden.bi.main.dto.PersonnelAdvisorDTO;
import cn.com.countrygarden.bi.main.dto.PersonnelCampusevaluationDTO;
import cn.com.countrygarden.bi.main.dto.personnelTagDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelAdvisorService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelCommenService;
import cn.com.countrygarden.bi.main.util.MD5;

/**
 * 导师信息-控制层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2018-09-27
 */
@RestController("PersonnelAdvisorController")
@RequestMapping("/api/personnelAdvisor")
public class PersonnelAdvisorController extends BaseController{
    @Autowired
    private PersonnelAdvisorService personnelAdvisorService;
    
    @Autowired
    private PersonnelAdvisorMapper personnelAdvisorMapper;
    
    @Autowired
    private AccessTokenService accessTokenService;
    
    @Autowired
    private Environment env;
    
    @Autowired
    private PersonnelCommenService personnelCommenService;


    @GetMapping(value = "/list", produces = "application/json;charset=utf-8")
    public Result list(PersonnelAdvisorDTO personnelAdvisordto,
                       @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                       @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                       HttpServletRequest request){
        return  personnelAdvisorService.queryPageList(personnelAdvisordto,page,size,getAccessToken(request));
    }
    
    @GetMapping(value = "/queryPageListadnamelist", produces = "application/json;charset=utf-8")
    public Result queryPageListadnamelist(PersonnelAdvisorDTO personnelAdvisordto,
                     
                       HttpServletRequest request){
        return  personnelAdvisorService.queryPageListadnamelist(personnelAdvisordto);
    }
    
    @GetMapping(value = "/peradvisorlist", produces = "application/json;charset=utf-8")
    public Result peradvisorlist(PersonnelAdvisor personnelAdvisor,
                      
                       HttpServletRequest request){
        return  personnelAdvisorService.peradvisorlist(personnelAdvisor);
    }

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

    @PostMapping(value = "/add")
    public Result add(String personadvisor,
                      HttpServletRequest request){
        return  personnelAdvisorService.add(personadvisor,getAccessToken(request));
    }

    @PutMapping(value = "/edit")
    public Result edit(String personnelAdvisor, HttpServletRequest request){
        return  personnelAdvisorService.edit(personnelAdvisor,getAccessToken(request));
    }

    @DeleteMapping(value="/del")
    public Result del(@RequestParam(value = "personnelId", required = true)Integer personnelId,@RequestParam(value = "personneltagId", required = true)Integer personneltagId){
        return  personnelAdvisorService.delperid(personnelId,personneltagId);
    }
    
    
    @DeleteMapping(value="/delpiliang")
    public Result delpiliang(@RequestParam(value = "personnelId", required = true)String personnelId,@RequestParam(value = "personneltagId", required = true)String personneltagId){
        return  personnelAdvisorService.delpiliang(personnelId,personneltagId);
    }
    
    @GetMapping(value = "/queryPageListadd",produces="application/json;charset=utf-8")
    public Result queryPageListadd(PersonnelAdvisorDTO personnelAdvisordto){
    	
       
        return personnelAdvisorService.queryPageListadd(personnelAdvisordto);
    }
    
    @GetMapping(value = "/queryadByUid",produces="application/json;charset=utf-8")
    public Result queryadByUid(@RequestParam(value="search",required=true)String search,HttpServletRequest request){
    	
        return personnelAdvisorService.queryadByUid(search,getAccessToken(request));
    }
    
  //导出数据
    @RequestMapping(value = "/evaluatperAdvisor", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluatperAdvisor(@RequestParam(value="is_all",required=false)Integer is_all,@RequestParam(value="personnelIds",required=false)String personnelIds,
    		PersonnelAdvisorDTO personnelAdvisordto,AccessToken accessToken,HttpServletRequest request, HttpServletResponse response) throws ParseException {
    	
    	Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        ExcelHelper helper = new ExcelHelper();
       // helper.expersonnelAdvisorCampuse(workbook,sheet);//创建表头
        
//        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")) {
    			 userquyu=null;
    			 rolesMap.put("identitys", null);
    			 break;
    		}else if (key.equals("role")) {
    			 userquyu=null;
    			 rolesMap.put("identitys", null);
    			 break;
			}else if (key.equals("gj_Area")) {
				//List<String> liuserquyu=personnelCommenService.findErpRegionByUserCode(getAccessToken().getUserCode());
				//userquyu=liuserquyu.get(0);
				 result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
				 for (int i = 0; i < result.size(); i++) {
						userquyu.add(result.get(i).getOrganName());
					}
			}
    		
    	}
    	
    	
    	
		String[] idIntegers;
		int[] idArry = null;
		if (personnelIds!=null&&!personnelIds.equals("")) {
			idIntegers=personnelIds.split(",");
		    idArry = new int[idIntegers.length];
		    for (int i = 0; i < idIntegers.length; i++) {
		    	idArry[i]=Integer.parseInt(idIntegers[i]);
			}

		}
		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 String additionTimequ=null;
		 String additionTimexin=null;
		List<Integer> perid=Ints.asList(idArry);
		
//		List<PersonnelAdvisorDTO> dtoper=new ArrayList<PersonnelAdvisorDTO>();
//		List<PersonnelAdvisorDTO> dtoperxin=new ArrayList<PersonnelAdvisorDTO>();
//      	if (result!=null&&result.size()!=0) {
//      		for (int i = 0; i < result.size(); i++) {
//      			List<PersonnelAdvisorDTO> persapper=personnelAdvisorMapper.exxlspersonnelAdvisor(personnelAdvisordto,rolesMap,perid,result.get(i).getOrganName());
//      			List<PersonnelAdvisorDTO> perxin=personnelAdvisorMapper.exxlspersonneall(rolesMap,result.get(i).getOrganName());
//      			if (persapper.size()!=0) {
//      				dtoper.addAll(persapper);
//  				}  
//      			if (perxin.size()!=0) {
//      				dtoperxin.addAll(perxin);
//  				}    
//      		}
//  		}else {
//  			dtoper = personnelAdvisorMapper.exxlspersonnelAdvisor(personnelAdvisordto,rolesMap,perid,null);
//  		}
		if (personnelAdvisordto.getRegionName()!=null&&!personnelAdvisordto.getRegionName().equals("")&&personnelAdvisordto.getUserId()!=null&&!personnelAdvisordto.getUserId().equals("")
      			&&personnelAdvisordto.getName()!=null&&!personnelAdvisordto.getName().equals("")) {
      		
      		userquyu=null;
		}
		
		if (is_all==1) {//导出全部
	     helper.exxlspersonnelAdvisor(personnelAdvisorMapper.exxlspersonnelAdvisor(personnelAdvisordto,rolesMap,perid,userquyu),workbook,sheet);
			
			
		}else if (is_all==0) {//导出最新
			
			List<PersonnelAdvisorDTO> perhe=new ArrayList<PersonnelAdvisorDTO>();
			
			List<PersonnelAdvisorDTO> perquan=personnelAdvisorMapper.exxlspersonnelAdvisor(personnelAdvisordto,rolesMap,perid,userquyu);
			
			
			List<PersonnelAdvisorDTO> perxin=personnelAdvisorMapper.exxlspersonneall(rolesMap,userquyu);
			
			for (PersonnelAdvisorDTO personn : perquan) {
				for (PersonnelAdvisorDTO personcxi : perxin) {
					
					if (personn.getCreatedDate()!=null) {
						additionTimequ=formatter.format(personn.getCreatedDate());
					}
					if (personcxi.getCreatedDate()!=null) {
						additionTimexin=formatter.format(personcxi.getCreatedDate());
					}
					
					if (personn.getPersonnelId().equals(personcxi.getPersonnelId())&&personn.getRegionName().equals(personcxi.getRegionName())&&
							personn.getPersonnelTypeId().equals(personcxi.getPersonnelTypeId())&&
							additionTimequ.equals(additionTimexin)) {
						perhe.add(personn);
					}
				}
			}
				
			 helper.exxlspersonnelAdvisor(perhe,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){

            }
        }
    	
    }
    
    /**
     * xls导入
     */
    @ResponseBody
    @RequestMapping(value = "/importXlsx", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result importXlsx(@RequestParam(value = "radio", defaultValue = "", required = false) Integer radio,
    		@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) {
        	personnelAdvisorService.excelToxls(radio,usname,multipartFile,fileName,getAccessToken().getUserCode(),getAccessToken(request));
        	   return Response.response("导入成功");
           
        }
        if (fileName.indexOf(".xls") != -1) {
        	personnelAdvisorService.excelToxls(radio,usname,multipartFile,fileName,getAccessToken().getUserCode(),getAccessToken(request));
        	   return Response.response("导入成功");
           
        }
       
        return Response.responseFail("上传文件应为excel文件格式为：xlsx或xls");
 
    }
    
  //上传
    @ResponseBody
    @RequestMapping(value = "/peuploadFiles", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result upload(
            @RequestParam(value = "file", defaultValue = "", required = true) MultipartFile[] multipartFiles,
            HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);

        //记录上传的文件名称
        StringBuilder sb = new StringBuilder();

        if (multipartFiles == null) {
            throw new ServiceException("请选择需要上传的文件");
        }

        String fileName = "";
        for (MultipartFile multipartFile : multipartFiles) {

           
			String basePath = env.getProperty("resident.file.path");
            String accessPath = env.getProperty("resident.file.url.base");
            if (StringUtils.isEmpty(basePath)) {
                basePath = request.getServletContext().getRealPath("");
            }
            //save file
            Instant instant = Instant.now();
            LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                   
            fileName = multipartFile.getOriginalFilename();
  
            if (fileName.indexOf(".ppt") != -1|| fileName.indexOf(".doc") != -1||fileName.indexOf(".xlsx") != -1||
            		fileName.indexOf(".xls") != -1||fileName.indexOf(".docx") != -1||fileName.indexOf(".rar") != -1||fileName.indexOf(".zip") != -1||fileName.indexOf(".7z") != -1||fileName.indexOf(".pdf") != -1) {
            	 //文件存放路径 /uploadFile/年/月/日/时/分/秒
                String saveDirectory = "/uploadFile/" + dateTime.getYear() + "/"
                        + dateTime.getMonthValue() + "/" + dateTime.getDayOfMonth()
                        + "/" + dateTime.getHour() + dateTime.getMinute() + dateTime.getSecond();

                String saveFileName = saveDirectory + "/" + MD5.GetMD5Code(dateTime.toString()) + FilenameUtils.getBaseName(fileName) + "." + FilenameUtils.getExtension(fileName);
//                String saveFileName = saveDirectory + "/" + fileName;
                File dir = new File(basePath + saveDirectory);

                if (!dir.exists()) {
                    dir.mkdirs();
                }
                sb.append(accessPath + saveFileName + ",");
                File saveFile = new File(basePath + saveFileName);
                try {
                    ((CommonsMultipartFile) multipartFile).getFileItem().write(saveFile);
                } catch (Exception e) {

                    throw new ServiceException("无法保存上传文件：" + "上传文件应格式为：xlsx 或 xls");
                }
            	
               // return Response.responseFail("上传文件应格式为：jpg 或 png");
                sb.delete(sb.length() - 1, sb.length());
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("name", fileName);
                resultMap.put("url", sb.toString());
                
                return Response.response(resultMap);
            }
           
        }
        return Response.responseFail("无法保存上传文件");
    }
    


}