/**
 * 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.List;
import java.util.Objects;

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

import org.apache.shiro.authz.annotation.RequiresPermissions;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.cku.oa.contest.service.ContestJudgeTypeClassService;
import com.cku.oa.show.entity.ChildShows;
import com.cku.oa.show.entity.MainShows;
import com.cku.oa.show.entity.ShowJudge;
import com.cku.oa.show.entity.ShowMainJudgeInfo;
import com.cku.oa.show.service.ChildShowsService;
import com.cku.oa.show.service.MainShowsService;
import com.cku.oa.show.service.ShowJudgeService;
import com.cku.oa.show.service.ShowMainJudgeInfoService;
import com.cku.util.DateUtils;
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.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 犬展子表Controller
 * @author lgl
 * @version 2016-07-13
 */
@Controller
@RequestMapping(value = "${adminPath}/show.child/childShows")
public class ChildShowsController extends BaseController {

	@Autowired
	private ChildShowsService childShowsService;
	@Autowired
	private MainShowsService mainShowsService;
	@Autowired
	private ShowJudgeService showJudgeService;
	@Autowired
	private ContestJudgeTypeClassService contestJudgeTypeClassService;
	@Autowired
	private ShowMainJudgeInfoService showMainJudgeInfoService;
	

	private final static String AUTHORITY_PRDFIX = "show.child:childShows:";

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

	@RequiresPermissions(AUTHORITY_PRDFIX+"view")
	@RequestMapping(value = {"list", ""})
	public String list(ChildShows childShows, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ChildShows> page = childShowsService.findPage(new Page<ChildShows>(request, response), childShows);
		model.addAttribute("page", page);
		
		User loginUser = UserUtils.getLoginUser();
		model.addAttribute("btnRefreshLastYear", !Objects.isNull(loginUser)  
				&& "18bab1fdef584d76a773c8c5816fc552".equals(loginUser.getId()));
		return "oa/show/child/childShowsList";
	}
//
//	@RequiresPermissions(AUTHORITY_PRDFIX+"view")
//	@RequestMapping(value = "form")
//	public String form(ChildShows childShows, Model model) {
//		List<MainShows> mainShowsList = mainShowsService.findAllMainShows();
//		model.addAttribute("mainShowsList", mainShowsList);
//		model.addAttribute("childShows", childShows);
//		return "oa/show/child/childShowsForm";
//	}

//	@RequiresPermissions(AUTHORITY_PRDFIX+"edit")
//	@RequestMapping(value = "save")
//	public String save(ChildShows childShows, Model model, RedirectAttributes redirectAttributes) {
//		if (!beanValidator(model, childShows)){
//			return form(childShows, model);
//		}
//		childShowsService.save(childShows);
//		addMessage(redirectAttributes, "保存犬展成功");
//		return "redirect:"+Global.getAdminPath()+"oa/show/child/childShows/?repage";
//	}

