/**
 * 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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.cku.oa.dog.service.DogTypeService;
import com.cku.oa.show.entity.ChildShows;
import com.cku.oa.show.entity.ShowJudge;
import com.cku.oa.show.entity.ShowResults;
import com.cku.oa.show.service.ChildShowsService;
import com.cku.oa.show.service.ShowJudgeService;
import com.cku.oa.show.service.ShowResultsService;
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.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

import edu.emory.mathcs.backport.java.util.Arrays;


/**
 * 犬展成绩Controller
 * @author lgl
 * @version 2016-07-13
 */
@Controller
@RequestMapping(value = "${adminPath}/results/showResults")
public class ShowResultsController extends BaseController {

	@Autowired
	private ShowResultsService showResultsService;
	@Autowired
	private ChildShowsService childShowsService;
	@Autowired
	private ShowJudgeService showJudgeService;
	@Autowired
	private DogTypeService dogTypeService;
//	@Autowired
//	private ShowScoreRankingService showScoreRankingService;

	private final static String AUTHORITY_PRDFIX = "results:showResults:";
	
	@ModelAttribute
	public ShowResults get(@RequestParam(required=false) String id) {
		ShowResults entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = showResultsService.get(id);
		}
		if (entity == null){
			entity = new ShowResults();
		}
		return entity;
	}
	
	@RequiresPermissions(AUTHORITY_PRDFIX+"view")
	@RequestMapping(value = {"list", ""})
	public String list(ShowResults showResults, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ShowResults> page = showResultsService.findPage(new Page<ShowResults>(request, response), showResults);
		for(ShowResults po:page.getList()){
			if(StringUtils.isNotBlank(po.getFciCode())){
				po.setBreedCnName(dogTypeService.getBreedCnName(po.getFciCode()));
			}
		}
		model.addAttribute("page", page);
		return "oa/show/results/showResultsList";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX+"view")
	@RequestMapping(value = "form")
	public String form(ShowResults showResults, Model model) {
		List<String> showCodeList = childShowsService.findShowCodeList("0");
		model.addAttribute("showCodeList", showCodeList);
		List<ShowJudge> showJudgeList = showJudgeService.findAllShowJudge();
		model.addAttribute("showJudgeList", showJudgeList);
		model.addAttribute("showResults", showResults);
		return "oa/show/results/showResultsForm";
	}
	
	@RequiresPermissions(AUTHORITY_PRDFIX+"edit")
	@RequestMapping(value = "editForm")
	public String editForm(ShowResults showResults, Model model) {
		List<String> showCodeList = childShowsService.findShowCodeList("0");
		model.addAttribute("showCodeList", showCodeList);
		List<ShowJudge> showJudgeList = showJudgeService.findAllShowJudge();
		model.addAttribute("showJudgeList", showJudgeList);
		if(!StringUtils.isEmpty(showResults.getResultCc())) {
			showResults.setResultCcs(showResults.getResultCc().split("/"));
		}
		model.addAttribute("showResults", showResults);
		return "oa/show/results/showResultsEditForm";
	}

	@RequiresPermissions(AUTHORITY_PRDFIX+"edit")
	@RequestMapping(value = "save")
	public String save(ShowResults showResults, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, showResults)){
			return form(showResults, model);
		}
		
		if (!(showResults.getResultCcs() == null || showResults.getResultCcs().length == 0)) {
			String ccStr = "";
			for (String cc : showResults.getResultCcs()) {
				ccStr += cc + "/";
			}
			ccStr = ccStr.substring(0, ccStr.length() - 1);
			showResults.setResultCc(ccStr);
		} else {
			showResults.setResultCc(null);
		}
		
		showResultsService.save(showResults);
		addMessage(redirectAttributes, "保存犬展成绩成功");
		return "redirect:"+Global.getAdminPath()+"/results/showResults/?repage";
	}
	
	@RequiresPermissions(AUTHORITY_PRDFIX+"delete")
	@RequestMapping(value = "delete")
	public String delete(ShowResults showResults, RedirectAttributes redirectAttributes) {
		showResultsService.delete(showResults);
		addMessage(redirectAttributes, "删除犬展成绩成功");
		return "redirect:"+Global.getAdminPath()+"/results/showResults/?repage";
	}

	/**
	 * 导入犬展成绩数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions(AUTHORITY_PRDFIX+"add")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int count = showResultsService.importShowResults(file);
			addMessage(redirectAttributes,"导入犬展成绩成功，共导入"+count+"条记录。");
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入犬展成绩失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/results/showResults/?repage";
    }
	
	/**
	 * 
	 * @description: 计算犬展积分
	 * @author: laiguanglong
	 * @date: 2016年11月23日 下午4:32:02
	 */
	@RequiresPermissions(AUTHORITY_PRDFIX+"statistics")
	@RequestMapping(value = "updateShowResult", method=RequestMethod.GET)
	@ResponseBody
	public String updateShowResult(@RequestParam(required=true) String id, RedirectAttributes redirectAttributes) {
		try {
			ChildShows childShows = childShowsService.get(id);
			showResultsService.countShowResult(childShows.getShowCode());
		} catch (Exception e) {
			return "{\"rc\":1,\"msg\":\""+e.getMessage()+"\"}";
		}
			
		return "{\"rc\":0}";
	}
	
	
	

	@RequiresPermissions(AUTHORITY_PRDFIX+"statistics")
	@RequestMapping(value = "refreshLastYear", method=RequestMethod.GET)
	public String refreshLastYear(ShowResults showResults, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		User loginUser = UserUtils.getLoginUser();
		if(!Objects.isNull(loginUser)  
				&& "18bab1fdef584d76a773c8c5816fc552".equals(loginUser.getId())) {
			return "oa/show/child/refreshLastYearForm";
		}
		return "";
	}
	
	@SuppressWarnings("unchecked")
	@RequiresPermissions(AUTHORITY_PRDFIX+"statistics")
	@RequestMapping(value = "refreshLastYearSave", method=RequestMethod.POST)
	@ResponseBody
	public String refreshLastYearSave(ShowResults showResults, RedirectAttributes redirectAttributes) {
		String showCodeLast = "";
		String showCode = showResults.getShowCode();
		showCode = showCode.replaceAll(" ", "");
		List<String> list =  Arrays.asList(showCode.split(","));
		try {
			if(StringUtils.isNotBlank(showCode)) {
				showCodeLast = showResultsService.refreshHm(list);
			}
			
		} catch (Exception e) {
			return "{\"rc\":1,\"msg\":\""+e.getMessage()+"\"}";
		}
		return "{\"rc\":0,\"msg\":\"共刷新 "+list.size()+"场积分，积分榜版本号为"+showCodeLast+"。\"}";
	}
	
	
}