package com.cku.oa.statistics.web;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cku.oa.dog.entity.Dog;
import com.cku.oa.dog.service.DogService;
import com.cku.oa.show.dao.ShowApplyDao;
import com.cku.oa.statistics.dao.ActivityRegisterDao;
import com.cku.oa.statistics.entity.GroomChildAll;
import com.cku.oa.statistics.entity.GroomChildTotalAll;
import com.cku.oa.statistics.entity.HandleChildAll;
import com.cku.oa.statistics.entity.HandleChildTotalAll;
import com.cku.oa.sys.entity.user.Member;
import com.cku.oa.sys.service.user.MemberService;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.modules.sys.entity.User;

/**
 * 活动统计
 * 
 * @author xuzhenxing
 *
 */

@Controller
@RequestMapping(value = "${adminPath}/statistics/activity")
public class ActivityRegisterController {

	@Autowired
	private ActivityRegisterDao activityRegisterDao;

	@Autowired
	private MemberService memberService;

	@Autowired
	private DogService dogService;

	@Autowired
	private ShowApplyDao showApplyDao;

	/**
	 * 报名信息统计
	 * 
	 * @throws ParseException
	 */
	@RequestMapping(value = "showRegister")

	public String activityRegister(HttpServletRequest request, HttpServletResponse response, Model model)
			throws ParseException {
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String organizeType = request.getParameter("organize");
		String showCode = request.getParameter("showCode");
		String isOnSubmit = request.getParameter("isOnSubmit");

		// 从页面的参数中获取当前的页码等信息
		Page<User> page = new Page<>(request, response);
		// 每页的大小
		page.setPageSize(2);
		// 设置默认查询日期
		if (StringUtils.isBlank(isOnSubmit)) {
			int year = Calendar.getInstance().get(Calendar.YEAR);
			if (StringUtils.isBlank(startDate)) {
				startDate = String.valueOf(year) + "-01-01 00:00:00";
			}
			if (StringUtils.isBlank(endDate)) {
				endDate = String.valueOf(year) + "-12-31 23:59:59";
			}
		}

		Map<String, Object> countTotal = activityRegisterDao.countTotal(showCode, startDate, endDate, organizeType);
		Map<String, Object> countTotalFee = activityRegisterDao.countTotalFee(showCode, startDate, endDate,
				organizeType);
		// showRegister.jsp页面中的子赛事详情查询
		Map<String, Map<String, Object>> showDetails = new HashMap<>(1 << 4);
		List<Map> showMainID = activityRegisterDao.showMainID(showCode, startDate, endDate, organizeType,
				(page.getPageNo() - 1) * page.getPageSize(), page.getPageSize());
		BigDecimal totalHandlingFee = BigDecimal.ZERO;
		for (int i = 0; i < showMainID.size(); i++) {
			String id = (String) showMainID.get(i).get("id");
			Map<String, Object> content = new HashMap<>(1 << 4);
			List<Map<String, Object>> showChild = activityRegisterDao.showChild(id);
			Map<String, Object> showChildTotal = activityRegisterDao.showChildTotal(id);

			List<Map<String, Object>> showChildResult = new ArrayList();
			for (Map<String, Object> map : showChild) {
				Map<String, Integer> childShowInfo = showApplyDao.countByShowCode((String) map.get("show_code"));
				map.put("numOfSubShow", childShowInfo.get("countAll"));
				map.put("pubbyCount", childShowInfo.get("pubbyCount"));
				map.put("adultDogCount", childShowInfo.get("adultDogCount"));
				String showName = (String) map.get("show_name");
				map.put("show_name", StringEscapeUtils.unescapeHtml4(showName));
				showChildResult.add(map);
			}

			Map<String, Object> showAppraisal = null;
			if (!CollectionUtils.isEmpty(showChild)) {
				showAppraisal = activityRegisterDao.showAppraisal(showChild.get(0).get("show_code").toString());
			}
			// 查询赛事退赛手续费金额及数量x`
			Map<String, BigDecimal> showRefundHandlingFee = activityRegisterDao.showRefundHandlingFee(id);
			// 修改退费总金额
			BigDecimal handlingFee = showRefundHandlingFee.get("refundHandlingFee");
			totalHandlingFee = totalHandlingFee.add(handlingFee);
			content.put("details", showChildResult);
			content.put("countAll", showChildTotal);
			content.put("appraisal", showAppraisal);
			content.put("handlingFee", showRefundHandlingFee);
			showDetails.put(id, content);
		}
		// 修改总收入，加上手续费
		countTotalFee.put("feeOfShow",
				new BigDecimal(countTotalFee.get("feeOfShow").toString()).add(totalHandlingFee).toString());
		// 返回showRegister.jsp页面上部的总记查询结果
		model.addAttribute("countTotal", countTotal);
		model.addAttribute("countTotalFee", countTotalFee);
		// 返回showRegister.jsp页面中的子赛事详细查询结果
		model.addAttribute("showDetails", showDetails);
		// 返回从页面接收到的值
		model.addAttribute("organize", organizeType);
		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("showCode", showCode);
		// 返回分页信息
		page.setCount(Integer.parseInt(countTotal.get("numOfMainShow").toString())); // 总条数
		page.initialize();// 初始化
		model.addAttribute("page", page);
		return "oa/statistics/activity/showRegister";

	}

