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.hssf.usermodel.HSSFWorkbook;
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.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 java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
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.PersonnelCampusevaluation;
import cn.com.countrygarden.bi.main.model.personnel.PersonnelTag;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelCampusevaluationMapper;
import cn.com.countrygarden.bi.main.dto.PersonnelCampusDTO;
import cn.com.countrygarden.bi.main.dto.PersonnelCampusevaluationDTO;
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.PersonnelCampusevaluationService;
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-20
 */
@RestController("PersonnelCampusevaluationController")
@RequestMapping("/api/personnelCampusevaluation")
public class PersonnelCampusevaluationController extends BaseController {
	@Autowired
	private PersonnelCampusevaluationService personnelCampusevaluationService;

	@Autowired
	private Environment env;

	@Autowired
	private AccessTokenService accessTokenService;

	@Autowired
	private PersonnelCampusevaluationMapper personnelcaluationmapper;

	@Autowired
	private PersonnelCommenService personnelCommenService;

	@GetMapping(value = "/percamlist", produces = "application/json;charset=utf-8")
	public Result percamlist(PersonnelCampusevaluationDTO percam,
			@RequestParam(value = "size", required = false, defaultValue = "10") int size,
			@RequestParam(value = "page", required = false, defaultValue = "1") int page, HttpServletRequest request) {

		return personnelCampusevaluationService.percamlist(percam, page, size, getAccessToken(request));

	}

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

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

	@PostMapping(value = "/add")
	public Result add(PersonnelCampusevaluationDTO personnelCampusevaluation, HttpServletRequest request) {

		return personnelCampusevaluationService.add(personnelCampusevaluation, getAccessToken(request));
	}

	@GetMapping(value = "/addone")
	public Result addone(@RequestParam(value = "userId", required = true) String userId,
			@RequestParam(value = "personneltagId", required = true) Integer personneltagId,
			HttpServletRequest request) {

		return personnelCampusevaluationService.addone(userId, personneltagId);
	}

	@PutMapping(value = "/edit")
	public Result edit(PersonnelCampusDTO personnelCampusevaluation, HttpServletRequest request) {
		return personnelCampusevaluationService.edit(personnelCampusevaluation, getAccessToken(request));
	}

	@DeleteMapping(value = "/del")
	public Result del(@RequestParam(value = "id", required = true) Integer id) {
		return personnelCampusevaluationService.del(id);
	}

	@DeleteMapping(value = "/delpiliang")
	public Result delpiliang(@RequestParam(value = "perid", required = true) String perid) {
		return personnelCampusevaluationService.delpiliang(perid);
	}

	@GetMapping(value = "/personInfoCodeOrId", produces = "application/json;charset=utf-8")
	public Result personInfoCodeOrId(@RequestParam(value = "search", required = true) String search) {

		return personnelCampusevaluationService.personInfoCodeOrId(search);
	}

	@GetMapping(value = "/queryadByUid", produces = "application/json;charset=utf-8")
	public Result queryadByUid(@RequestParam(value = "search", required = true) String search,
			HttpServletRequest request) {

		return personnelCampusevaluationService.queryadByUid(search, getAccessToken(request));
	}

	@GetMapping(value = "/personneltag", produces = "application/json;charset=utf-8")
	public Result personneltag(@RequestParam(value = "userId", required = false) String userId,
			@RequestParam(value = "identity", required = false) String identity) {

		return personnelCampusevaluationService.personneltag(userId, identity);
	}

	// 上传图片
	@ResponseBody
	@RequestMapping(value = "/pefileUpload", 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("无法保存上传文件");
				}

				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("无法保存上传文件");
	}

	/**
	 * xls导入
	 */
	@ResponseBody
	@RequestMapping(value = "/importXlsx", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result importXlsx(@RequestParam(value = "usname", defaultValue = "", required = false) String usname,
			@RequestParam(value = "radio", defaultValue = "", required = false) Integer radio,
			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(personnelCampusevaluationService.excelToxls(radio, multipartFile, fileName, usname,
					getAccessToken().getUserCode(), getAccessToken(request)));

		}
		if (fileName.indexOf(".xls") != -1) {

			return Response.response(personnelCampusevaluationService.excelToxls(radio, multipartFile, fileName, usname,
					getAccessToken().getUserCode(), getAccessToken(request)));

		}

		return Response.responseFail("上传文件应为excel文件格式为：xlsx或xls");

	}

	// 导出数据
	@RequestMapping(value = "/evaluationpersonnelCampuse", produces = "multipart/form-data", method = RequestMethod.GET)
	public void evaluationpersonnelCampuse(PersonnelCampusevaluationDTO percam, HttpServletRequest request,
			AccessToken accessToken, HttpServletResponse response) throws ParseException {

		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")) {
				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());
				}
			}

		}
		helper.expersonnelCampuse(workbook, sheet);// 创建表头

//        List<PersonnelCampusevaluationDTO> dtoper=new ArrayList<PersonnelCampusevaluationDTO>();
//    	
//    	if (result!=null&&result.size()!=0) {
//    		for (int i = 0; i < result.size(); i++) {
//    			List<PersonnelCampusevaluationDTO> persapper=personnelcaluationmapper.exxlspersonnelcampus(percam,rolesMap,result.get(i).getOrganName());
//    			if (persapper.size()!=0) {
//    				dtoper.addAll(persapper);
//				}    		
//    		}
//		}else {
//			dtoper = personnelcaluationmapper.exxlspersonnelcampus(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;
		}

		helper.excreatnelCampuse(personnelcaluationmapper.exxlspersonnelcampus(percam, rolesMap, userquyu), 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) {

			}
		}

	}

}