/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workfullmanage.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.mapper.JsonMapper;
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.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.entity.WorkFullPay;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workfullmanage.service.WorkFullPayService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
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.*;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工程计量支付Controller
 * @author mapengbo
 * @version 2017-11-03
 */
@Controller
@RequestMapping(value = "${adminPath}/workfullmanage/workFullPay")
public class WorkFullPayController extends BaseController {

	@Autowired
	private WorkFullPayService workFullPayService;
	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;
	
	@ModelAttribute
	public WorkFullPay get(@RequestParam(required=false) String id) {
		WorkFullPay entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workFullPayService.get(id);
		}
		if (entity == null){
			entity = new WorkFullPay();
		}
		return entity;
	}

	@RequiresPermissions("workfullmanage:workFullPay:workFullManageList")
	@RequestMapping("/workFullManageList")
	public String workFullManageList(WorkFullManage workFullManage, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workFullManage.setQueryCon(id);
			workFullManage.setMasterId(UserUtils.getUser().getId());
		}
		//查询项目归档的数据
//		workFullManage.setFullProjectStatus("3");
		//添加只查询当前公司的数据  no
		Page<WorkFullManage> page = workFullManageService.findPage(new Page<WorkFullManage>(request, response), workFullManage);
		List<WorkFullManage> list = page.getList();
		for (WorkFullManage workFull:list){
			if(!Strings.isNullOrEmpty(workFull.getHostMaster())){
				String[] split = workFull.getHostMaster().split(",");
				String hostMasterName = workFullManageService.getPeople(split);
				workFull.setHostMasterName(hostMasterName);
			}

			if(!Strings.isNullOrEmpty(workFull.getFollowMaster())){
				String[] split1 = workFull.getFollowMaster().split(",");
				String followMasterName = workFullManageService.getPeople(split1);
				workFull.setFollowMasterName(followMasterName);
			}
			if(!Strings.isNullOrEmpty(workFull.getHostMember())){
				String[] split2 = workFull.getHostMember().split(",");
				String hostMemberName = workFullManageService.getPeople(split2);
				workFull.setHostMemberName(hostMemberName);
			}
			if(!Strings.isNullOrEmpty(workFull.getFollowMember())){
				String[] split3 = workFull.getFollowMember().split(",");
				String followMemberName = workFullManageService.getPeople(split3);
				workFull.setFollowMemberName(followMemberName);
			}
		}
		//查询是否存没有已通过的信息
		page.setList(list);
		model.addAttribute("page", page);
		return "modules/workfullpay/workFullManagePayList";
	}

	@RequiresPermissions("workfullmanage:workFullPay:workFullManageListResult")
	@RequestMapping("/workFullManageListResult")
	public String workFullManageListResult(WorkFullManage workFullManage, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workFullManage.setQueryCon(id);
			workFullManage.setMasterId(UserUtils.getUser().getId());
		}
		//添加只查询当前公司的数据  no
		Page<WorkFullManage> page = workFullManageService.findPage(new Page<WorkFullManage>(request, response), workFullManage);
		List<WorkFullManage> list = page.getList();
		for (WorkFullManage workFull:list){
			if(!Strings.isNullOrEmpty(workFull.getHostMaster())){
				String[] split = workFull.getHostMaster().split(",");
				String hostMasterName = workFullManageService.getPeople(split);
				workFull.setHostMasterName(hostMasterName);
			}

			if(!Strings.isNullOrEmpty(workFull.getFollowMaster())){
				String[] split1 = workFull.getFollowMaster().split(",");
				String followMasterName = workFullManageService.getPeople(split1);
				workFull.setFollowMasterName(followMasterName);
			}
			if(!Strings.isNullOrEmpty(workFull.getHostMember())){
				String[] split2 = workFull.getHostMember().split(",");
				String hostMemberName = workFullManageService.getPeople(split2);
				workFull.setHostMemberName(hostMemberName);
			}
			if(!Strings.isNullOrEmpty(workFull.getFollowMember())){
				String[] split3 = workFull.getFollowMember().split(",");
				String followMemberName = workFullManageService.getPeople(split3);
				workFull.setFollowMemberName(followMemberName);
			}
		}
		//查询是否存没有已通过的信息
		page.setList(list);
		model.addAttribute("page", page);
		return "modules/workfullpay/workFullManageListResult";
	}

	/**
	 * 工程计量支付列表页面
	 */
	@RequiresPermissions("workfullmanage:workFullPay:list")
	@RequestMapping(value = {"list", ""})
	public String list(String manage_id,WorkFullPay workFullPay,HttpServletResponse response, Model model) {
		if (StringUtils.isBlank(manage_id)){
			manage_id = request.getParameter("manage_id");
		}
		WorkFullManage workFullManage = null;
		if(!Strings.isNullOrEmpty(manage_id)){
			workFullManage = workFullManageService.get(manage_id);
			workFullPay.setWorkFullManageId(manage_id);
		}else{
			workFullManage = workFullManageService.get(workFullPay.getWorkFullManageId());
		}
		//查询是否存没有已通过的信息
		Page<WorkFullPay> page = workFullPayService.findPage(new Page<WorkFullPay>(request, response), workFullPay);
		model.addAttribute("page", page);
		model.addAttribute("workFullManage", workFullManage);
		return "modules/workfullpay/workFullPayList";
	}

	/**
	 * 查看，增加，编辑工程计量支付表单页面
	 */
	@RequiresPermissions(value={"workfullmanage:workFullPay:view","workfullmanage:workFullPay:add","workfullmanage:workFullPay:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkFullPay workFullPay, Model model) {
		String manage_id = request.getParameter("manage_id");
		String tabId = request.getParameter("tabId");
		String view = "workFullPayForm";
		if("0".equals(tabId)){
			view = "workFullPayFormDetail";
		}else if("1".equals(tabId)){
			WorkFullManage workFullManage = workFullManageService.get(manage_id);
			model.addAttribute("workFullManage",workFullManage);
			view = "projectResult";
		}else if("2".equals(tabId)){
			WorkFullManage workFullManage = workFullManageService.get(manage_id);
			model.addAttribute("workFullManage",workFullManage);
			view = "projectResultDetail";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workFullPay.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);
				workFullPay.setAct(act);
			}
			view = "workFullPayFormEdit";
		}
		workFullPay.setWorkFullManageId(manage_id);
		if(workFullPay.getIsNewRecord()) {
			//每次新增之前查询第一条记录的合同金额
			WorkFullPay countFlag = workFullPayService.getFirstRecord(workFullPay);
			if (countFlag != null) {
				String totalMoney = workFullPayService.querySum(countFlag);    //累计支付金额
				workFullPay.setArrangeMoney(countFlag.getArrangeMoney());
				if (!"0".equals(countFlag.getArrangeMoney())) {
					double v = (double) Double.valueOf(totalMoney).doubleValue() * 100 / Double.valueOf(countFlag.getArrangeMoney()).doubleValue();
					workFullPay.setCompletePerPay(String.valueOf(new BigDecimal(v).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
				} else {
					workFullPay.setCompletePerPay("0");
				}
				model.addAttribute("countFlag", workFullPay.getCountFlag());
				workFullPay.setTotalPayMoney(totalMoney);
			} else {
				model.addAttribute("countFlag", "0");
			}
			model.addAttribute("flag", "0"); //新增
		}else{
			model.addAttribute("flag", "1"); //修改
		}
		// 环节编号
		String taskDefKey = workFullPay.getAct().getTaskDefKey();
		// 修改环节
		if ("deptLeaderAudit".equals(taskDefKey)){
			view = "workFullPayAudit";
		}
		// 自定义流程都是以task开头
		if(StringUtils.isNotBlank(taskDefKey)&&taskDefKey.startsWith("task")){
			view = "workFullPayAudit";
		}

		model.addAttribute("manage_id",manage_id);
		model.addAttribute("workFullPay", workFullPay);
		return "modules/workfullpay/" + view;
	}

	/**
	 * 暂存数据
	 */
	@RequestMapping(value = "store")
	@ResponseBody
	public String store(WorkFullPay workFullPay,
						Model model,HttpServletResponse response,
						RedirectAttributes redirectAttributes) throws Exception {
		if (!beanValidator(model, workFullPay)){
			return form(workFullPay, model);
		}
		if(!workFullPay.getIsNewRecord()){//编辑表单保存
			if(VarStr.FULLPAYSTATUS[1].equals(workFullPay.getFullPayStatus()) || VarStr.FULLPAYSTATUS[3].equals(workFullPay.getFullPayStatus())){
				addMessage(redirectAttributes, "只有暂存状态和未通过状态的数据可修改");
				return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
			}
			WorkFullPay t = workFullPayService.get(workFullPay.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullPay, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workFullPayService.save(t);//保存
		}else{//新增表单保存
			workFullPay.setFullPayStatus("1");//暂存状态
			int statusNotFour = workFullPayService.getStatusNotFour(workFullPay);
			if(statusNotFour > 0){
				addMessage(redirectAttributes, "还有未审核通过的流程，暂无法提交申请");
				return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
			}
			//每次新增之前查询数据库中的记录数
			String s = workFullPayService.queryCount(workFullPay);
			workFullPay.setCountFlag(String.valueOf(Integer.parseInt(s) + 1));
			/*//将累计金额加上本次核对金额
			int nowToltalMoney = 0;
			if(Strings.isNullOrEmpty(workFullPay.getTotalPayMoney())){
				nowToltalMoney = Integer.parseInt(workFullPay.getConfirmPayMoney());
			}else{
				nowToltalMoney = Integer.parseInt(workFullPay.getConfirmPayMoney()) + Integer.parseInt(workFullPay.getTotalPayMoney());
			}*/
			//将累计金额加上本次核对金额
			Double nowToltalMoney = 0.0;
			if(Strings.isNullOrEmpty(workFullPay.getTotalPayMoney())){
				nowToltalMoney = Double.valueOf(workFullPay.getConfirmPayMoney()).doubleValue();//Integer.parseInt(workFullPay.getConfirmPayMoney());
			}else{
				nowToltalMoney = Double.valueOf(workFullPay.getConfirmPayMoney()).doubleValue()+Double.valueOf(workFullPay.getTotalPayMoney()).doubleValue();//Integer.parseInt(workFullPay.getConfirmPayMoney()) + Integer.parseInt(workFullPay.getTotalPayMoney());
			}

			workFullPay.setTotalPayMoney(new BigDecimal(nowToltalMoney).setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
			//将累计付款比例改为当前的比例
			String arrangeMoney = workFullPay.getArrangeMoney();
			if(StringUtils.isNotBlank(arrangeMoney) && !"0".equals(arrangeMoney)){
				double per = ((double) nowToltalMoney) * 100 / Integer.parseInt(arrangeMoney);
				workFullPay.setCompletePerPay(String.valueOf(new BigDecimal(per)
						.setScale(2,BigDecimal
								.ROUND_HALF_UP)
						.doubleValue()));
			}
			workFullPayService.save(workFullPay);//保存
		}
		addMessage(redirectAttributes, "保存工程计量支付信息成功");
		return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
	}
	/**
	 * 暂存数据
	 */
	@RequestMapping(value = "storewin")
	@ResponseBody
	public String storewin(WorkFullPay workFullPay,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception {
		if (!beanValidator(model, workFullPay)){
			return form(workFullPay, model);
		}
		HashMap<Object, Object> map = Maps.newHashMap();
		if(!workFullPay.getIsNewRecord()){//编辑表单保存
			if(VarStr.FULLPAYSTATUS[1].equals(workFullPay.getFullPayStatus()) || VarStr.FULLPAYSTATUS[3].equals(workFullPay.getFullPayStatus())){
				map.put("str","只有暂存状态和未通过状态的数据可修改");
				return JsonMapper.toJsonString(map);
			}
			WorkFullPay t = workFullPayService.get(workFullPay.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullPay, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workFullPayService.save(t);//保存
		}else{//新增表单保存
			workFullPay.setFullPayStatus("1");//暂存状态
			int statusNotFour = workFullPayService.getStatusNotFour(workFullPay);
			if(statusNotFour > 0){
				map.put("str","还有未审核通过的流程，暂无法提交申请");
				return JsonMapper.toJsonString(map);
			}
			//每次新增之前查询数据库中的记录数
			String s = workFullPayService.queryCount(workFullPay);
			workFullPay.setCountFlag(String.valueOf(Integer.parseInt(s) + 1));
			//将累计金额加上本次核对金额
			int nowToltalMoney = 0;
			if(Strings.isNullOrEmpty(workFullPay.getTotalPayMoney())){
				nowToltalMoney = Integer.parseInt(workFullPay.getConfirmPayMoney());
			}else{
				nowToltalMoney = Integer.parseInt(workFullPay.getConfirmPayMoney()) + Integer.parseInt(workFullPay.getTotalPayMoney());
			}
			workFullPay.setTotalPayMoney(String.valueOf(nowToltalMoney));
			//将累计付款比例改为当前的比例
			String arrangeMoney = workFullPay.getArrangeMoney();
			if(StringUtils.isNotBlank(arrangeMoney) && !"0".equals(arrangeMoney)){
				double per = ((double) nowToltalMoney) * 100 / Integer.parseInt(arrangeMoney);
				workFullPay.setCompletePerPay(String.valueOf(new BigDecimal(per)
						.setScale(2,BigDecimal
								.ROUND_HALF_UP)
						.doubleValue()));
			}
			workFullPayService.save(workFullPay);//保存
		}

		map.put("str","保存工程计量支付信息成功");
		return JsonMapper.toJsonString(map);
	}

	/**
	 * 保存工程计量支付
	 */
	@RequiresPermissions(value={"workfullmanage:workFullPay:add","workfullmanage:workFullPay:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkFullPay workFullPay, Model model,HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workFullPay)){
			return form(workFullPay, model);
		}
		Map<String, Object> variables = Maps.newHashMap();
		Role role = UserUtils.getSelectRole().get(0);
		StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
		buffer.append("bmzr");
		variables.put("SSRHbmzr", buffer.toString()); //设置部门负责人

		if(!workFullPay.getIsNewRecord()){//编辑表单保存
			if(VarStr.FULLPAYSTATUS[1].equals(workFullPay.getFullPayStatus()) || VarStr.FULLPAYSTATUS[3].equals(workFullPay.getFullPayStatus())){
				addMessage(redirectAttributes, "只有暂存状态和未通过状态的数据可修改");
				return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
			}
			workFullPay.setFullPayStatus(VarStr.FULLPAYSTATUS[1]);
			WorkFullPay t = workFullPayService.get(workFullPay.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullPay, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workFullPayService.save(t,variables);//保存
		}else{//新增表单保存
			int statusNotFour = workFullPayService.getStatusNotFour(workFullPay);
			if(statusNotFour > 0){
				addMessage(redirectAttributes, "还有未审核通过的流程，暂无法提交申请！！！");
				return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
			}
			//每次新增之前查询数据库中的记录数
			String s = workFullPayService.queryCount(workFullPay);
			workFullPay.setCountFlag(String.valueOf(Integer.parseInt(s) + 1));
			//将累计金额加上本次核对金额
			Double nowToltalMoney = 0.0;
			if(Strings.isNullOrEmpty(workFullPay.getTotalPayMoney())){
				nowToltalMoney = Double.valueOf(workFullPay.getConfirmPayMoney()).doubleValue();//Integer.parseInt(workFullPay.getConfirmPayMoney());
			}else{
				nowToltalMoney = Double.valueOf(workFullPay.getConfirmPayMoney()).doubleValue()+Double.valueOf(workFullPay.getTotalPayMoney()).doubleValue();//Integer.parseInt(workFullPay.getConfirmPayMoney()) + Integer.parseInt(workFullPay.getTotalPayMoney());
			}
			workFullPay.setTotalPayMoney(new BigDecimal(nowToltalMoney).setScale(2,   BigDecimal.ROUND_HALF_UP).toString());
			//将累计付款比例改为当前的比例
			String arrangeMoney = workFullPay.getArrangeMoney();
			if(StringUtils.isNotBlank(arrangeMoney) && !"0".equals(arrangeMoney)){
				double per = ((double) nowToltalMoney) * 100 / Integer.parseInt(arrangeMoney);
				workFullPay.setCompletePerPay(String.valueOf(new BigDecimal(per)
										.setScale(2,BigDecimal
											 .ROUND_HALF_UP)
												 .doubleValue()));
			}
			workFullPay.setFullPayStatus(VarStr.FULLPAYSTATUS[1]);
			workFullPayService.save(workFullPay,variables);//保存
		}
		addMessage(redirectAttributes, "保存工程计量支付成功");
		request.setAttribute("manage_id",workFullPay.getWorkFullManageId());
		return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
	}

	/**
	 * 保存工程计量支付
	 */
	@RequiresPermissions(value={"workfullmanage:workFullPay:add","workfullmanage:workFullPay:edit"},logical=Logical.OR)
	@RequestMapping(value = "savewin")
	@ResponseBody
	public String savewin(WorkFullPay workFullPay, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workFullPay)){
			return form(workFullPay, model);
		}
		HashMap<Object, Object> map = Maps.newHashMap();
		Map<String, Object> variables = Maps.newHashMap();
		Role role = UserUtils.getSelectRole().get(0);
		StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
		buffer.append("bmzr");
		variables.put("SSRHbmzr", buffer.toString()); //设置部门负责人

		if(!workFullPay.getIsNewRecord()){//编辑表单保存
			if(VarStr.FULLPAYSTATUS[1].equals(workFullPay.getFullPayStatus()) || VarStr.FULLPAYSTATUS[3].equals(workFullPay.getFullPayStatus())){
				map.put("str","只有暂存状态和未通过状态的数据可修改");
				return JsonMapper.toJsonString(map);
			}
			workFullPay.setFullPayStatus(VarStr.FULLPAYSTATUS[1]);
			WorkFullPay t = workFullPayService.get(workFullPay.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullPay, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workFullPayService.save(t,variables);//保存
		}else{//新增表单保存
			int statusNotFour = workFullPayService.getStatusNotFour(workFullPay);
			if(statusNotFour > 0){
				map.put("str","还有未审核通过的流程，暂无法提交申请");
				return JsonMapper.toJsonString(map);
			}
			//每次新增之前查询数据库中的记录数
			String s = workFullPayService.queryCount(workFullPay);
			workFullPay.setCountFlag(String.valueOf(Integer.parseInt(s) + 1));
			//将累计金额加上本次核对金额
			int nowToltalMoney = 0;
			if(Strings.isNullOrEmpty(workFullPay.getTotalPayMoney())){
				nowToltalMoney = Integer.parseInt(workFullPay.getConfirmPayMoney());
			}else{
				nowToltalMoney = Integer.parseInt(workFullPay.getConfirmPayMoney()) + Integer.parseInt(workFullPay.getTotalPayMoney());
			}
			workFullPay.setTotalPayMoney(String.valueOf(nowToltalMoney));
			//将累计付款比例改为当前的比例
			String arrangeMoney = workFullPay.getArrangeMoney();
			if(StringUtils.isNotBlank(arrangeMoney) && !"0".equals(arrangeMoney)){
				double per = ((double) nowToltalMoney) * 100 / Integer.parseInt(arrangeMoney);
				workFullPay.setCompletePerPay(String.valueOf(new BigDecimal(per)
						.setScale(2,BigDecimal
								.ROUND_HALF_UP)
						.doubleValue()));
			}
			workFullPay.setFullPayStatus(VarStr.FULLPAYSTATUS[1]);
			workFullPayService.save(workFullPay,variables);//保存
		}
		map.put("str","保存工程计量支付成功");
		return JsonMapper.toJsonString(map);
	}
	
	/**
	 * 删除工程计量支付
	 */
	@RequiresPermissions("workfullmanage:workFullPay:del")
	@RequestMapping(value = "delete")
	public String delete(WorkFullPay workFullPay, Model model,HttpServletResponse response, RedirectAttributes redirectAttributes) {
		//审核中的不能删除
//		if(VarStr.FULLPAYSTATUS[1].equals(workFullPay.getFullPayStatus()) || VarStr.FULLPAYSTATUS[3].equals(workFullPay.getFullPayStatus())){
//			addMessage(redirectAttributes, "只有暂存状态和未通过状态的数据可删除");
//			return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullPay/?repage";
//		}
		String currentId = UserUtils.getUser().getId();
		Role role = UserUtils.getSelectRole().get(0);
		//项目竣工之前项目登记人和项目经理可以删除
		/*if(!currentId.equals(workFullPay.getCreateBy().getId()) || !role.getEnname().contains("bmzr")){
			addMessage(redirectAttributes, "您没有权限做该操作");
			return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullPay/?repage";
		}*/
		WorkFullManage workFullManage = workFullManageService.get(workFullPay.getWorkFullManageId());
		//项目竣工
		/*if(!"4".equals(workFullManage.getFullProjectStatus()) || !role.getEnname().contains("bmzr")){
			addMessage(redirectAttributes, "项目已经竣工，只有项目经理可删除");
			model.addAttribute("workFullExecute",workFullPay);
			return list(workFullPay,response,model);
		}*/
		//项目竣工之后 只有项目经理可以删除
		workFullPayService.delete(workFullPay);
		addMessage(redirectAttributes, "删除工程计量支付成功");
		return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
	}
	
	/**
	 * 批量删除工程计量支付
	 */
	@RequiresPermissions("workfullmanage:workFullPay:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workFullPayService.delete(workFullPayService.get(id));
		}
		addMessage(redirectAttributes, "删除工程计量支付成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullPay/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workfullmanage:workFullPay:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkFullPay workFullPay, Model model, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工程计量支付"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkFullPay> page = workFullPayService.findPage(new Page<WorkFullPay>(request, response, -1), workFullPay);
    		new ExportExcel("工程计量支付", WorkFullPay.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出工程计量支付记录失败！失败信息："+e.getMessage());
		}
		return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
    }

	/**
	 * 导入Excel数据

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

	/**
	 * 查询待办列表
	 * @return
	 */

	@RequestMapping("/queryToList")
	public String queryToList(Act act, Model model){
		act.setProcDefKey("workfullpay");
		List<Act> list = new ArrayList<>();
		list.addAll(actTaskService.todoList(act));
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<WorkFullPay> lists = new ArrayList<WorkFullPay>();

		List<Activity> activities = activityService.groupByActivityMenu("f5f37f9906374d5abbf57c95dfa28869",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.todoList(act));
		}

		Role role = UserUtils.getSelectRole().get(0);
		String officeId = "";
		if ("4".equals(role.getDataScope())){
			User user = UserUtils.getUser();
			officeId = user.getOffice().getId();
		}
		for (Act a : list) {
			String taskDefinitionKey = a.getTask().getTaskDefinitionKey();
			if(taskDefinitionKey!=null && !"modifyApply".equals(taskDefinitionKey) && !taskDefinitionKey.contains("audit") && !"deptLeaderAudit".equals(taskDefinitionKey)) {
				WorkFullPay workFullPay = workFullPayService.getByProcessInstanceId(a.getProcInsId());
				if (workFullPay != null) {
					WorkFullManage workFullManage = workFullManageService.get(workFullPay.getWorkFullManageId());
					if (workFullManage.getCompanyId().equals(companyId)) {
						workFullPay.setCreateBy(UserUtils.get(workFullPay.getCreateBy().getId()));
						User createBy = UserUtils.get(workFullPay.getCreateBy().getId());
						if (StringUtils.isNotBlank(officeId)) {
							if (officeId.equals(createBy.getOffice().getId())) {
								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());
									}
								}
								workFullPay.setAct(a);
								lists.add(workFullPay);
							}
						} else {
							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());
								}
							}
							workFullPay.setAct(a);
							lists.add(workFullPay);
						}
					}
				}
			}
		}
		model.addAttribute("list", lists);
		return "modules/workfullpay/payTodoList";
	}

	/**
	 * 查询已办列表
	 * @return
	 */
	@RequestMapping("/queryCompleteList")
	public String queryCompleteList(Act act,Model model){
		act.setProcDefKey("workfullpay");
		List<WorkFullPay> page = workFullPayService.historicList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();

		List<Activity> activities = activityService.groupByActivityMenu("f5f37f9906374d5abbf57c95dfa28869",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			page.addAll(workFullPayService.historicList(act));
		}

		model.addAttribute("list",page);
		return "modules/workfullpay/payHistoricList";
	}

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnLeave")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		String manage_id = request.getParameter("manage_id");
		// 获取流程XML上的表单KEY
		String formKey = "/workfullmanage/workFullPay/form?manage_id="+manage_id;