	@RequestMapping(value = "showResult")
	public String showChildView(HttpServletRequest request, HttpServletResponse response, Model model) {
		String showCode = request.getParameter("showCode");
		List<Map> showResult = activityRegisterDao.showResult(showCode);
		model.addAttribute("showResult", showResult);
		model.addAttribute("showCode", showCode);
		return "oa/statistics/activity/showResult";
	}

	@RequestMapping(value = "dogview")
	public String showDogView(HttpServletRequest request, HttpServletResponse response, Model model) {
		String pedigreeCertified = request.getParameter("pedigreeCertified");
		Dog dog = activityRegisterDao.showDog(pedigreeCertified);
		model.addAttribute("dog", dog);
		return "oa/statistics/activity/dogView";
	}

	@RequestMapping(value = "groomRegister")
	public String groomRegister(HttpServletRequest request, HttpServletResponse response, Model model)
			throws ParseException {
		Page<User> page = new Page<User>(request, response);// 从页面的参数中获取当前的页码等信息
		page.setPageSize(20); // 每页的大小
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String showCode = request.getParameter("showCode");
		String isOnSubmit = request.getParameter("isOnSubmit");

		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);

		if (isOnSubmit == null || isOnSubmit.equals("")) {
			if (startDate == null || startDate.equals(""))
				// startDate =
				// String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day)+"
				// 00:00:00";
				startDate = String.valueOf(year) + "-01-01 00:00:00";
			if (endDate == null || endDate.equals(""))
				// endDate =
				// String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day)+"
				// 23:59:59";
				endDate = String.valueOf(year) + "-12-31 23:59:59";

		}

		Map<String, Map<String, Object>> groomDetails = new HashMap<String, Map<String, Object>>();
		int countOfGroom = activityRegisterDao.countGroom(startDate, endDate, showCode);
		Map countTotal = activityRegisterDao.groomCountTotal(startDate, endDate, showCode);
		List<String> groomMainID = activityRegisterDao.groomMainID(startDate, endDate, showCode,
				(page.getPageNo() - 1) * page.getPageSize(), page.getPageSize());

		List<GroomChildAll> groomChildAll = activityRegisterDao.groomChildAll(groomMainID);
		List<GroomChildTotalAll> groomChildTotalAll = activityRegisterDao.groomChildTotalAll(groomMainID);

		Map<String, List<GroomChildAll>> groomChildAllMap = new HashMap<>();
		Map<String, GroomChildTotalAll> groomChildTotalAllMap = new HashMap<>();
		if (!CollectionUtils.isEmpty(groomChildAll)) {
			groomChildAllMap
					.putAll(groomChildAll.stream().collect(Collectors.groupingBy(GroomChildAll::getGroomMainID)));
		}

		if (!CollectionUtils.isEmpty(groomChildTotalAll)) {
			groomChildTotalAllMap.putAll(groomChildTotalAll.stream()
					.collect(Collectors.toMap(GroomChildTotalAll::getGroomMainID, Function.identity())));
		}

