/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.cku.oa.show.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.cku.oa.dog.entity.Dog;
import com.cku.oa.dog.service.DogService;
import com.cku.oa.finance.service.PaymentChargingItemService;
import com.cku.oa.finance.service.PaymentOrderService;
import com.cku.oa.show.entity.ChildShows;
import com.cku.oa.show.entity.MainShows;
import com.cku.oa.show.entity.ShowApply;
import com.cku.oa.show.entity.ShowSortGroup;
import com.cku.oa.show.service.ChildShowsService;
import com.cku.oa.show.service.MainShowsService;
import com.cku.oa.show.service.ShowApplyService;
import com.cku.oa.show.vo.ShowApplyVO;
import com.cku.oa.sys.entity.user.Member;
import com.cku.oa.sys.service.user.MemberService;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;

import net.sf.json.JSONObject;

/**
 * 犬展报名表Controller
 *
 * @author lgl
 * @version 2016-07-15
 */
@Controller
@RequestMapping(value = "${adminPath}/apply/showApply")
public class ShowApplyController extends BaseController {

	@Autowired
	private ShowApplyService showApplyService;
	@Autowired
	private ChildShowsService childShowsService;
	@Autowired
	private MainShowsService mainShowsService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private DogService dogService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private PaymentChargingItemService paymentChargingItemService;

	private final static String AUTHORITY_PRDFIX = "apply:showApply:";

