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

import java.util.*;

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

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.modules.sys.entity.MainDict;
import com.jeeplus.modules.sys.entity.MainDictDetail;
import com.jeeplus.modules.sys.utils.UserUtils;
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.leavetype.entity.LeaveType;
import com.jeeplus.modules.leavetype.service.LeaveTypeService;

/**
 * 假期类型字典Controller
 * @author ssrh
 * @version 2018-09-07
 */
@Controller
@RequestMapping(value = "${adminPath}/leavetype/leaveType")
public class LeaveTypeController extends BaseController {

	@Autowired
	private LeaveTypeService leaveTypeService;
	@Autowired
	private HttpServletRequest request;
	@ModelAttribute
	public LeaveType get(@RequestParam(required=false) String id) {
		LeaveType entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = leaveTypeService.get(id);
		}
		if (entity == null){
			entity = new LeaveType();
		}
		return entity;
	}
	
	/**
	 * 假期类型字典列表页面
	 */
	@RequiresPermissions("leavetype:leaveType:list")
	@RequestMapping(value = {"list", ""})
	public String list(LeaveType leaveType, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(StringUtils.isBlank(leaveType.getCompanyId())){
			leaveType.setCompanyId(UserUtils.getSelectCompany().getId());
		}
		List<LeaveType> list = leaveTypeService.findList(leaveType);
		List<LeaveType> sortedList = new ArrayList<>();
		if(list!=null&&list.size()>0) {
			this.sortList(sortedList,list,null);
		}
		model.addAttribute("list", sortedList);
		return "modules/leavetype/leaveTypeList";
	}
	@RequestMapping(value = {"sysList"})
	public String sysList(LeaveType leaveType, HttpServletRequest request, HttpServletResponse response, Model model) {
		leaveType.setIsSys("0");
		List<LeaveType> list = leaveTypeService.findList(leaveType);
		List<LeaveType> sortedList = new ArrayList<>();
		if(list!=null&&list.size()>0) {
			this.sortList(sortedList,list,null);
		}
		model.addAttribute("list", sortedList);
		return "modules/leavetype/leaveTypeSysList";
	}
	private void sortList(List<LeaveType> sortedList, List<LeaveType> list,LeaveType parent) {
		Iterator<LeaveType> iterator = list.iterator();
		while (iterator.hasNext()){
			LeaveType next = iterator.next();
			if(next==null)continue;
			if(parent==null) {
				sortedList.add(next);
				iterator.remove();
				this.sortList(sortedList,list,next);
				next.setParentId("0");
				iterator = list.iterator();
			}else {
				if(parent.getId().equals(next.getParentId())){
					sortedList.add(next);
					iterator.remove();
					this.sortList(sortedList,list,next);
					iterator = list.iterator();
				}
			}
		}
	}
	/**
	 * 查看，增加，编辑假期类型字典表单页面
	 */
	@RequiresPermissions(value={"leavetype:leaveType:view","leavetype:leaveType:add","leavetype:leaveType:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LeaveType leaveType, Model model) {
		String view=request.getParameter("view");
		model.addAttribute("leaveType", leaveType);
		if("view".equals(view)){
			return "modules/leavetype/leaveTypeFormView";
		}
		model.addAttribute("leaveType", leaveType);
		return "modules/leavetype/leaveTypeForm";
	}

	/**
	 * 保存假期类型字典
	 */
	@RequiresPermissions(value={"leavetype:leaveType:add"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(LeaveType leaveType, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, leaveType)){
			return form(leaveType, model);
		}
		boolean admin = UserUtils.getUser().isAdmin();
		if(admin){
			leaveType.setIsSys("0");//系统默认
		}else{
			leaveType.setIsSys("1");//公司级
		}
		leaveType.setKey(IdGen.uuid());
		leaveType.setBranchOffice(UserUtils.getSelectBranchOffice());
		leaveType.setOfficeId(UserUtils.getSelectOffice().getId());
		leaveType.setCompanyId(UserUtils.getSelectCompany().getId());
		if(!"0".equals(leaveType.getParentId()) && !Strings.isNullOrEmpty(leaveType.getParentId())){
			LeaveType md = leaveTypeService.get(leaveType.getParentId());
			if(md != null){
				leaveType.setIsEnd("1");//是末级
				leaveType.setParentIds(md.getParentIds()+leaveType.getParentId()+",");
			}else{
				leaveType.setParentIds("0,");
			}
			md.setIsEnd("0");//不是末级
			leaveTypeService.upateEndFlag(md);
		}else{
			leaveType.setIsEnd("1");//是末级
			leaveType.setParentId("0");
			leaveType.setParentIds("0,");
		}
		if(!leaveType.getIsNewRecord()){//编辑表单保存
			LeaveType t = leaveTypeService.get(leaveType.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(leaveType, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			leaveTypeService.save(t);//保存
		}else{//新增表单保存
			leaveType.setState("0");
			leaveTypeService.save(leaveType);//保存
		}
		addMessage(redirectAttributes, "保存假期类型字典成功");
		return "redirect:"+Global.getAdminPath()+"/leavetype/leaveType/?repage";
	}
	
	/**
	 * 删除假期类型字典
	 */
	@RequiresPermissions("leavetype:leaveType:del")
	@RequestMapping(value = "delete")
	public String delete(LeaveType leaveType, RedirectAttributes redirectAttributes) {
		leaveTypeService.delete(leaveType);
		addMessage(redirectAttributes, "删除假期类型字典成功");
		return "redirect:"+Global.getAdminPath()+"/leavetype/leaveType/?repage";
	}
	
	/**
	 * 批量删除假期类型字典
	 */
	@RequiresPermissions("leavetype:leaveType:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			leaveTypeService.delete(leaveTypeService.get(id));
		}
		addMessage(redirectAttributes, "删除假期类型字典成功");
		return "redirect:"+Global.getAdminPath()+"/leavetype/leaveType/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("leavetype:leaveType:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(LeaveType leaveType, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "假期类型字典"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LeaveType> page = leaveTypeService.findPage(new Page<LeaveType>(request, response, -1), leaveType);
    		new ExportExcel("假期类型字典", LeaveType.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出假期类型字典记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/leavetype/leaveType/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("leavetype:leaveType: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<LeaveType> list = ei.getDataList(LeaveType.class);
			for (LeaveType leaveType : list){
				try{
					leaveTypeService.save(leaveType);
					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()+"/leavetype/leaveType/?repage";
    }
	
	/**
	 * 下载导入假期类型字典数据模板
	 */
	@RequiresPermissions("leavetype:leaveType:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "假期类型字典数据导入模板.xlsx";
    		List<LeaveType> list = Lists.newArrayList(); 
    		new ExportExcel("假期类型字典数据", LeaveType.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/leavetype/leaveType/?repage";
    }
	/**
	 * 获取机构JSON数据。
	 *
	 * @param extId    排除的ID
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
											  @RequestParam(required = false) Boolean isAll,
											  @RequestParam(required = false) String typeId,
											  HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		LeaveType leaveType=new LeaveType();
		leaveType.setCompanyId(UserUtils.getSelectCompany().getId());
		List<LeaveType> list = leaveTypeService.findList(leaveType);
		for (int i = 0; i < list.size(); i++) {
			LeaveType 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("pIds", e.getParentIds());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				if (e.getIsEnd() != null && "0".equals(e.getIsEnd())) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}


	/**
	 * 更改删除标志
	 * @return
	 */
	@RequestMapping(value = "updateDelFlag")
	public String updateDelFlag(HttpServletRequest request){
		String id = request.getParameter("id");
		String flag = request.getParameter("flat");
		leaveTypeService.updateDelFlag(id,flag);
		return "redirect:"+Global.getAdminPath()+"/leavetype/leaveType/?repage";
	}

	//同步默认字典
	@RequestMapping(value = "syncDict")
	@ResponseBody
	public Map<Object, Object> syncDict(LeaveType leaveType,HttpServletRequest request){
		Map<Object,Object> map = new HashMap<>();
		leaveType.setIsSys("0");
		boolean flag = leaveTypeService.syncDict(leaveType);
		map.put("flag",flag);
		return map;
	}
}