//		String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
		// 获取流程实例对象
		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 model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkFullPay workFullPay, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		String taskDefKey = workFullPay.getAct().getTaskDefKey();
		if("modifyApply".equals(taskDefKey)){
			workFullPay.getAct().setComment("重新申请");
			return form(workFullPay, model);
		}else{
			/*if (StringUtils.isBlank(workFullPay.getAct().getComment())){
				addMessage(model, "请填写审核意见。");
				return form(workFullPay, model);
			}*/
		}
		String str  = workFullPayService.auditSave(workFullPay, VarStr.FULLPAYSTATUS);
		addMessage(redirectAttributes, str);
		return list(workFullPay.getWorkFullManageId(),new WorkFullPay(),response,model);
	}

	/**
	 * 工程计量支付审核
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAuditTwo")
	@ResponseBody
	public String saveAuditTwo(WorkFullPay workFullPay, Model model, RedirectAttributes redirectAttributes) {
		HashMap<Object, Object> map = Maps.newHashMap();
		String taskDefKey = workFullPay.getAct().getTaskDefKey();
		if("modifyApply".equals(taskDefKey)){
			workFullPay.getAct().setComment("重新申请");
		}else{
			/*if (StringUtils.isBlank(workFullPay.getAct().getComment())){
				map.put("str","请填写审核意见");
				return JsonMapper.toJsonString(map);
			}*/
		}
		workFullPayService.auditSave(workFullPay, VarStr.FULLPAYSTATUS);
		map.put("str","保存工程计量支付成功");
		return JsonMapper.toJsonString(map);
	}

	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkFullPay workFullPay, Model model) {
		model.addAttribute("processInstanceId", workFullPay.getProcessInstanceId());
		return "modules/workfullmanage/workRecordTrack";
	}
	

}