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

import java.util.Date;
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.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmtree.service.SysMtreeService;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workreimbursement.service.WorkReimbursementService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
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.workovertime.entity.WorkOvertime;
import com.jeeplus.modules.workovertime.service.WorkOvertimeService;

/**
 * 加班申请Controller
 * @author ssrh
 * @version 2018-09-04
 */
@Controller
@RequestMapping(value = "${adminPath}/workovertime/workOvertime")
public class WorkOvertimeController extends BaseController {

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private SysMtreeService sysMtreeService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private OfficeService officeService;

	@Autowired
	private WorkOvertimeService workOvertimeService;

	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	
	@ModelAttribute
	public WorkOvertime get(@RequestParam(required=false) String id) {
		WorkOvertime entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workOvertimeService.get(id);
		}
		if (entity == null){
			entity = new WorkOvertime();
		}
		return entity;
	}
	
	/**
	 * 加班申请列表页面
	 */
	@RequiresPermissions("workovertime:workOvertime:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkOvertime workOvertime, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkOvertime> page = workOvertimeService.findPage(new Page<WorkOvertime>(request, response), workOvertime); 
		model.addAttribute("page", page);
		return "modules/workovertime/workOvertimeList";
	}

	/**
	 * 查看，增加，编辑加班申请表单页面
	 */
	//@RequiresPermissions(value={"workovertime:workOvertime:view","workovertime:workOvertime:add","workovertime:workOvertime:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkOvertime workOvertime, Model model) {
		String view = "workOvertimeForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workOvertimeView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workOvertime.getProcessInstanceId());
			if (processInstance!=null) {
				Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
				Act act = new Act();
				act.setTaskId(taskInfok.getId());
				act.setTaskName(taskInfok.getName());
				act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
				act.setProcDefId(taskInfok.getProcessDefinitionId());
				act.setProcInsId(taskInfok.getProcessInstanceId());
				act.setTask(taskInfok);
				workOvertime.setAct(act);
				view = "workOvertimeModify";
			}
		}
		// 环节编号
		String taskDefKey = workOvertime.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("bmzr".equals(taskDefKey))){
			view = "workOvertimeAudit";
		}
		if(StringUtils.isBlank(workOvertime.getId())){
			workOvertime.setName(UserUtils.getUser().getName());
			WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
			workStaffBasicInfo.setUserId(UserUtils.getUser().getId());
			workStaffBasicInfo.setOffice(UserUtils.getSelectOffice());
			workStaffBasicInfo = workStaffBasicInfoService.getByUserOffice(workStaffBasicInfo);
			workOvertime.setWorkStaffBasicInfo(workStaffBasicInfo);
		}
		model.addAttribute("workOvertime", workOvertime);
		return "modules/workovertime/"+view;
	}
	/**
	 * 暂存
	 */
	@RequestMapping(value = "store")
	public String store(WorkOvertime workOvertime,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workOvertime)){
			return form(workOvertime, model);
		}
		User user = workOvertime.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workOvertime.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
		}
		workOvertime.setStatus("1"); //暂存状态
		workOvertime.setCompanyId(UserUtils.getSelectCompany().getId());
		workOvertime.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workOvertime.getProcessInstanceId()) && workOvertime.getProcessInstanceId().equals("NULL")){
			workOvertime.setProcessInstanceId("");
		}
		if(!workOvertime.getIsNewRecord()){//编辑表单保存
			WorkOvertime t = workOvertimeService.get(workOvertime.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workOvertime, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workOvertimeService.save(t);//保存
		}else{//新增表单保存
			workOvertimeService.save(workOvertime);//保存
		}
		addMessage(redirectAttributes, "保存加班申请成功");
		return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
	}
	/**
	 * 保存加班申请
	 */
	@RequiresPermissions(value={"workovertime:workOvertime:add","workovertime:workOvertime:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkOvertime workOvertime, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workOvertime)){
			return form(workOvertime, model);
		}
		User user = workOvertime.getCreateBy();
		String sta = workOvertime.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
		}
		//状态设置为审核中
		workOvertime.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workOvertimeService.get(workOvertime.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workOvertime.setCompanyId(UserUtils.getSelectCompany().getId());
			workOvertime.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workOvertimeService.save(workOvertime, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "加班申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "加班申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "加班申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkOvertime workOvertime, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			List<User> users = UserUtils.getByProssType(workOvertime.getProcessInstanceId(),1);
			String flag = workOvertime.getAct().getFlag();
			if ("yes".equals(flag) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workOvertimeService.auditSave(workOvertime,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败");
		}

		if (StringUtils.isNotBlank(workOvertime.getHome()) && "home".equals(workOvertime.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
		}
	}
	/**
	 * 删除加班申请
	 */
	@RequiresPermissions("workovertime:workOvertime:del")
	@RequestMapping(value = "delete")
	public String delete(WorkOvertime workOvertime, RedirectAttributes redirectAttributes) {
		workOvertimeService.delete(workOvertime);
		addMessage(redirectAttributes, "删除加班申请成功");
		return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
	}
	
	/**
	 * 批量删除加班申请
	 */
	@RequiresPermissions("workovertime:workOvertime:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workOvertimeService.delete(workOvertimeService.get(id));
		}
		addMessage(redirectAttributes, "删除加班申请成功");
		return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workovertime:workOvertime:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkOvertime workOvertime, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "加班申请"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkOvertime> page = workOvertimeService.findPage(new Page<WorkOvertime>(request, response, -1), workOvertime);
    		new ExportExcel("加班申请", WorkOvertime.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出加班申请记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workovertime:workOvertime: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<WorkOvertime> list = ei.getDataList(WorkOvertime.class);
			for (WorkOvertime workOvertime : list){
				try{
					workOvertimeService.save(workOvertime);
					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()+"/workovertime/workOvertime/?repage";
    }
	
	/**
	 * 下载导入加班申请数据模板
	 */
	@RequiresPermissions("workovertime:workOvertime:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "加班申请数据导入模板.xlsx";
    		List<WorkOvertime> list = Lists.newArrayList(); 
    		new ExportExcel("加班申请数据", WorkOvertime.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
    }
	/**
	 * 强制撤销
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkOvertime workOvertime,RedirectAttributes redirectAttributes){
		workOvertimeService.cancelInvalidate(workOvertime);
		return "redirect:"+Global.getAdminPath()+"/workovertime/workOvertime/?repage";
	}
	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkOvertime workOvertime,Model model) {
		model.addAttribute("processInstanceId", workOvertime.getProcessInstanceId());
		return "modules/workovertime/workTrack";
	}
	

}