package com.jeeplus.modules.API.works.calendar;

import java.text.ParseException;
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 com.jeeplus.modules.utils.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.iim.dao.MyCalendarDao;
import com.jeeplus.modules.iim.entity.MyCalendar;
import com.jeeplus.modules.iim.service.MyCalendarService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value = "${frontPath}/work/calendar")
public class CalendarController extends BaseController {

	@Autowired
	private MyCalendarDao myCalendarDao;

	@Autowired
	private MyCalendarService myCalendarService;

	/**
	 * 本月所有拥有日程的日期
	 *
	 * @param id
	 * @param year
	 * @param month
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping(value = "getMyCalendarList", method = RequestMethod.GET)
	public AjaxJson findMyCalendarList(HttpServletRequest request, HttpServletResponse response,
									   RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson json = new AjaxJson();
		String userId = request.getParameter("userId");
		String date = request.getParameter("date");
		String str[] = date.split("-");
		if (str.length == 2) {
			String year = str[0];
			String month = str[1];
			if (month.length() == 2) {

				MyCalendar myCalendar = new MyCalendar();
				User user = UserUtils.get(userId);
				myCalendar.setUser(user);
				myCalendar.setCompanyId(UserUtils.getSelectCompany().getId());
				List<MyCalendar> list = myCalendarDao.findList(myCalendar);
				List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
				int count = DateUtils.getMaxDay(Integer.parseInt(year), Integer.parseInt(month));
				/*
				 * if(month.equals("02")){ if((Integer.parseInt(year)%4==0 &&
				 * Integer.parseInt(year)%100!=0) ||
				 * Integer.parseInt(year)%400==0){ count=29; }else{ count=28; }
				 * }else if(month.equals("01") || month.equals("03") ||
				 * month.equals("05") || month.equals("07")||
				 * month.equals("08")|| month.equals("10")||month.equals("12")){
				 * count=31; }else if(month.equals("04") || month.equals("06")
				 * || month.equals("09") || month.equals("11")){ count=30; }
				 */
				for (int j = 1; j <= count; j++) {
					List<MyCalendar> newList = new ArrayList<MyCalendar>();
					for (int i = 0; i < list.size(); i++) {
						String date1 = list.get(i).getStart();
						String end = list.get(i).getEnd();
						String dates[] = date1.split("-");
						if (dates.length > 1) {
							int dates2 = Integer.parseInt(dates[2].substring(0, 2));
							if (end == null || end.equals("")) {
								if (dates[0].equals(year) && dates[1].equals(month) && dates2 == j) {
									newList.add(list.get(i));
								}
							} else {
								String datesEnd[] = end.split("-");
								if (datesEnd.length > 1) {
									int end2 = Integer.parseInt(datesEnd[2].substring(0, 2));
									if (dates[0].equals(year) && dates[1].equals(month) && dates2 <= j && j <= end2) {
										newList.add(list.get(i));
									}
								}
							}
						}
					}
					// System.out.println("=================" + newList.size());
					String day = "";
					if (j < 10) {
						day = "0" + j;
					} else {
						day = j + "";
					}
					if (newList.size() > 0) {
						String listIds = "";
						for (int a = 0; a < newList.size(); a++) {
							listIds = listIds + newList.get(a).getId() + ",";
						}
						Map<String, String> map = new HashMap<String, String>();

						map.put("day", year + "-" + month + "-" + day);
						map.put("type", "1");// 1代表当天有值0 代表当天无值
						map.put("calendarIds", listIds);
						mapList.add(map);
					} else {
						Map<String, String> map = new HashMap<String, String>();
						map.put("day", year + "-" + month + "-" + day);
						map.put("type", "0");// 1代表当天有值 0代表当天无值
						map.put("calendarIds", "");
						mapList.add(map);
					}
				}
				json.setMsg("获取日程成功");
				json.put("data", mapList);
				json.setErrorCode(ErrorCode.code_1004);
			} else {
				json.setMsg("日期格式错误，获取日程失败");
				json.put("data", Lists.newArrayList());
				json.setErrorCode(ErrorCode.code_2002);
				json.setSuccess(false);
			}
		} else {
			json.setMsg("日期格式错误，获取日程失败");
			json.put("data", Lists.newArrayList());
			json.setErrorCode(ErrorCode.code_2002);
			json.setSuccess(false);
		}
		return json;
	}

	/**
	 * 获取日程列表2
	 */
	@ResponseBody
	@RequestMapping(value = "getCalendarList", method = RequestMethod.GET)
	public AjaxJson getCalendarList(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		String userId = request.getParameter("userId");
		User user = UserUtils.get(userId);
		MyCalendar myCalendar = new MyCalendar();
		myCalendar.setUser(user);
		myCalendar.setCompanyId(UserUtils.getSelectCompany().getId());
		List<MyCalendar> list = myCalendarDao.findList(myCalendar);
		List<Map<String, Object>> mapList = Lists.newArrayList();
		for (MyCalendar my : list) {
			Map<String, Object> map = Maps.newHashMap();
			String date = my.getStart();
			String dates[] = date.split("-");
			String day = dates[0] + "-" + dates[1] + "-" + dates[2].substring(0, 2);
			map.put("date", day);
			map.put("calendarId", my.getId());
			map.put("type", "1");
			mapList.add(map);
		}

		if (mapList != null) {
			j.put("data", mapList);
			j.setMsg("获取列表成功");
			j.setErrorCode(ErrorCode.code_1004);
		} else {
			j.setSuccess(false);
			j.setErrorCode(ErrorCode.code_2004);
			j.setMsg("获取列表失败");
			j.put("data", mapList);
		}
		return j;
	}

	/**
	 * 获取某日的日程详情
	 *
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping(value = "getTodayCalendarList", method = RequestMethod.GET)
	public AjaxJson getTodayCalendarList(HttpServletRequest request, HttpServletResponse response,
										 RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson json = new AjaxJson();
		String calendarIds = request.getParameter("calendarIds");
		String ids[] = calendarIds.split(",");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<MyCalendar> MycalendarList = new ArrayList<MyCalendar>();
		for (int i = 0; i < ids.length; i++) {
			MycalendarList.add(myCalendarDao.get(ids[i]));
		}
		for (MyCalendar my : MycalendarList) {
			Map<String, Object> map = Maps.newHashMap();
			if (my != null) {
				map.put("calendarId", my.getId());
				map.put("title", my.getTitle());
				map.put("start", my.getStart());
				map.put("end", my.getEnd());
				map.put("location", my.getLocation());
				map.put("notice", my.getNotice());
				map.put("companyId", my.getCompanyId());
				mapList.add(map);
			}
			// my.setUser(null); // 返回值内去掉user内容
		}
		if (mapList == null) {
			json.setSuccess(false);
			json.setErrorCode(ErrorCode.code_2004);
			json.setMsg("获取当日日程失败");
			json.put("data", mapList);
		} else {
			json.setMsg("获取当日日程成功");
			json.put("data", mapList);
			json.setErrorCode(ErrorCode.code_1004);
		}
		return json;

	}

	/**
	 * 获取某日日程2
	 */

	@ResponseBody
	@RequestMapping(value = "getCalendarByDate", method = RequestMethod.GET)
	public AjaxJson getCalendarByDate(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		MyCalendar myCalendar = new MyCalendar();
		String date = request.getParameter("date");
		User user = UserUtils.getUser();
		String str[] = date.split("-");
		myCalendar.setUser(user);
		myCalendar.setStart(date+" 23:59:59");
		myCalendar.setEnd(date+" 00:00:00");
		myCalendar.setCompanyId(UserUtils.getSelectCompany().getId());
		List<MyCalendar> list = myCalendarService.findListByDate(myCalendar);
		List<Map<String, Object>> mapList = Lists.newArrayList();
		if (list != null && !list.isEmpty()) {
			for (MyCalendar my : list) {
				Map<String, Object> map = Maps.newHashMap();
				if (my != null) {
					map.put("calendarId", my.getId());
					map.put("title", my.getTitle());
					map.put("start", my.getStart());
					map.put("end", my.getEnd());
					map.put("location", my.getLocation());
					map.put("notice", my.getNotice());
					map.put("companyId", my.getCompanyId());
					mapList.add(map);
				}
			}
			if (str.length == 3) {
				if (str[1].length() == 2) {
					if (str[2].length() == 2) {
						j.put("data", mapList);
						j.setMsg("获取当日日程成功");
						j.setErrorCode(ErrorCode.code_1004);
					} else {
						j.setMsg("获取当日日程失败");
						j.put("data", Lists.newArrayList());
						j.setErrorCode(ErrorCode.code_2005);
						j.setSuccess(false);
					}
				} else {
					j.setMsg("获取当日日程失败");
					j.put("data", Lists.newArrayList());
					j.setErrorCode(ErrorCode.code_2005);
					j.setSuccess(false);
				}
			} else {
				j.setMsg("获取当日日程失败");
				j.put("data", Lists.newArrayList());
				j.setErrorCode(ErrorCode.code_2005);
				j.setSuccess(false);
			}
		} else {
			j.setMsg("今日无日程");
			j.put("data", Lists.newArrayList());
			j.setErrorCode(ErrorCode.code_1004);
		}
		return j;

	}

	/**
	 * 获取日程详情
	 *
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getCalendarDetail", method = RequestMethod.GET)
	public AjaxJson getCalendarDetail(HttpServletRequest request, HttpServletResponse response,
									  RedirectAttributes redirectAttributes) {
		AjaxJson json = new AjaxJson();
		String calendarId = request.getParameter("calendarId");
		MyCalendar g = myCalendarDao.get(calendarId);
		g.setUser(null);
		json.put("data", g);
		json.setErrorCode(ErrorCode.code_1004);
		return json;

	}

	/**
	 * 删除日程
	 *
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "deleteCalendar", method = RequestMethod.GET)
	public AjaxJson deleteCalendar(HttpServletRequest request, HttpServletResponse response,
								   RedirectAttributes redirectAttributes) {
		AjaxJson json = new AjaxJson();
		String calendarId = request.getParameter("calendarId");
		MyCalendar mycalendar = new MyCalendar();
		mycalendar = myCalendarDao.get(calendarId);
		if (calendarId != null && !calendarId.equals("") && mycalendar != null) {
			myCalendarDao.delete(mycalendar);
			json.setMsg("删除成功");
			json.put("data", "success");
			json.setErrorCode(ErrorCode.code_1004);
		} else {
			json.setMsg("删除失败");
			json.put("data", "false");
			json.setErrorCode(ErrorCode.code_2006);
			json.setSuccess(false);
		}
		return json;
	}

	/**
	 * 新增日程,修改日程
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "saveCalendar", method = RequestMethod.POST)
	public AjaxJson addCalendar(HttpServletRequest request, HttpServletResponse response)throws Exception {
		AjaxJson j = new AjaxJson();
		HashMap<String, String> requestMap = findRequestMap(request);

		MyCalendar myCalendar = myCalendarService.saveCalendar(requestMap);

		j.put("date", myCalendar.getStart());
		j.setMsg("操作日程成功");
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}
}