	@RequiresPermissions(AUTHORITY_PRDFIX+"delete")
	@RequestMapping(value = "delete")
	public String delete(ChildShows childShows, RedirectAttributes redirectAttributes) {
		childShowsService.delete(childShows);
		addMessage(redirectAttributes, "删除犬展成功");
		return "redirect:"+Global.getAdminPath()+"oa/showchild/childShows/?repage";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX+"view")
	@RequestMapping(value = "form")
	public String form(MainShows mainShows, Model model) {
		List<ShowJudge> showJudgeList = showJudgeService.findAllShowJudge();
		model.addAttribute("showJudgeList", showJudgeList);
		//赛场赛制类型
		model.addAttribute("contestJudgeTypeList", contestJudgeTypeClassService.getJudgeTypeList());
		if(mainShows.getId()!=null){
			ChildShows childShows = childShowsService.get(mainShows.getId());
			mainShows = mainShowsService.get(childShows.getMainShowId());
			mainShows.setChildShowsList(childShowsService.findChildShowsByMainShowId(mainShows.getId()));
			if(mainShows.getOrgnizeType().equals("0") && mainShows.getBusinessModelFlag().equals("0")){
				mainShows.setOrgnizeTypeAndModelFlag("0");
			}else if(mainShows.getOrgnizeType().equals("0") && mainShows.getBusinessModelFlag().equals("1")){
				mainShows.setOrgnizeTypeAndModelFlag("2");
			}else{
				mainShows.setOrgnizeTypeAndModelFlag(mainShows.getOrgnizeType());
			}
		}
		model.addAttribute("mainShows", mainShows);
		model.addAttribute("showFeeTemplate", childShowsService.getShowFeeTemplate());
		return "oa/show/child/childShowsViewForm";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX+"add")
	@RequestMapping(value = "add")
	public String add(MainShows mainShows, Model model) {
		List<ShowJudge> showJudgeList = showJudgeService.findAllShowJudge();
		model.addAttribute("showJudgeList", showJudgeList);
		model.addAttribute("childShowsId", mainShows.getId());
		//赛场赛制类型
		model.addAttribute("contestJudgeTypeList", contestJudgeTypeClassService.getJudgeTypeList());
		if(mainShows.getId()!=null){
			ChildShows childShows = childShowsService.get(mainShows.getId());
			mainShows = mainShowsService.get(childShows.getMainShowId());
			mainShows.setChildShowsList(childShowsService.findChildShowsByMainShowId(mainShows.getId()));
			if("0".equals(mainShows.getOrgnizeType()) && "0".equals(mainShows.getBusinessModelFlag())){
				mainShows.setOrgnizeTypeAndModelFlag("0");//合办旧模式
			}else if("0".equals(mainShows.getOrgnizeType()) && "1".equals(mainShows.getBusinessModelFlag())){
				mainShows.setOrgnizeTypeAndModelFlag("2");//合办新模式
			}else{//1、自办 3、合办新模式2025
				mainShows.setOrgnizeTypeAndModelFlag(mainShows.getOrgnizeType());
			}
			//犬展裁判附件信息
			List<ShowMainJudgeInfo> judgeInfoList  =showMainJudgeInfoService.findListByShowMainId(mainShows.getId());
			mainShows.setJudgeInfoList(judgeInfoList);
		}
		model.addAttribute("mainShows", mainShows);
		model.addAttribute("showFeeTemplate", childShowsService.getShowFeeTemplate());
		//主办单位在2022年1月5号之后创建的犬展使用新版
		model.addAttribute("organizerNewDate", DateUtils.strToDate("2022-01-05"));
		model.addAttribute("organizerNewDate2", DateUtils.strToDate("2023-04-23"));
		return "oa/show/child/childShowsAdd";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX+"add")
	@RequestMapping(value = "saveMain")
	public String saveMain(MainShows mainShows, Model model, RedirectAttributes redirectAttributes) {
		logger.info("举办方式"+mainShows.getOrgnizeType());
		logger.info("主办单位"+mainShows.getOrganizer());
		logger.info("报名结束日期"+mainShows.getClosingTime());
		logger.info("犬展报名"+mainShows.getRegister());
		logger.info("犬只上限只数"+mainShows.getDogNumMax());
		logger.info("犬展地点"+mainShows.getShowLocation());
		logger.info("裁判"+mainShows.getReferee());
		logger.info("子犬展size"+mainShows.getChildShowsList().size());
		for(ChildShows childShows:mainShows.getChildShowsList()){
			logger.info("犬展编号"+childShows.getShowCode());
			logger.info("犬展名称"+childShows.getShowName());
			logger.info("赛制"+childShows.getShowRules());
			logger.info("报名费"+childShows.getFee());
			logger.info("-----------------------------------------");
		}

//		if (!beanValidator(model, mainShows)){
//			return add(mainShows, model);
//		}
		try { 
			// orgnizeTypeAndModelFlag 0:合办旧模式 1:自办 2: 合办新模式
			String orgnizeTypeAndModelFlag = mainShows.getOrgnizeTypeAndModelFlag();
			if(StringUtils.isNotBlank(orgnizeTypeAndModelFlag) && orgnizeTypeAndModelFlag.equals("2")){
				mainShows.setOrgnizeType("0");
				mainShows.setBusinessModelFlag("1");
			}else if(StringUtils.isNotBlank(orgnizeTypeAndModelFlag) && orgnizeTypeAndModelFlag.equals("0")){
				mainShows.setOrgnizeType("0");
				mainShows.setBusinessModelFlag("0");
			}else{
				mainShows.setBusinessModelFlag("0");
				mainShows.setOrgnizeType(orgnizeTypeAndModelFlag);
			}
			mainShows.setIsShowType(null==mainShows.getIsShowType()?"1":mainShows.getIsShowType());
			childShowsService.saveMainShows(mainShows);
			addMessage(redirectAttributes, "保存主子表成功");
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "保存犬展信息失败:"+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/show.child/childShows/list";
	}

	/**
	 * 导入犬展信息
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions(AUTHORITY_PRDFIX+"add")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			//犬展信息导入
			childShowsService.importShows(file);
			addMessage(redirectAttributes, "导入犬展信息成功！");
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入犬展信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/show.child/childShows/?repage";
    }

	/**
	 * 下载导入犬展信息模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions(AUTHORITY_PRDFIX+"view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "犬展信息导入模板.xlsx";
    		List<ChildShows> list = Lists.newArrayList();
    		ChildShows childShows = new ChildShows();
			childShows.setOrgnizeType("合办旧模式");
			childShows.setOrganizer("北京");
			childShows.setShowRules("全犬种");
			childShows.setShowCode("201637-北京-00");
			childShows.setFee("380");
			childShows.setStartTime(DateUtils.strToDateLong("2016-08-05 09:00:00"));
			childShows.setEndTime(DateUtils.strToDateLong("2016-08-05 17:00:00"));
			childShows.setShowName("2016年CKU希可优全犬种FCI国际冠军展（CACIB）7月2日");
			childShows.setShowLocation("北京平谷 - 7月2日-7月4日（平谷金佳骏犬业有限公司）");
			childShows.setClosingTime(DateUtils.strToDateLong("2016-08-01 15:00:00"));
			childShows.setRegister("1");
			childShows.setMainShowName("北京优生繁育展（晚场犬展）");
			childShows.setDogNumMax("180");
			childShows.setBranchShowDetail("平谷金佳骏犬业有限公司");
			childShows.setAttention("1、应北京检疫部门要求，所有参展选手需要携带《检疫证》！！2、所有在犬展活动现场埋植芯片、国外换发和场外鉴定都需要带《检疫证》和《狂犬牌》");
			childShows.setUseCoupon("是");
			childShows.setYear("2020");
    		list.add(childShows);
    		new ExportExcel("犬展信息", ChildShows.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/show.child/childShows/?repage";
    }

}