	@ModelAttribute
	public ShowApply get(@RequestParam(required = false) String id) {
		ShowApply entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = showApplyService.get(id);
		}
		if (entity == null) {
			entity = new ShowApply();
		}
		return entity;
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "view")
	@RequestMapping(value = { "list", "" })
	public String list(ShowApply showApply, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ShowApply> page = showApplyService.findPage(new Page<ShowApply>(request, response), showApply);
		for (ShowApply sa : page.getList()) {
			Member member = memberService.getByMemberCode(sa.getDogOwnerMemberCode());
			if (member != null) {
				sa.setAccountBalance(member.getAccountBalance());
			}
			// 对于2025新合办的记录特殊处理，需要关联多个shortName结果出来
			if(StringUtils.isNotEmpty(sa.getPaymentChargingItemId()) 
					&& sa.getPaymentChargingItemId().contains(",")) {
				sa.setShortName(paymentChargingItemService.getShortNames(sa.getPaymentChargingItemId()));
			}
		}
		// 查询有没有退款或退款中 fmdog_breed_certified_code
		Map<String, String> map = paymentOrderService.getRefundStateByBusinessId(page.getList().stream()
				.map(a -> a.getId() + "#" + a.getPedigreeCertified()).collect(Collectors.toSet()));
		List<ShowApply> list = page.getList().stream().map(a -> {
			ShowApplyVO b = new ShowApplyVO();
			BeanUtils.copyProperties(a, b);
			b.setBusinessRefundState(map.keySet().contains(a.getId() + "#" + a.getPedigreeCertified()));
			return b;
		}).collect(Collectors.toList());
		page.setList(list);
		model.addAttribute("page", page);
		if (!SecurityUtils.getSubject().isPermitted("apply:showApply:viewAll")) {
			model.addAttribute("page", showApplyService.transformPage(page));
		}
		return "oa/show/apply/showApplyList";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "view")
	@RequestMapping(value = "form")
	public String form(ShowApply showApply, Model model) {
		List<MainShows> mainShowsList = mainShowsService.findUnCloseMainShows(null, null, null, null, null);
		model.addAttribute("mainShowsList", mainShowsList);
		List<ChildShows> childShowsList = Lists.newArrayList();
		model.addAttribute("childShowsList", childShowsList);
		// if(StringUtils.isNotBlank(showApply.getId())){
		// //回显年龄组别
		// String ageGroupList =
		// showApplyService.getAgeGroupListString(showApply.getId());
		// model.addAttribute("ageGroupList", ageGroupList);
		// }
		// 记录修改人
		if (showApply.getUpdateBy() != null && StringUtils.isNotBlank(showApply.getUpdateBy().getId())) {
			User updateUser = userDao.get(showApply.getUpdateBy().getId());
			showApply.setUpdateBy(updateUser);
		}
		model.addAttribute("showApply", showApply);
		// 回显年龄组别
		String ageGroups = showApply.getAgeGroup();
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isNotBlank(ageGroups) && ageGroups.contains(",")) {
			String[] ageGroupArray = ageGroups.split(",");
			for (String ageGroup : ageGroupArray) {
				sb.append(DictUtils.getDictLabel(ageGroup, "show_age_group", "")).append(",");
			}
		} else {
			String label = DictUtils.getDictLabel(ageGroups, "show_age_group", "");
			String[] showCodeArray = showApply.getShowCode().split(",");
			for (int i = 0, len = showCodeArray.length; i < len; i++) {
				sb.append(label).append(",");
			}
		}
		sb.deleteCharAt(sb.length() - 1);
		showApply.setAgeGroup(sb.toString());
		StringBuilder sb2 = new StringBuilder();
		if (StringUtils.isNotBlank(showApply.getIsOwner())) {
			String[] isOwners = showApply.getIsOwner().split(",");
			for (String isOwnerT : isOwners) {// 是否为犬主人组： 是：1、否：0
				sb2.append(StringUtils.isNoneBlank(isOwnerT) && "1".equals(isOwnerT)?"犬主人组":" ").append(",");
			}
		}
		sb2.deleteCharAt(sb2.length() - 1);
		showApply.setIsOwner(sb2.toString());
		return "oa/show/apply/showApplyForm";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "edit")
	@RequestMapping(value = "editForm")
	public String editForm(ShowApply showApply, Model model) {
		List<MainShows> mainShowsList = mainShowsService.findUnCloseMainShows(null, null, null, null, null);
		model.addAttribute("mainShowsList", mainShowsList);
		List<ChildShows> childShowsList = Lists.newArrayList();
		model.addAttribute("childShowsList", childShowsList);
		// if(StringUtils.isNotBlank(showApply.getId())){
		// //回显年龄组别
		// String ageGroupList =
		// showApplyService.getAgeGroupListString(showApply.getId());
		// model.addAttribute("ageGroupList", ageGroupList);
		// }
		// 记录修改人
		if (showApply.getUpdateBy() != null && StringUtils.isNotBlank(showApply.getUpdateBy().getId())) {
			User updateUser = userDao.get(showApply.getUpdateBy().getId());
			showApply.setUpdateBy(updateUser);
		}
		model.addAttribute("showApply", showApply);
		// 回显
		if (StringUtils.isNotBlank(showApply.getId())) {
			Dog dog = dogService.getByPedigreeCertifiedCode(showApply.getPedigreeCertified());
			if (dog != null) {
				JSONObject jo = showApplyService.getAgeGroupListString(showApply.getMainShowId(), dog, "0");
				model.addAttribute("ageGroupArray", jo.get("ageGroupArray"));
			}
		}
		return "oa/show/apply/showApplyEditForm";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "edit")
	@RequestMapping(value = "expireByMainShowId")
	@ResponseBody
	public Object expireByMainShowId(@RequestParam(required = true) String mainShowId) {
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			showApplyService.expireByMainShowId(mainShowId);
			map.put("rc", "0");
		} catch (Exception e) {
			map.put("rc", "1");
			map.put("msg", e.getMessage());
		}
		return map;
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "add")
	@RequestMapping(value = "save")
	public String save(ShowApply showApply, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, showApply)) {
			return form(showApply, model);
		}
		String msg = "保存犬展报名表成功";
		try {
			Dog dog = dogService.getByPedigreeCertifiedCode(showApply.getPedigreeCertified());
			showApply.setDogName(dog.getNameEn());
			showApplyService.saveShowApply(showApply);
		} catch (Exception e) {
			logger.info("保存犬展报名失败", e);
			msg = "保存犬展报名失败:" + e.getMessage();
		}
		addMessage(redirectAttributes, msg);
		return "redirect:" + Global.getAdminPath() + "/apply/showApply/?repage";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "delete")
	@RequestMapping(value = "delete")
	public String delete(ShowApply showApply, RedirectAttributes redirectAttributes) {
		try {
			showApplyService.delete(showApply);
			addMessage(redirectAttributes, "删除犬展报名表成功");
		} catch (Exception e) {
			addMessage(redirectAttributes, "删除犬展报名表失败：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/apply/showApply/?repage";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "view")
	@RequestMapping(value = "findChildShowsByMainShowId")
	@ResponseBody
	public List<ChildShows> findChildShowsByMainShowId(String mainShowId) {
		if (StringUtils.isBlank(mainShowId)) {
			return Lists.newArrayList();
		}
		return childShowsService.findChildShowsByMainShowId(mainShowId);
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "add")
	@RequestMapping(value = "calculateShowApplyFee")
	@ResponseBody
	public String calculateShowApplyFee(String showCodes, String pedigreeCertified) throws Exception {
		ShowApply showApply = new ShowApply();
		showApply.setShowCode(showCodes);
		showApply.setPhoneApplyFlag("0");
		showApply.setPedigreeCertified(pedigreeCertified);
		return showApplyService.calculateShowApplyFee(showApply);
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "add")
	@RequestMapping(value = "setShowApplyInfo")
	@ResponseBody
	public Map<String, Object> setShowApplyInfo(String mainShowId, String pedigreeCertified, String showCode) {
		Map<String, Object> map = null;
		try {
			map = showApplyService.setShowApplyInfo(mainShowId, pedigreeCertified, showCode);
		} catch (Exception e) {
			logger.warn("设置参展信息出错", e);
		}
		return map;
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "add")
	@RequestMapping(value = "getHandlerInfo")
	@ResponseBody
	public String getHandlerInfo(String handlerMemberCode, String pedigreeCertified) {
		Member handlerMember = memberService.getByMemberCode(handlerMemberCode);
		String result = "";
		Dog dog = dogService.getByPedigreeCertifiedCode(pedigreeCertified);
		if (handlerMember != null) {
			result = handlerMember.getName() + " " + handlerMember.getMobile();
			Member member = memberService.getByMemberCode(dog.getMemberCode());
			if (member != null && !handlerMemberCode.equals(member.getMemberCode())) {
				result = member.getMobile() + " " + result;
			}
		}
		return result;
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "edit")
	@RequestMapping(value = "updateRefundAbsenceFlag")
	public String updateRefundAbsenceFlag(ShowApply showApply, RedirectAttributes redirectAttributes) {
		showApplyService.updateRefundAbsenceFlag(showApply);
		addMessage(redirectAttributes, "更新状态成功");
		return "redirect:" + Global.getAdminPath() + "/apply/showApply/form?id=" + showApply.getId();
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "edit")
	@RequestMapping(value = "export")
	public String export(String showCodePrefix, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			showApplyService.export(showCodePrefix, response);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出犬展信息失败！失败信息：" + e.getMessage());
		}
		return null;
	}

	@Autowired
	private PaymentOrderService paymentOrderService;

	@RequiresPermissions("finance:paymentOrder:orderItem")
	@RequestMapping(value = "orderList")
	public String orderList(ShowApply showApply, Model model) {
		List<ShowApply> list = showApplyService.findList(showApply);
		// 查询有没有退款或退款中
		Map<String, String> map = paymentOrderService.getRefundStateByBusinessId(
				list.stream().map(a -> a.getId() + "#" + a.getPedigreeCertified()).collect(Collectors.toSet()));
		List<ShowApplyVO> list2 = list.stream().map(a -> {
			ShowApplyVO b = new ShowApplyVO();
			BeanUtils.copyProperties(a, b);
			b.setBusinessRefundState(map.keySet().contains(a.getId() + "#" + a.getPedigreeCertified()));
			return b;
		}).collect(Collectors.toList());
		model.addAttribute("list", list2);
		return "oa/show/apply/showApplyOrderList";
	}

	/**
	 * @description: 获取数据集合
	 * @author: cuihuaiyu
	 * @date: 2018年1月25日 上午10:41:25
	 */
	@RequiresPermissions(AUTHORITY_PRDFIX + "view")
	@RequestMapping(value = "/getExportlist")
	public String getExportlist(HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		String showCodePrefix = request.getParameter("showCodePrefix");
		List<ShowApply> list = new ArrayList<ShowApply>();
		try {
			list = showApplyService.getShowApply(showCodePrefix);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出犬展信息失败！失败信息：" + e.getMessage());
		}
		model.addAttribute("list", list);
		return "oa/show/apply/showApply/exportApplyList";
	}

	// 在线编辑数据
	// @RequiresPermissions(AUTHORITY_PRDFIX+"edit")
	// @RequestMapping(value = "updateRefundAbsence")
	// public String updateRefundAbsence(ShowApply showApply, RedirectAttributes
	// redirectAttributes) {
	// try {
	// showApplyService.updateRefundAbsence(showApply);
	// } catch (Exception e) {
	// addMessage(redirectAttributes, "犬展保存失败！失败信息："+e.getMessage());
	// }
	// return "oa/show/apply/showApply/exportApplyList";
	// }

	@RequiresPermissions(AUTHORITY_PRDFIX + "edit")
	@RequestMapping(value = "/exportScoreBlank")
	public void exportScoreBlank(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			String showCodePrefix = request.getParameter("showCodePrefix");
			showApplyService.exportScoreBlank(showCodePrefix, file, response);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出犬展信息失败！失败信息：" + e.getMessage());
		}
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "view")
	@RequestMapping(value = "/groupByShowApply")
	@ResponseBody
	public List<ShowSortGroup> groupByShowApply(String showCodePrefix) throws Exception {
		List<ShowApply> list = showApplyService.getShowApply(showCodePrefix);
		return showApplyService.groupByShowApply(list);
	}

	@RequiresPermissions(AUTHORITY_PRDFIX + "view")
	@RequestMapping(value = "/showApplyConflict")
	@ResponseBody
	public List<ShowApply> showApplyConflict(String showCodePrefix) throws Exception {
		List<ShowApply> list = showApplyService.getShowApply(showCodePrefix);
		return showApplyService.checkShowApplyConflict(list);
	}

	/**
	 * @description: 后台导出数据
	 * @author: cuihuaiyu
	 * @date: 2018年1月25日 上午10:41:25
	 */
	@RequiresPermissions(AUTHORITY_PRDFIX + "edit")
	@RequestMapping(value = "/exportBs")
	public void exportBs(HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) throws Exception {
		String showCodePrefix = request.getParameter("showCodePrefix");
		List<ShowApply> list = null;
		try {
			list = showApplyService.getShowApply(showCodePrefix);
			// 导出
			new ExportExcel(showCodePrefix + "犬展报名", ShowApply.class, 2).setDataList(list)
					.write(response, showCodePrefix + "犬展报名.xlsx").dispose();
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导出犬展信息失败！失败信息：" + e.getMessage());
		}
	}

}