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

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
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.workactivity.service.ActivityService;
import com.jeeplus.modules.workinvoicereturn.entity.WorkInvoiceReturn;
import com.jeeplus.modules.workinvoicereturn.service.WorkInvoiceReturnService;
import com.jeeplus.modules.workinvoicereturnalter.entity.WorkInvoiceReturnAlter;
import com.jeeplus.modules.workinvoicereturnalter.entity.WorkInvoiceReturnAlter;
import com.jeeplus.modules.workinvoicereturnalter.service.WorkInvoiceReturnAlterService;
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.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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Map;

/**
 * 退票管理Controller
 * @author lw
 * @version 2018-06-15
 */
@Controller
@RequestMapping(value = "${adminPath}/workinvoicereturnalter/workInvoiceReturnAlter")
public class WorkInvoiceReturnAlterController extends BaseController {

	@Autowired
	private WorkInvoiceReturnAlterService workInvoiceReturnService;
	@Autowired
	private WorkInvoiceReturnService invoiceReturnService;

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private ActivityService activityService;
	@Autowired
	private OfficeService officeService;
	@ModelAttribute
	public WorkInvoiceReturnAlter get(@RequestParam(required=false) String id) {
		WorkInvoiceReturnAlter entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workInvoiceReturnService.get(id);
		}
		if (entity == null){
			entity = new WorkInvoiceReturnAlter();
		}
		return entity;
	}
	
	/**
	 * 退票管理列表页面
	 */
	@RequiresPermissions("workinvoicereturn:workInvoiceReturn:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkInvoiceReturnAlter workInvoiceReturn, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkInvoiceReturnAlter> page = workInvoiceReturnService.findPage(new Page<WorkInvoiceReturnAlter>(request, response), workInvoiceReturn);
		model.addAttribute("page", page);
		return "modules/workinvoicereturnalter/workInvoiceReturnAlterList";
	}

	/**
	 * 查看，增加，编辑退票管理表单页面
	 */
	//@RequiresPermissions(value={"workinvoicereturn:workInvoiceReturn:view","workinvoicereturn:workInvoiceReturn:add","workinvoicereturn:workInvoiceReturn:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkInvoiceReturnAlter workInvoiceReturn, Model model) {
		String view = "workInvoiceReturnAlterForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workInvoiceReturnAlterView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workInvoiceReturn.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);
				workInvoiceReturn.setAct(act);
				view = "workInvoiceReturnAlterModify";
			}
		}
		// 环节编号
		String taskDefKey = workInvoiceReturn.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && !taskDefKey.equals("modifyApply")){
			view = "workInvoiceReturnAlterAudit";
		}
		if(StringUtils.isBlank(workInvoiceReturn.getReturnNumber())){
			workInvoiceReturn.setUname(UserUtils.getUser().getName());
		}
		model.addAttribute("workInvoiceReturnAlter", workInvoiceReturn);
		return "modules/workinvoicereturnalter/"+view;
	}
	@RequestMapping(value = "store")
	public String store(WorkInvoiceReturnAlter workInvoiceReturn,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workInvoiceReturn)){
			return form(workInvoiceReturn, model);
		}
		if(workInvoiceReturn.getWorkInvoiceReturn()!=null){
			WorkInvoiceReturn workInvoiceReturn1 = invoiceReturnService.get(workInvoiceReturn.getWorkInvoiceReturn().getId());
			workInvoiceReturn1.setStatus("8");
			invoiceReturnService.save(workInvoiceReturn1);
		}
		User user = workInvoiceReturn.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workInvoiceReturn.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workinvoicereturnalter/workInvoiceReturnAlter/?repage";
		}
		workInvoiceReturn.setStatus("1"); //暂存状态
		workInvoiceReturn.setCompanyId(UserUtils.getSelectCompany().getId());
		workInvoiceReturn.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workInvoiceReturn.getProcessInstanceId()) && workInvoiceReturn.getProcessInstanceId().equals("NULL")){
			workInvoiceReturn.setProcessInstanceId("");
		}
		if(!workInvoiceReturn.getIsNewRecord()){//编辑表单保存
			WorkInvoiceReturnAlter t = workInvoiceReturnService.get(workInvoiceReturn.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workInvoiceReturn, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workInvoiceReturnService.save(t);//保存
		}else{//新增表单保存
			workInvoiceReturnService.save(workInvoiceReturn);//保存
		}
		addMessage(redirectAttributes, "退票变更申请暂存成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoicereturnalter/workInvoiceReturnAlter/?repage";
	}
	/**
	 * 保存退票管理
	 */
	@RequestMapping(value = "save")
	public String save(WorkInvoiceReturnAlter workInvoiceReturn, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workInvoiceReturn)){
			return form(workInvoiceReturn, model);
		}
		if(workInvoiceReturn.getWorkInvoiceReturn()!=null){
			WorkInvoiceReturn workInvoiceReturn1 = invoiceReturnService.get(workInvoiceReturn.getWorkInvoiceReturn().getId());
			workInvoiceReturn1.setStatus("8");
			invoiceReturnService.save(workInvoiceReturn1);
		}
		User user = workInvoiceReturn.getCreateBy();
		String sta = workInvoiceReturn.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workinvoicereturnalter/workInvoiceReturnAlter/?repage";
		}
		//状态设置为审核中
		workInvoiceReturn.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workInvoiceReturnService.get(workInvoiceReturn.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workInvoiceReturn.setCompanyId(UserUtils.getSelectCompany().getId());
			workInvoiceReturn.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workInvoiceReturnService.save(workInvoiceReturn, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "退票变更申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "退票变更申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "退票变更申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workinvoicereturnalter/workInvoiceReturnAlter/?repage";
	}
	
	/**
	 * 删除退票管理
	 */
	@RequiresPermissions("workinvoicereturn:workInvoiceReturn:del")
	@RequestMapping(value = "delete")
	public String delete(WorkInvoiceReturnAlter workInvoiceReturn, RedirectAttributes redirectAttributes) {
		workInvoiceReturnService.delete(workInvoiceReturn);
		addMessage(redirectAttributes, "删除退票变更管理成功");
		return "redirect:"+Global.getAdminPath()+"/workinvoicereturnalter/workInvoiceReturnAlter/?repage";
	}

	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkInvoiceReturnAlter workInvoiceReturn, Model model,
                            RedirectAttributes redirectAttributes) {
		try {
			List<User> users = UserUtils.getByProssType(workInvoiceReturn.getProcessInstanceId(),1);
			if ((users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workInvoiceReturnService.auditSave(workInvoiceReturn,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "项目登记流程审批失败");
		}


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

	/**
	 * 导入Excel数据

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

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnLeave")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = "/workinvoicereturn/workInvoiceReturn/form";
		// 获取流程实例对象
		if (act.getProcInsId() != null){
			if(actTaskService.getProcIns(act.getProcInsId())!=null){
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			}else{
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}
		}
		return "redirect:" + ActUtils.getFormUrl(formKey, act);
	}

	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkInvoiceReturnAlter workInvoiceReturn, Model model) {
		model.addAttribute("processInstanceId", workInvoiceReturn.getProcessInstanceId());
		return "modules/workinvoicereturnalter/workInvoiceReturnAlterTask";
	}
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkInvoiceReturnAlter workInvoiceReturn, RedirectAttributes redirectAttributes){
		workInvoiceReturnService.cancelInvalidate(workInvoiceReturn);
		return "redirect:"+Global.getAdminPath()+"/workinvoicereturnalter/workInvoiceReturnAlter/?repage";
	}
	

}