		for (int i = 0; i < groomMainID.size(); i++) {
			Map<String, Object> content = new HashMap<String, Object>();
			String id = groomMainID.get(i);
			List<GroomChildAll> groomChild = groomChildAllMap.get(id);
			GroomChildTotalAll groomChildTotal = groomChildTotalAllMap.get(id);
			content.put("details", groomChild);
			content.put("countAll", groomChildTotal);
			groomDetails.put(id, content);
		}

//		for (int i = 0; i < groomMainID.size(); i++) {
//			Map<String, Object> content = new HashMap<String, Object>();
//			String id = groomMainID.get(i);
//			List<Map> groomChild = activityRegisterDao.groomChild(id);
//			Map groomChildTotal = activityRegisterDao.groomChildTotal(id);
//			content.put("details", groomChild);
//			content.put("countAll", groomChildTotal);
//			groomDetails.put(id, content);
//		}
		model.addAttribute("countTotal", countTotal);
		model.addAttribute("groomDetails", groomDetails);

		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("showCode", showCode);
		// 返回分页信息
		page.setCount(countOfGroom); // 总条数
		page.initialize();// 初始化
		model.addAttribute("page", page);
		return "oa/statistics/activity/groomRegister";
	}

	@RequestMapping(value = "handleRegister")

	public String handleRegister(HttpServletRequest request, HttpServletResponse response, Model model)
			throws ParseException {
		Page<User> page = new Page<User>(request, response);// 从页面的参数中获取当前的页码等信息
		page.setPageSize(20); // 每页的大小
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String showCode = request.getParameter("showCode");
		String isOnSubmit = request.getParameter("isOnSubmit");

		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);

		if (isOnSubmit == null || isOnSubmit.equals("")) {
			if (startDate == null || startDate.equals(""))
				// startDate =
				// String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day)+"
				// 00:00:00";
				startDate = String.valueOf(year) + "-01-01 00:00:00";
			if (endDate == null || endDate.equals(""))
				// endDate =
				// String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day)+"
				// 23:59:59";
				endDate = String.valueOf(year) + "-12-31 23:59:59";

		}

		Map<String, Map<String, Object>> handleDetails = new HashMap<String, Map<String, Object>>();
		int countOfhandle = activityRegisterDao.countHandle(startDate, endDate, showCode);
		Map countTotal = activityRegisterDao.handleCountTotal(startDate, endDate, showCode);
		List<String> handleMainID = activityRegisterDao.handleMainID(startDate, endDate, showCode,
				(page.getPageNo() - 1) * page.getPageSize(), page.getPageSize());

		List<HandleChildAll> handleChildAll = activityRegisterDao.handleChildAll(handleMainID);
		List<HandleChildTotalAll> handleChildTotalAll = activityRegisterDao.handleChildTotalAll(handleMainID);

		Map<String, List<HandleChildAll>> handleChildAllMap = new HashMap<>();
		Map<String, HandleChildTotalAll> handleChildTotalAllMap = new HashMap<>();
		if (!CollectionUtils.isEmpty(handleChildAll)) {
			handleChildAllMap
					.putAll(handleChildAll.stream().collect(Collectors.groupingBy(HandleChildAll::getHandleMainID)));
		}

		if (!CollectionUtils.isEmpty(handleChildTotalAll)) {
			handleChildTotalAllMap.putAll(handleChildTotalAll.stream()
					.collect(Collectors.toMap(HandleChildTotalAll::getHandleMainID, Function.identity())));
		}

		for (int i = 0; i < handleMainID.size(); i++) {
			Map<String, Object> content = new HashMap<String, Object>();
			String id = handleMainID.get(i);
			List<HandleChildAll> handleChild = handleChildAllMap.get(id);
			HandleChildTotalAll handleChildTotal = handleChildTotalAllMap.get(id);
			content.put("details", handleChild);
			content.put("countAll", handleChildTotal);
			handleDetails.put(id, content);
		}

