/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workfield.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.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.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.workfield.entity.WorkField;
import com.jeeplus.modules.workfield.service.WorkFieldService;

/**
 * 外勤申请Controller
 * @author ssrh
 * @version 2018-09-06
 */
@Controller
@RequestMapping(value = "${adminPath}/workfield/workField")
public class WorkFieldController extends BaseController {


	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@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 WorkFieldService workFieldService;

	@ModelAttribute
	public WorkField get(@RequestParam(required=false) String id) {
		WorkField entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workFieldService.get(id);
		}
		if (entity == null){
			entity = new WorkField();
		}
		return entity;
	}
	
	/**
	 * 外勤申请列表页面
	 */
	@RequiresPermissions("workfield:workField:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkField workField, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkField> page = workFieldService.findPage(new Page<WorkField>(request, response), workField); 
		model.addAttribute("page", page);
		return "modules/workfield/workFieldList";
	}

	/**
	 * 查看，增加，编辑外勤申请表单页面
	 */
	//@RequiresPermissions(value={"workfield:workField:view","workfield:workField:add","workfield:workField:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkField workField, Model model) {
		String view = "workFieldForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workFieldView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workField.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);
				workField.setAct(act);
				view = "workFieldModify";
			}
		}
		// 环节编号
		String taskDefKey = workField.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("bmzr".equals(taskDefKey))){
			view = "workFieldAudit";
		}
		if(StringUtils.isBlank(workField.getId())){
			workField.setName(UserUtils.getUser().getName());
			WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
			workStaffBasicInfo.setUserId(UserUtils.getUser().getId());
			workStaffBasicInfo.setOffice(UserUtils.getSelectOffice());
			workStaffBasicInfo = workStaffBasicInfoService.getByUserOffice(workStaffBasicInfo);
			workField.setWorkStaffBasicInfo(workStaffBasicInfo);
			workField.setCreateDate(new Date());
		}
		model.addAttribute("workField", workField);
		return "modules/workfield/"+view;
	}

	/**
	 * 暂存
	 */
	@RequestMapping(value = "store")
	public String store(WorkField workField,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workField)){
			return form(workField, model);
		}
		User user = workField.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workField.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workfield/workField/?repage";
		}
		workField.setStatus("1"); //暂存状态
		workField.setCompanyId(UserUtils.getSelectCompany().getId());
		workField.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workField.getProcessInstanceId()) && workField.getProcessInstanceId().equals("NULL")){
			workField.setProcessInstanceId("");
		}
		if(!workField.getIsNewRecord()){//编辑表单保存
			WorkField t = workFieldService.get(workField.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workField, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workFieldService.save(t);//保存
		}else{//新增表单保存
			workFieldService.save(workField);//保存
		}
		addMessage(redirectAttributes, "保存外勤申请成功");
		return "redirect:"+Global.getAdminPath()+"/workfield/workField/?repage";
	}
	/**
	 * 保存外勤申请
	 */
	@RequiresPermissions(value={"workfield:workField:add","workfield:workField:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkField workField, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workField)){
			return form(workField, model);
		}
		User user = workField.getCreateBy();
		String sta = workField.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workfield/workField/?repage";
		}
		//状态设置为审核中
		workField.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workFieldService.get(workField.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workField.setCompanyId(UserUtils.getSelectCompany().getId());
			workField.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workFieldService.save(workField, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "外勤申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "外勤申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "外勤申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workfield/workField/?repage";
	}

	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkField workField, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			List<User> users = UserUtils.getByProssType(workField.getProcessInstanceId(),1);
			String flag = workField.getAct().getFlag();
			if ("yes".equals(flag) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workFieldService.auditSave(workField,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败");
		}

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

	/**
	 * 导入Excel数据

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

	/**
	 * 强制撤销
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkField workField,RedirectAttributes redirectAttributes){
		workFieldService.cancelInvalidate(workField);
		return "redirect:"+Global.getAdminPath()+"/workfield/workField/?repage";
	}
	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkField workField,Model model) {
		model.addAttribute("processInstanceId", workField.getProcessInstanceId());
		return "modules/workfield/workTrack";
	}



}