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

import java.util.ArrayList;
import java.util.List;

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

import com.jeeplus.modules.oa.entity.Leave;
import com.jeeplus.modules.oa.service.LeaveService;
import com.jeeplus.modules.oa_evection.entity.oa_evection.OaEvection;
import com.jeeplus.modules.oa_evection.service.oa_evection.OaEvectionService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workgoout.entity.GoOut;
import com.jeeplus.modules.workgoout.service.GoOutService;
import com.jeeplus.modules.workovertimeform.entity.WorkOvertimeForm;
import com.jeeplus.modules.workovertimeform.service.WorkOvertimeFormService;
import com.jeeplus.modules.worksealform.entity.WorkSealForm;
import com.jeeplus.modules.worksealform.service.WorkSealFormService;
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.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.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.workapprovalcopy.entity.ApprovalCopy;
import com.jeeplus.modules.workapprovalcopy.service.ApprovalCopyService;

/**
 * 抄送信息Controller
 * @author yangfan
 * @version 2017-07-21
 */
@Controller
@RequestMapping(value = "${adminPath}/workapprovalcopy/approvalCopy")
public class ApprovalCopyController extends BaseController {

	@Autowired
	private ApprovalCopyService approvalCopyService;
	@Autowired
	protected LeaveService leaveService;
	@Autowired
	private WorkOvertimeFormService workOvertimeFormService;
	@Autowired
	private OaEvectionService oaEvectionService;
	@Autowired
	private WorkSealFormService workSealFormService;
	@Autowired
	private GoOutService goOutService;
	@ModelAttribute
	public ApprovalCopy get(@RequestParam(required=false) String id) {
		ApprovalCopy entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = approvalCopyService.get(id);
		}
		if (entity == null){
			entity = new ApprovalCopy();
		}
		return entity;
	}
	
	/**
	 * 抄送信息列表页面
	 */
	@RequiresPermissions("workapprovalcopy:approvalCopy:list")
	@RequestMapping(value = {"list", ""})
	public String list(ApprovalCopy approvalCopy, HttpServletRequest request, HttpServletResponse response, Model model) {
		approvalCopy.setCCId(UserUtils.getUser().getId());
		Page<ApprovalCopy> page = approvalCopyService.findPage(new Page<ApprovalCopy>(request, response), approvalCopy);
		List<ApprovalCopy> list = page.getList();
		List<ApprovalCopy> lists = new ArrayList<ApprovalCopy>();
		if (list!=null && list.size()!=0){
			for (ApprovalCopy a:list){
				String approvalNames = "";
				if (StringUtils.isNotBlank(a.getApproverId())) {
					String[] ids = a.getApproverId().split(",");
					for (String id : ids) {
						if (UserUtils.get(id)!=null) {
							approvalNames += "," + UserUtils.get(id).getName();
						}
					}
					User user = UserUtils.get(a.getUserId());
					if (user!=null){
						a.setUserName(user.getName());
					}else {
						a.setUserName(a.getUserId());
					}
					if (StringUtils.isNotBlank(approvalNames)) {
						a.setApproverIdName(approvalNames.substring(1, approvalNames.length() > 15 ? 15 : approvalNames.length()));
					}
					lists.add(a);
				}
			}
			page.setList(lists);
		}
		model.addAttribute("page", page);
		return "modules/workapprovalcopy/approvalCopyList";
	}

	/**
	 * 查看，增加，编辑抄送信息表单页面
	 */
	@RequiresPermissions(value={"workapprovalcopy:approvalCopy:view","workapprovalcopy:approvalCopy:add","workapprovalcopy:approvalCopy:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(HttpSession session,ApprovalCopy approvalCopy, Model model) {
		String type = approvalCopy.getType();
		String approvalId = approvalCopy.getApprovalId();
		session.setAttribute("state","disabled");
		//请假申请
		if(type.equals("leave")){
			Leave leave = leaveService.getById(approvalId);
			String id = leave.getId();
			model.addAttribute("id",id);
			model.addAttribute("name","view");
			return "redirect:"+Global.getAdminPath()+"/oa/leave/form";}
		//加班申请
		if(type.equals("overtime")){
			WorkOvertimeForm workOvertimeForm = workOvertimeFormService.getById(approvalId);
			String id = workOvertimeForm.getId();
			model.addAttribute("id",id);
			model.addAttribute("name","view");
			return "redirect:"+Global.getAdminPath()+"/workovertimeform/workOvertimeForm/form";}
		//外出申请
		if(type.equals("goout")){
			GoOut goOut = goOutService.getById(approvalId);
			String id = goOut.getId();
			model.addAttribute("id",id);
			model.addAttribute("name","view");
			return "redirect:"+Global.getAdminPath()+"/goout/goOut/form";}
		//用印申请
		if(type.equals("sealform")){
			WorkSealForm workSealForm = workSealFormService.getById(approvalId);
			String id = workSealForm.getId();
			model.addAttribute("id",id);
			model.addAttribute("name","view");
			return "redirect:"+Global.getAdminPath()+"/worksealform/workSealForm/form";}
		//出差申请
		if(type.equals("evection")){
			OaEvection oaEvection = oaEvectionService.getById(approvalId);
			String id = oaEvection.getId();
			model.addAttribute("id",id);
			model.addAttribute("name","view");
			return "redirect:"+Global.getAdminPath()+"/oa_evection/oaEvection/form";}
			return null;
	//model.addAttribute("approvalCopy", approvalCopy);
	//return "modules/workapprovalcopy/approvalCopyForm";
	//if(approvalCopy.getType()=="leava")
	}

	/**
	 * 保存抄送信息
	 */
	@RequiresPermissions(value={"workapprovalcopy:approvalCopy:add","workapprovalcopy:approvalCopy:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(HttpSession session,ApprovalCopy approvalCopy, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, approvalCopy)){
			return form(session,approvalCopy, model);
		}
		if(!approvalCopy.getIsNewRecord()){//编辑表单保存
			ApprovalCopy t = approvalCopyService.get(approvalCopy.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(approvalCopy, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			approvalCopyService.save(t);//保存
		}else{//新增表单保存
			approvalCopyService.save(approvalCopy);//保存
		}
		addMessage(redirectAttributes, "保存抄送信息成功");
		return "redirect:"+Global.getAdminPath()+"/workapprovalcopy/approvalCopy/?repage";
	}
	
	/**
	 * 删除抄送信息
	 */
	@RequiresPermissions("workapprovalcopy:approvalCopy:del")
	@RequestMapping(value = "delete")
	public String delete(ApprovalCopy approvalCopy, RedirectAttributes redirectAttributes) {
		approvalCopyService.delete(approvalCopy);
		addMessage(redirectAttributes, "删除抄送信息成功");
		return "redirect:"+Global.getAdminPath()+"/workapprovalcopy/approvalCopy/?repage";
	}
	
	/**
	 * 批量删除抄送信息
	 */
	@RequiresPermissions("workapprovalcopy:approvalCopy:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			approvalCopyService.delete(approvalCopyService.get(id));
		}
		addMessage(redirectAttributes, "删除抄送信息成功");
		return "redirect:"+Global.getAdminPath()+"/workapprovalcopy/approvalCopy/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workapprovalcopy:approvalCopy:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(ApprovalCopy approvalCopy, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "抄送信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ApprovalCopy> page = approvalCopyService.findPage(new Page<ApprovalCopy>(request, response, -1), approvalCopy);
    		new ExportExcel("抄送信息", ApprovalCopy.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出抄送信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workapprovalcopy/approvalCopy/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workapprovalcopy:approvalCopy: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<ApprovalCopy> list = ei.getDataList(ApprovalCopy.class);
			for (ApprovalCopy approvalCopy : list){
				try{
					approvalCopyService.save(approvalCopy);
					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()+"/workapprovalcopy/approvalCopy/?repage";
    }
	
	/**
	 * 下载导入抄送信息数据模板
	 */
	@RequiresPermissions("workapprovalcopy:approvalCopy:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "抄送信息数据导入模板.xlsx";
    		List<ApprovalCopy> list = Lists.newArrayList(); 
    		new ExportExcel("抄送信息数据", ApprovalCopy.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workapprovalcopy/approvalCopy/?repage";
    }
	
	
	

}