//		for (int i = 0; i < handleMainID.size(); i++) {
//			Map<String, Object> content = new HashMap<String, Object>();
//			String id = handleMainID.get(i);
//			List<Map> handleChild = activityRegisterDao.handleChild(id);
//			Map handleChildTotal = activityRegisterDao.handleChildTotal(id);
//			content.put("details", handleChild);
//			content.put("countAll", handleChildTotal);
//			handleDetails.put(id, content);
//		}
//		

		model.addAttribute("countTotal", countTotal);
		model.addAttribute("handleDetails", handleDetails);

		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("showCode", showCode);
		// 返回分页信息
		page.setCount(countOfhandle); // 总条数
		page.initialize();// 初始化
		model.addAttribute("page", page);
		return "oa/statistics/activity/handleRegister";
	}

	@RequestMapping(value = "groomerView")
	public String groomerView(HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = new Page<User>(request, response);// 从页面的参数中获取当前的页码等信息
		page.setPageSize(20); // 每页的大小
		String showCode = request.getParameter("showCode");
		int countGroomer = activityRegisterDao.countGroomer(showCode);
		List<Map> groomerViewResult = activityRegisterDao.groomerView(showCode,
				(page.getPageNo() - 1) * page.getPageSize(), page.getPageSize());
		model.addAttribute("groomerView", groomerViewResult);
		model.addAttribute("showCode", showCode);
		page.setCount(countGroomer); // 总条数
		page.initialize();// 初始化
		model.addAttribute("page", page);
		return "oa/statistics/activity/groomerView";
	}

	@RequestMapping(value = "memberView")
	public String memberView(HttpServletRequest request, HttpServletResponse response, Model model) {
		String memberCode = request.getParameter("memberCode");
		Member member = memberService.getByMemberCode(memberCode);
		model.addAttribute("member", member);
		return "oa/statistics/activity/memberView";
	}

	@RequestMapping(value = "showOrderList")
	public String showOrderList(HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = new Page<User>(request, response);// 从页面的参数中获取当前的页码等信息
		page.setPageSize(20); // 每页的大小
		String orderCode = request.getParameter("orderCode");
		String memberCode = request.getParameter("memberCode");
		String showCode = request.getParameter("showCode");
		String orderPrice = request.getParameter("orderPrice");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String isOnSubmit = request.getParameter("isOnSubmit");
		String paymentState = request.getParameter("paymentState");
		String showChargeItemID = request.getParameter("chargingItemID");
		String orderType = request.getParameter("orderType");
		String refund = request.getParameter("refund");
		String absence = request.getParameter("absence");

		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);

		if (isOnSubmit == null || isOnSubmit.equals("")) {
			if (startDate == null || startDate.equals(""))
				// startDate =
				// String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day)+"
				// 00:00:00";
				startDate = String.valueOf(year) + "-01-01 00:00:00";
			if (endDate == null || endDate.equals(""))
				// endDate =
				// String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day)+"
				// 23:59:59";
				endDate = String.valueOf(year) + "-12-31 23:59:59";
		}

		Map showOrderListCount = new HashMap();
		List<Map> showOrderList = new ArrayList<Map>();
		if (orderType != null && orderType.equals("oa")) {

		} else {
			showOrderListCount = activityRegisterDao.showOrderListCount(absence, refund, orderType, showChargeItemID,
					paymentState, orderCode, memberCode, showCode, orderPrice, startDate, endDate);
			showOrderList = activityRegisterDao.showOrderList(absence, refund, orderType, showChargeItemID,
					paymentState, orderCode, memberCode, showCode, orderPrice, startDate, endDate,
					(page.getPageNo() - 1) * page.getPageSize(), page.getPageSize());
		}

		List<Map> showChargeItem = activityRegisterDao.showChargeItem();

		// 返回分页信息
		page.setCount(Integer.parseInt(showOrderListCount.get("numOfShowOrder").toString())); // 总条数
		page.initialize();// 初始化

		model.addAttribute("orderCode", orderCode);
		model.addAttribute("memberCode", memberCode);
		model.addAttribute("showCode", showCode);
		model.addAttribute("orderPrice", orderPrice);
		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("orderType", orderType);
		model.addAttribute("paymentState", paymentState);
		model.addAttribute("chargingItemID", showChargeItemID);
		model.addAttribute("showChargeItem", showChargeItem);
		model.addAttribute("showOrderList", showOrderList);
		model.addAttribute("showOrderListCount", showOrderListCount);
		model.addAttribute("refund", refund);
		model.addAttribute("absence", absence);
		model.addAttribute("page", page);
		return "oa/statistics/activity/showOrderList";
	}

	@RequestMapping(value = "handleView")
	public String handleView(HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = new Page<User>(request, response);// 从页面的参数中获取当前的页码等信息
		page.setPageSize(20); // 每页的大小
		String showCode = request.getParameter("showCode");
		int countHandleMember = activityRegisterDao.countHandleMember(showCode);
		List<Map> handleMemberView = activityRegisterDao.handleMemberView(showCode,
				(page.getPageNo() - 1) * page.getPageSize(), page.getPageSize());
		model.addAttribute("handleMemberView", handleMemberView);
		model.addAttribute("showCode", showCode);
		page.setCount(countHandleMember); // 总条数
		page.initialize();// 初始化
		model.addAttribute("page", page);
		return "oa/statistics/activity/handleView";
	}
}
