package cn.com.countrygarden.bi.main.controller.bigholderSatisfy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageRowBounds;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dto.AreaUser;
import cn.com.countrygarden.bi.main.dto.BigholderImportedDto;
import cn.com.countrygarden.bi.main.dto.BigholderProjectDto;
import cn.com.countrygarden.bi.main.dto.SatisfyInfo;
import cn.com.countrygarden.bi.main.dto.bigholder.UnsatisfyDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.BigholderRightManager;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.bigholderSatisfy.BigholderSatisfyService;

@RestController
@RequestMapping("/api/bigholderSatisfyController")
public class BigholderSatisfyController {
	
	@Autowired
	private AccessTokenService accessTokenService;

	@Autowired
	private BigholderSatisfyService bigholderSatisfyService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/dataImport", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result importSatisfyData(@RequestParam(value="yearMonth") String yearMonth,@RequestParam(value = "uploadfiles",required = false)MultipartFile multipartFile,HttpServletRequest request){
		String accessToken = request.getParameter("AccessToken");
		AccessToken token = accessTokenService.findByToken(accessToken);
		if(null  == multipartFile){
			throw new ServiceException("请选择需要上传的文件");
		}
		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
		if (commonsMultipartFile.isEmpty()) {
			return Response.responseFail("上传文件为空文件");
		}
		String fileName = commonsMultipartFile.getOriginalFilename();
		if(!(fileName.contains(".xlsx")||fileName.contains(".xls"))) {
			return Response.responseFail("上传文件应为excel文件格式为：xlsx 或 xls");
		}
		//文件名及月份校验
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MONTH, -1);
		Date lastMonthDate = cal.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String lastMonthStr = sdf.format(lastMonthDate);
		if(!lastMonthStr.equals(yearMonth)) {
			return Response.responseFail("当前只能导入"+lastMonthStr+"月份的数据");
		}
		lastMonthStr = lastMonthStr.replace("-", "");
		String fileName1 = lastMonthStr+"-项目总问卷.xls";
		String fileName2 = lastMonthStr+"-项目总问卷.xlsx";
		if(!(fileName1.equals(fileName)||fileName2.equals(fileName))) {
			return Response.responseFail("本月上传的文件名及格式应为:【"+fileName1+"】或【"+fileName2+"】");
		}
		HashMap<String, Object> result = bigholderSatisfyService.addSatisfyList(commonsMultipartFile,fileName,token.getUserCode());
		String flag = (String) result.get("flag");
		List<String> errorInfoList = (List<String>) result.get("errorInfo");
		Result response = new Result();
		if(flag!=null&&"ok".equals(flag)){
			response.setData(new Result().setResultMsg("0"));
			return response;
		}else if(errorInfoList!=null&&errorInfoList.size()>0){
			response.setResultMsg("1");
			response.setData(errorInfoList);
			return Response.response(response);
		}
		response.setResultMsg("2");//异常信息
		return Response.response(response);
	}
	
	@RequestMapping(value = "/findImportedList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Object findImportedList(@RequestParam(value="yearMonth",defaultValue="") String yearMonth,@RequestParam(value="skip") Integer page,@RequestParam(value="limit") Integer size,HttpServletRequest request){
		 PageRowBounds pageRowBounds = new PageRowBounds(page,size);
		 List<BigholderImportedDto> pagedlist = bigholderSatisfyService.findImportedList(yearMonth,pageRowBounds);
		 return Response.response(new PageData(pagedlist,pageRowBounds));
	}
	
	@RequestMapping(value = "/findAreaList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Object getAreas(HttpServletRequest request){
//		String accessToken = request.getParameter("AccessToken");
//		AccessToken token = accessTokenService.findByToken(accessToken);
		return Response.response(bigholderSatisfyService.getAreas());
	}
	
	@RequestMapping(value = "/updateArea", produces = "application/json;charset=utf-8", method = RequestMethod.PUT)
	public Result updateArea(@RequestParam(value="yearMonth",defaultValue="") String yearMonth,@RequestParam(value="estateArea",defaultValue="") String estateArea,@RequestParam(value="area") String area, @RequestParam(value="project") String project,HttpServletRequest request){
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MONTH, -1);
		Date date = cal.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String dateStr = sdf.format(date);
		if(!dateStr.equals(yearMonth)) {
			return Response.responseFail("当前只能更改【"+dateStr+"】月份下的区域数据");
		}
		boolean flag = bigholderSatisfyService.updateArea(estateArea,area,project);
		if(flag){
			return Response.response("ok");
		}else {
			return Response.responseFail("修改区域失败");
		}
	}
	
	
	@RequestMapping(value = "/findUserList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Object getUsers(@RequestParam(value="user",defaultValue="") String user,HttpServletRequest request){
//		String accessToken = request.getParameter("AccessToken");
//		AccessToken token = accessTokenService.findByToken(accessToken);
		Integer page = 1;
		Integer size = 100;
		PageRowBounds pageRowBounds = new PageRowBounds(page,size);
		List<BigholderRightManager> users = bigholderSatisfyService.getUsers(user,pageRowBounds);
		return Response.response(new PageData(users,pageRowBounds));
	}
	
	@RequestMapping(value = "/addRightList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result addRightList(@RequestParam(value="area",defaultValue="") String area,@RequestParam(value="areaId",defaultValue="") String areaId,@RequestParam(value="user",defaultValue="") String user,@RequestParam(value="userId",defaultValue="") String userId,HttpServletRequest request){
		if(!StringUtils.hasText(user)||!StringUtils.hasText(userId)) {
			return Response.responseFail("不存在该负责人，无法添加");
		}
		boolean flag = bigholderSatisfyService.addRightList(area,areaId,user,userId);
		if(flag){
			return Response.response("ok");
		}else {
			return Response.responseFail("区域已存在该负责人，不能重复添加");
		}
	}
	
	@RequestMapping(value = "/deleteRightList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result deleteRightList(@RequestParam(value="areaId",defaultValue="") String areaId,@RequestParam(value="userId",defaultValue="") String userId,HttpServletRequest request){
		boolean flag = bigholderSatisfyService.deleteRightList(areaId,userId);
		if(flag){
			return Response.response("ok");
		}else {
			return Response.responseFail("删除权限失败");
		}
	}
	
	@RequestMapping(value = "/findRightList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Object findRightList(@RequestParam(value="skip",defaultValue="1") Integer page,@RequestParam(value="limit",defaultValue="8") Integer size,HttpServletRequest request){
//		String accessToken = request.getParameter("AccessToken");
//		AccessToken token = accessTokenService.findByToken(accessToken);
		String user = request.getParameter("user");
		String area = request.getParameter("area");
		HashMap<String, String> param = new HashMap<String,String>();
		param.put("user", user);
		param.put("area", area);
		PageRowBounds pageRowBounds = new PageRowBounds(page,size);
		List<AreaUser> areaUserList = bigholderSatisfyService.findRightList(user,area,pageRowBounds);
		if(areaUserList==null||areaUserList.size()==0) {
			return Response.response(new PageData(areaUserList,null));
		}
		return Response.response(new PageData(areaUserList,pageRowBounds));
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/dataImport2", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result importLandEstateData(@RequestParam(value = "uploadfiles",required = false)MultipartFile multipartFile,HttpServletRequest request){
		String accessToken = request.getParameter("AccessToken");
		AccessToken token = accessTokenService.findByToken(accessToken);
		if(null  == multipartFile){
			throw new ServiceException("请选择需要上传的文件");
		}
		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
		if (commonsMultipartFile.isEmpty()) {
			return Response.responseFail("上传文件为空文件");
		}
		String fileName = commonsMultipartFile.getOriginalFilename();
		if(!(fileName.contains(".xlsx")||fileName.contains(".xls"))) {
			return Response.responseFail("上传文件应为excel文件格式为：xlsx 或 xls");
		}
		HashMap<String, Object> result = bigholderSatisfyService.addLandEstateList(commonsMultipartFile,fileName,token.getUserCode());
		String quarterExist = (String) result.get("quarterExist");
		List<String> errorInfoList = (List<String>) result.get("errorInfo");
		String flag = (String) result.get("flag");
		Result response = new Result();
		if(quarterExist!=null&&"1".equals(quarterExist)) {
			response.setResultMsg("2");
			return Response.response(response);
		}else if (errorInfoList!=null&&errorInfoList.size()>0) {
			response.setResultMsg("1");
			response.setData(errorInfoList);
			return Response.response(response);
		}else if (flag!=null&&"ok".equals(flag)) {
			response.setResultMsg("0");
			return Response.response(response);
		}
		response.setResultMsg("3");//异常信息
		return Response.response(response);
	}
	
	@RequestMapping(value = "/projectRankList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result projectRankList(@RequestParam(value="pageIndex") Integer page,@RequestParam(value="pageSize") Integer size,@RequestParam(value="area",defaultValue="") String area,@RequestParam(value="project",defaultValue="") String project,@RequestParam(value="yearMonth") String yearMonth,@RequestParam(value="yearMonthStart") String yearMonthStart,@RequestParam(value="yearMonthEnd") String yearMonthEnd,@RequestParam(value="timeType") String timeType,HttpServletRequest request){
		String accessToken = request.getParameter("AccessToken");
		AccessToken token = accessTokenService.findByToken(accessToken);
		String userCode = token.getUserCode();
		List<BigholderProjectDto> projectRankList = null;
		if(!StringUtils.hasText(area)&&!StringUtils.hasText(project)) {
			PageRowBounds pageRowBounds = new PageRowBounds(page,size);
			projectRankList = bigholderSatisfyService.projectRankList(userCode,yearMonth,yearMonthStart,yearMonthEnd,timeType,pageRowBounds);
			return Response.response(new PageData(projectRankList,pageRowBounds));
		}else {
			projectRankList = bigholderSatisfyService.projectRankList(userCode,yearMonth,yearMonthStart,yearMonthEnd,timeType,null);
			List<BigholderProjectDto> searchList = search(area, project, projectRankList);
			PageData pageData = paging(searchList, searchList.size(), page, size);
			return Response.response(pageData);
		}
	}
	
	@RequestMapping(value = "/satisfyInfosByTime", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result satisfyInfosByTime(@RequestParam(value="yearMonthStart") String yearMonthStart,@RequestParam(value="yearMonthEnd") String yearMonthEnd,@RequestParam(value="timeType") String timeType,@RequestParam(value="area") String area,@RequestParam(value="project") String project,HttpServletRequest request){
		String accessToken = request.getParameter("AccessToken");
		AccessToken token = accessTokenService.findByToken(accessToken);
		String userCode = token.getUserCode();
		SatisfyInfo satisfyInfo = bigholderSatisfyService.satisfyInfosByTime(userCode,area,project,yearMonthStart,yearMonthEnd,timeType);
		return Response.response(satisfyInfo);
	}
	
	@RequestMapping(value = "/unsatisfyInfo", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result unsatisfyInfo(@RequestParam(value="annualState") String annualState,@RequestParam(value="howQuarters") String howQuarters,@RequestParam(value="yearMonthStart") String yearMonthStart,@RequestParam(value="yearMonthEnd") String yearMonthEnd,@RequestParam(value="area") String area,@RequestParam(value="project") String project,HttpServletRequest request){
		String accessToken = request.getParameter("AccessToken");
		AccessToken token = accessTokenService.findByToken(accessToken);
		String userCode = token.getUserCode();
		List<UnsatisfyDto> unsatisfyDtos = null;
		if("0".equals(annualState)) {
			yearMonthStart = yearMonthEnd;
			unsatisfyDtos = bigholderSatisfyService.unsatisfyInfo(userCode,area,project,yearMonthStart,yearMonthEnd);
			return Response.response(unsatisfyDtos);
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int year = cal.get(Calendar.YEAR);
		switch (howQuarters) {
		case "1":
			yearMonthStart = year + "-01";
			yearMonthEnd = year + "-03";
			break;
		case "2":
			yearMonthStart = year + "-04";
			yearMonthEnd = year + "-06";
			break;
		case "3":
			yearMonthStart = year + "-07";
			yearMonthEnd = year + "-09";
			break;
		default:
			yearMonthStart = year + "-10";
			yearMonthEnd = year + "-12";
			break;
		}
		unsatisfyDtos = bigholderSatisfyService.unsatisfyInfo(userCode,area,project,yearMonthStart,yearMonthEnd);
		return Response.response(unsatisfyDtos);
	}
	
	@RequestMapping(value = "/trendAnalysis", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result trendAnalysis(@RequestParam(value="yearMonthStart") String yearMonthStart,@RequestParam(value="yearMonthEnd") String yearMonthEnd,@RequestParam(value="area") String area,@RequestParam(value="project") String project,@RequestParam(value="type",defaultValue="0") String type,HttpServletRequest request){
		String accessToken = request.getParameter("AccessToken");
		AccessToken token = accessTokenService.findByToken(accessToken);
		String userCode = token.getUserCode();
		List<UnsatisfyDto> trendDtoList = bigholderSatisfyService.trendAnalysis(userCode,area,project,yearMonthStart,yearMonthEnd,type);
		return Response.response(trendDtoList);
	}
	
	@RequestMapping(value = "/isExistExceptionArea", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	public Result isExistExceptionArea(HttpServletRequest request){
		String flag = bigholderSatisfyService.isExistExceptionArea();
		return Response.response(flag);
	}
	
	/**
	 * 对list进行搜索
	 * @param area
	 * @param project
	 * @param list
	 * @return
	 */
	private List<BigholderProjectDto> search(String area,String project,List<BigholderProjectDto> list){
	   List<BigholderProjectDto> results = new ArrayList<>();
	   if(StringUtils.hasText(area)&&StringUtils.hasText(project)) {
		   for(int i=0; i < list.size(); i++){
			   if(area.equals((list.get(i)).getEstateArea())&&project.equals((list.get(i)).getProjectName())){
				   results.add(list.get(i));
			   }
		   }
	   }
	   if(StringUtils.hasText(area)&&!StringUtils.hasText(project)) {
		   for(int i=0; i < list.size(); i++){
			   if(area.equals((list.get(i)).getEstateArea())) {
				   results.add(list.get(i));
			   }
		   }
	   }
	   if(!StringUtils.hasText(area)&&StringUtils.hasText(project)) {
		   for(int i=0; i < list.size(); i++){
			   if(project.equals((list.get(i)).getProjectName())) {
				   results.add(list.get(i));
			   }
		   }
	   }
	   return results;
	}
	
	/**
	 * 分页
	 * @return
	 */
	private PageData paging(List<BigholderProjectDto> datas, int totalSize, int pageIndex,
			int pageSize) {
		// 页数
		int pages = 0;
		if (totalSize % pageSize > 0) {
			pages = totalSize / pageSize + 1;
		} else {
			pages = totalSize / pageSize;
		}
		List<BigholderProjectDto> subList = null;
		int fromIndex = (pageIndex - 1) * pageSize;
		if (pageIndex < pages) {
			subList = datas.subList(fromIndex, fromIndex + pageSize);
		} else if (pageIndex == pages) {
			subList = datas.subList(fromIndex, totalSize);
		} else {
			subList = new ArrayList<BigholderProjectDto>();
		}
		PageData pageData = new PageData();
		pageData.setData(subList);
		pageData.setCurrentPage(pageIndex);
		if(pageIndex==pages) {
			pageData.setEndOfPage(true);
		}else {
			pageData.setEndOfPage(false);
		}
		pageData.setPages(pages);
		pageData.setPageSize(pageSize);
		return pageData;
	}
}
