/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.casecategory.web;

import java.util.List;
import java.util.Map;

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

import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.Logical;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.casecategory.entity.CaseCategory;
import com.jeeplus.modules.casecategory.service.CaseCategoryService;

/**
 * 案例分类Controller
 * @author liuw
 * @version 2018-01-24
			*/
	@Controller
	@RequestMapping(value = "${adminPath}/casecategory/caseCategory")
	public class CaseCategoryController extends BaseController {

		@Autowired
	private CaseCategoryService caseCategoryService;
	@Autowired
	private HttpServletRequest request;
	
	@ModelAttribute
	public CaseCategory get(@RequestParam(required=false) String id) {
		CaseCategory entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = caseCategoryService.get(id);
		}
		if (entity == null){
			entity = new CaseCategory();
		}
		return entity;
	}
	
	/**
	 * 案例分类列表页面
	 */
	@RequiresPermissions("casecategory:caseCategory:list")
	@RequestMapping(value = {"list", ""})
	public String list(CaseCategory caseCategory, HttpServletRequest request, HttpServletResponse response, Model model) {
		/*Page<CaseCategory> page = caseCategoryService.findPage(new Page<CaseCategory>(request, response), caseCategory);
		model.addAttribute("page", page);
		return "modules/casecategory/caseCategoryList";*/
		List<CaseCategory> list = caseCategoryService.findList(caseCategory);
		model.addAttribute("list", list);
		return "modules/casecategory/caseCategoryList";
	}

	/**
	 * 查看，增加，编辑案例分类表单页面
	 */
	@RequiresPermissions(value={"casecategory:caseCategory:view","casecategory:caseCategory:add","casecategory:caseCategory:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(CaseCategory caseCategory, Model model) {
		if (caseCategory.getParent()!=null && StringUtils.isNotBlank(caseCategory.getParent().getId())){
			caseCategory.setParent(caseCategoryService.get(caseCategory.getParent().getId()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(caseCategory.getId())){
				CaseCategory sysNumberClassChild = new CaseCategory();
				sysNumberClassChild.setParent(new CaseCategory(caseCategory.getParent().getId()));
				List<CaseCategory> list = caseCategoryService.findList(caseCategory);
				if (list.size() > 0){
					caseCategory.setSort(list.get(list.size()-1).getSort());
					if (caseCategory.getSort() != null){
						caseCategory.setSort(caseCategory.getSort() + 30);
					}
				}
			}
		}
		if (caseCategory.getSort() == null){
			caseCategory.setSort(30);
		}
		model.addAttribute("caseCategory", caseCategory);
		String tabId = request.getParameter("tabId");
		if("0".equals(tabId)){
			return "modules/casecategory/caseCategoryView";
		}
		return "modules/casecategory/caseCategoryForm";
	}

	/**
	 * 保存案例分类
	 */
	@RequiresPermissions(value={"casecategory:caseCategory:add","casecategory:caseCategory:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(CaseCategory caseCategory, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, caseCategory)){
			return form(caseCategory, model);
		}
		if(!caseCategory.getIsNewRecord()){//编辑表单保存
			CaseCategory t = caseCategoryService.get(caseCategory.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(caseCategory, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			caseCategoryService.save(t);//保存
		}else{//新增表单保存
			caseCategoryService.save(caseCategory);//保存
		}
		addMessage(redirectAttributes, "保存案例分类成功");
		return "redirect:"+Global.getAdminPath()+"/casecategory/caseCategory/?repage";
	}
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<CaseCategory> list = caseCategoryService.findList(new CaseCategory());
		for (int i=0; i<list.size(); i++){
			CaseCategory e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	/**
	 * 删除案例分类
	 */
	@RequiresPermissions("casecategory:caseCategory:del")
	@RequestMapping(value = "delete")
	public String delete(CaseCategory caseCategory, RedirectAttributes redirectAttributes) {
		caseCategoryService.delete(caseCategory);
		addMessage(redirectAttributes, "删除案例分类成功");
		return "redirect:"+Global.getAdminPath()+"/casecategory/caseCategory/?repage";
	}
	
	/**
	 * 批量删除案例分类
	 */
	@RequiresPermissions("casecategory:caseCategory:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			caseCategoryService.delete(caseCategoryService.get(id));
		}
		addMessage(redirectAttributes, "删除案例分类成功");
		return "redirect:"+Global.getAdminPath()+"/casecategory/caseCategory/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("casecategory:caseCategory:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(CaseCategory caseCategory, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "案例分类"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<CaseCategory> page = caseCategoryService.findPage(new Page<CaseCategory>(request, response, -1), caseCategory);
    		new ExportExcel("案例分类", CaseCategory.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出案例分类记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/casecategory/caseCategory/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("casecategory:caseCategory:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<CaseCategory> list = ei.getDataList(CaseCategory.class);
			for (CaseCategory caseCategory : list){
				try{
					caseCategoryService.save(caseCategory);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条案例分类记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条案例分类记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入案例分类失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/casecategory/caseCategory/?repage";
    }
	
	/**
	 * 下载导入案例分类数据模板
	 */
	@RequiresPermissions("casecategory:caseCategory:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "案例分类数据导入模板.xlsx";
    		List<CaseCategory> list = Lists.newArrayList(); 
    		new ExportExcel("案例分类数据", CaseCategory.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/casecategory/caseCategory/?repage";
    }



	
	

}