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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
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.ActAuditService;
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.workpayment.entity.WorkPayment;
import com.jeeplus.modules.workpayment.service.WorkPaymentService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 付款申请Controller
 * @author fgy
 * @version 2018-01-16
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workpayment/workPayment")
public class WorkPaymentController extends BaseController {

	@Autowired
	private WorkPaymentService workPaymentService;
	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActAuditService actAuditService;
	
	@ModelAttribute
	public WorkPayment get(@RequestParam(required=false) String id) {
		WorkPayment entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workPaymentService.get(id);
		}
		if (entity == null){
			entity = new WorkPayment();
		}
		return entity;
	}
	
	/**
	 * 付款申请列表页面
	 */
	@RequiresPermissions("workpayment:workPayment:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkPayment workPayment, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			workPayment.setCompanyId(user.getComId());
			if (!UserUtils.isManager()){
				workPayment.setCreateBy(user);//申请人
				//workPayment.setOfficeId(UserUtils.getSelectOffice().getId());
			}
		}

		Page<WorkPayment> page = workPaymentService.findPage(new Page<WorkPayment>(request, response), workPayment); 
		model.addAttribute("page", page);
		return "modules/workpayment/workPaymentList";
	}

	/**
	 * 查看，增加，编辑付款申请表单页面
	 */
	@RequiresPermissions(value={"workpayment:workPayment:view","workpayment:workPayment:add","workpayment:workPayment:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkPayment workPayment, Model model) {
		String view = "workPaymentForm";
		// 查看审批申请单
		if (org.apache.commons.lang3.StringUtils.isNotBlank(workPayment.getId())){//.getAct().getProcInsId())){
			// 环节编号
			String taskDefKey = workPayment.getAct().getTaskDefKey();
			if (taskDefKey!=null) {
				// 查看工单
				if (workPayment.getAct().isFinishTask()) {
					view = "workPaymentView";
				}
				// 修改环节
				else if ("apply_end".equals(taskDefKey)) {
					view = "workPaymentAudit";
				}
				// 审核环节
				else if ("audit1".equals(taskDefKey)) {
					if (org.apache.commons.lang3.StringUtils.isBlank(workPayment.getAct().getStatus())){
						model.addAttribute("disabled","true");
					}else {
						model.addAttribute("disabled","false");
					}
					view = "workPaymentAudit";
				}
				//
				else if ("modifyApply".equals(taskDefKey)) {
					view = "workPaymentForm";
				}
			}
			if (org.apache.commons.lang3.StringUtils.isNotBlank(workPayment.getName())){
				if (workPayment.getName().equals("view")){
					model.addAttribute("disabled","true");
					workPayment.getAct().setProcInsId(workPayment.getProcessInstanceId());
					view = "workPaymentAudit";
				}
			}
		}
		model.addAttribute("workPayment", workPayment);
		return "modules/workpayment/"+view;
	}

	/**
	 * 保存付款申请
	 */
	@RequiresPermissions(value={"workpayment:workPayment:add","workpayment:workPayment:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkPayment workPayment, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workPayment)){
			return form(workPayment, model);
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(workPayment.getId())) {
			WorkPayment t = workPaymentService.get(workPayment.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workPayment, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			if (t.getStatus().equals("3") || t.getStatus().equals("4")){
				addMessage(redirectAttributes, "已结束流程不能修改！");
			}else {
				workPaymentService.save(t);
			}
		} else {
			try {
				Map<String,Boolean> resultMap = workPaymentService.saveWorkPettyCash(workPayment);
				boolean flag = resultMap.get("flag");
				if(!flag){
					addMessage(redirectAttributes,"不能选择自己为审批人!");
				}else{
					boolean b = resultMap.get("b");
					if (b){
						addMessage(redirectAttributes, "付款申请已经提交");
					}else {
						addMessage(redirectAttributes, "系统内部错误！");
					}
				}
			}catch (Exception e){
				logger.info("save e.getMessage()="+e.getMessage());
				addMessage(redirectAttributes, "系统内部错误！");
			}
		}
		return "redirect:"+Global.getAdminPath()+"/workpayment/workPayment/?repage";
	}
	
	/**
	 * 删除付款申请
	 */
	@RequiresPermissions("workpayment:workPayment:del")
	@RequestMapping(value = "delete")
	public String delete(WorkPayment workPayment, RedirectAttributes redirectAttributes) {
		workPaymentService.delete(workPayment);
		addMessage(redirectAttributes, "删除付款申请成功");
		return "redirect:"+Global.getAdminPath()+"/workpayment/workPayment/?repage";
	}
	
	/**
	 * 批量删除付款申请
	 */
	@RequiresPermissions("workpayment:workPayment:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workPaymentService.delete(workPaymentService.get(id));
		}
		addMessage(redirectAttributes, "删除付款申请成功");
		return "redirect:"+Global.getAdminPath()+"/workpayment/workPayment/?repage";
	}
	/**
	 * 执行审批任务
	 * @param
	 * @param vars
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkPayment workPayment, Map<String, Object> vars, Model model) {
		//workPaymentService.auditSave(workPayment);
		Act act = workPayment.getAct();
		actAuditService.saveAudit(act, act.getProcInsId(), "payment", workPayment.getAct().getComment(), workPayment.getId(), "2");
		if (workPayment!=null && org.apache.commons.lang3.StringUtils.isNotBlank(workPayment.getHome()) && workPayment.getHome().equals("home")){
			return "redirect:" + adminPath + "/home";
		}
		return "redirect:" + adminPath + "/workpayment/workPayment";
	}

	/**
	 * 待办任务
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workPaymentTodoList"})
	public String workPaymentTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("payment");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkPayment> lists = new ArrayList<WorkPayment>();
		for (Act a : list) {
			WorkPayment workPayment = workPaymentService.getByProcessInstanceId(a.getProcInsId());
			if (workPayment != null && workPayment.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null) {
					User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
					if (user != null) {
						a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
					}
				}
				workPayment.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(workPayment.getId())){
					workPayment.setName(officeService.get(companyId).getName());
				}
				lists.add(workPayment);
			}
		}
		model.addAttribute("list", lists);
		return "modules/workpayment/workPaymentTodoList";
	}

	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workPaymentHistoricList"})
	public String workPaymentHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("payment");
		Page<Act> page = actTaskService.historicList(new Page<Act>(request, response), act);
		List<Act> list = page.getList();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkPayment> lists = new ArrayList<WorkPayment>();
		for (Act a : list) {
			WorkPayment workPayment = workPaymentService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (workPayment != null && workPayment.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				workPayment.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(workPayment.getId())){
					workPayment.setName(officeService.get(companyId).getName());
				}
				lists.add(workPayment);
			}
		}
		model.addAttribute("list", lists);

		return "modules/workpayment/workPaymentHistoricList";
	}

	/**
	 * 审核付款申请
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnWorkpayment")
	public String applyOnWorkpayment(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
		//logger.info("------formKeys:"+formKeys);
		// 获取流程实例对象
		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);
	}

	/**
	 * 撤销付款申请
	 * @param
	 * @return
	 */
	@RequestMapping(value = "revoke")
	public String revoke(HttpServletRequest request, HttpServletResponse response) {

		HashMap<String, String> requestMap = findRequestMap(request);
		String processInstanceId = requestMap.get("processInstanceId");
		String id = requestMap.get("id");
		String deleteReason = requestMap.get("reason");

		AjaxJson j = new AjaxJson();
		try {
			WorkPayment workPayment = workPaymentService.getById(id);
			workPayment.setStatus("5");
			workPayment.preUpdate();
			workPaymentService.update(workPayment);
			Map map = workPaymentService.getPaymentById(id,"1");
			j.put("data",map);
			actTaskService.endProcessInstance(processInstanceId, deleteReason);
			j.setMsg("撤销申请成功");

			//撤销后，更改所有发送过的通知的阅读状态
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workPayment.getId());
			workProjectNotifyService.readByNotifyId(notify);
		}catch (Exception e){
			j.setErrorCode("101");
			logger.info(e.getMessage());
			j.setMsg("撤销申请失败");
			j.setSuccess(false);
		}
		return "redirect:" + adminPath + "/workpayment/workPayment";
	}



	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workpayment:workPayment:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkPayment workPayment, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "付款申请"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkPayment> page = workPaymentService.findPage(new Page<WorkPayment>(request, response, -1), workPayment);
    		new ExportExcel("付款申请", WorkPayment.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出付款申请记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workpayment/workPayment/?repage";
    }

	/**
	 * 导入Excel数据

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

}