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

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.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workcontractrev.entity.WorkContractRe;
import com.jeeplus.modules.workcontractrev.service.WorkContractReService;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;

/**
 * 合同评审Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/workcontractre/workContractRe")
public class WorkContractReController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkContractReService workContractReService;

	@ModelAttribute
	public WorkContractRe get(@RequestParam(required=false) String id) {
		WorkContractRe entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workContractReService.get(id);
		}
		if (entity == null){
			entity = new WorkContractRe();
		}
		return entity;
	}
	
	/**
	 * 职级调整列表页面
	 */
	@RequiresPermissions("workcontractre:workContractRe:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkContractRe workContractRe, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkContractRe> page = workContractReService.findPage(new Page<WorkContractRe>(request, response), workContractRe); 
		model.addAttribute("page", page);
		return "modules/workcontractre/workContractReList";
	}

	/**
	 * 查看，增加，编辑表单页面
	 */
	@RequiresPermissions(value={"workcontractre:workContractRe:view","workcontractre:workContractRe:add","workcontractre:workContractRe:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkContractRe workContractRe, Model model) {
		String flat=request.getParameter("tabId");
		model.addAttribute("workContractRe", workContractRe);
		return "modules/workcontractre/workContractReForm";
	}

	@RequestMapping(value = "selectclient")
	public String selectclientAhref(WorkContractRe workContractRe, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String searchLabel1, String searchKey1, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkContractRe> page = workContractReService.findPage1(new Page<WorkContractRe>(request, response), workContractRe);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("searchLabel1", searchLabel1);
		model.addAttribute("searchKey1", searchKey1);
		model.addAttribute("obj", workContractRe);
		model.addAttribute("page", page);
		return "modules/sys/gridselectRe";
	}

	@RequestMapping(value = "getRow")
	@ResponseBody
	public String getPNumberr() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkContractRe workContractRe = workContractReService.get(obj);
		WorkClientInfo workClientInfo = workContractRe.getWorkClientInfoList().get(0);
		map.put("money",workContractRe.getMoney());
		map.put("id",workClientInfo.getId());
		map.put("name",workClientInfo.getName());
		map.put("companyType", DictUtils.getMainDictLabel(workClientInfo.getCompanyType(),"company_type",""));

		map.put("companyIndustry", DictUtils.getMainDictLabel(workClientInfo.getCompanyIndustry(),"company_industry",""));
		if(workClientInfo.getArea()!=null){
			map.put("areaName",workClientInfo.getArea().getName());
		}
		return JsonMapper.toJsonString(map);
	}

	/**
	 * 保存
	 */
	@RequiresPermissions(value={"workcontractre:workContractRe:add","workcontractre:workContractRe:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkContractRe workContractRe, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workContractRe)){
			return form(workContractRe, model);
		}
		workContractRe.setState("2");
		if(!workContractRe.getIsNewRecord()){//编辑表单保存
			WorkContractRe t = workContractReService.get(workContractRe.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workContractRe, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			String str =workContractReService.saveChange(t);//保存
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "合同评审申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "合同评审申请已经提交");
			}
		}else{//新增表单保存
			workContractRe.setCompanyId(UserUtils.getSelectCompany().getId());
			workContractRe.setOfficeId(UserUtils.getSelectOffice().getId());
			String str =workContractReService.saveChange(workContractRe);//保存
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "合同评审申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "合同评审申请已经提交");
			}
		}
		return "redirect:"+Global.getAdminPath()+"/workcontractre/workContractRe/?repage";
	}
	/**
	 * 保存调整
	 */
	@RequiresPermissions(value={"workcontractre:workContractRe:add","workcontractre:workContractRe:edit"},logical=Logical.OR)
	@RequestMapping(value = "store")
	public String store(WorkContractRe workContractRe, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workContractRe)){
			return form(workContractRe, model);
		}
		workContractRe.setState("1");
		if(!workContractRe.getIsNewRecord()){//编辑表单保存
			WorkContractRe t = workContractReService.get(workContractRe.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workContractRe, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workContractReService.save(t);//保存
		}else{//新增表单保存
			workContractRe.setCompanyId(UserUtils.getSelectCompany().getId());
			workContractRe.setOfficeId(UserUtils.getSelectOffice().getId());
			workContractReService.save(workContractRe);//保存
		}
		addMessage(redirectAttributes, "保存合同评审成功");
		return "redirect:"+Global.getAdminPath()+"/workcontractre/workContractRe/?repage";
	}
	/**
	 * 删除职级调整
	 */
	@RequiresPermissions("workcontractre:workContractRe:del")
	@RequestMapping(value = "delete")
	public String delete(WorkContractRe workContractRe, RedirectAttributes redirectAttributes) {
		if("5".equals(workContractRe.getState())|| "2".equals(workContractRe.getState())){
			if("5".equals(workContractRe.getState())){
				addMessage(redirectAttributes, "已审批通过，无法删除");
				return "redirect:"+Global.getAdminPath()+"/workcontractre/workContractRe/?repage";
			}else{
				addMessage(redirectAttributes, "正在审核中，无法删除");
				return "redirect:"+Global.getAdminPath()+"/workcontractre/workContractRe/?repage";
			}
		}
		workContractReService.delete(workContractRe);
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/workcontractre/workContractRe/?repage";
	}



	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkContractRe workContractRe, Model model,
							RedirectAttributes redirectAttributes) {
//		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workContractRe.getAct().getTaskDefKey();

			List<User> users = null;
			if ("bmzr".equals(taskDefKey)){
				users = UserUtils.getByProssType(workContractRe.getProcessInstanceId(),2);
				if (users==null ) {
//					users = UserUtils.getByRoleActivityEnname("fgld", 3, workRegularApply.getOfficeId(), "19", user);
					users = UserUtils.getByRoleActivityEnname("bzshb", 3, workContractRe.getOfficeId(), "66", workContractRe.getCreateBy());
				}
			}else  if ("fgld".equals(taskDefKey)){
				users = UserUtils.getByProssType(workContractRe.getProcessInstanceId(),3);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("cwzg", 3, workContractRe.getOfficeId(), "66", workContractRe.getCreateBy());

			}else  if ("zjl".equals(taskDefKey)){
				users = UserUtils.getByProssType(workContractRe.getProcessInstanceId(),4);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("fzjl", 3, workContractRe.getOfficeId(), "66", workContractRe.getCreateBy());

			}else if ("rlzy".equals(taskDefKey)){
				users = UserUtils.getByProssType(workContractRe.getProcessInstanceId(),5);
				if (users==null )
					users = UserUtils.getByRoleActivityEnname("zjl", 3, workContractRe.getOfficeId(), "66", workContractRe.getCreateBy());
			}else if ("zjll".equals(taskDefKey)){
				List<User> list = Lists.newArrayList();
				list.add(UserUtils.getUser());
				users = list;
			}
			else if ("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workContractRe.getProcessInstanceId(),1);
			}
				String str = workContractReService.auditSave(workContractRe,users);
				addMessage(redirectAttributes, str);

//		}catch (Exception e){
//			logger.info("Exception e:"+e);
//			addMessage(redirectAttributes, "审批失败");
//		}
		if (StringUtils.isNotBlank(workContractRe.getHome()) && "home".equals(workContractRe.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workcontractre/workContractRe/?repage";
		}

	}
	//	审批页面
	@RequestMapping(value = "audit")
	public String workContractInfoAudit(Act act, WorkContractRe workContractRe, Model model) {

		if (act.getProcInsId() != null) {
			if (actTaskService.getProcIns(act.getProcInsId()) != null) {
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			} else {
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}
		}
		if (act != null && StringUtils.isNotBlank(act.getTaskId())) {
			workContractRe.setAct(act);
			model.addAttribute("processInstanceId", workContractRe.getProcessInstanceId());
		}
		model.addAttribute("workContractRe", workContractRe);
		return "modules/workcontractre/workContractReAudit";
	}

	@RequiresPermissions(value={"workcontractRe:workContractRe:edit"},logical=Logical.OR)
	@RequestMapping(value = "modify")
	public String modify(WorkContractRe workContractRe, Model model, RedirectAttributes redirectAttributes) {
		workContractRe=workContractReService.get(workContractRe.getId());
		ProcessInstance processInstance = actTaskService.getProcIns(workContractRe.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);
			workContractRe.setAct(act);
		}
		model.addAttribute("workContractRe", workContractRe);
		return "modules/workcontractre/workContractReModifyApply";
	}

	@RequestMapping(value = "getProcess")
	public String getProcess(WorkContractRe workContractRe, Model model, HttpServletRequest request){
		model.addAttribute("processInstanceId", workContractRe.getProcessInstanceId());
		return "modules/workcontractre/workContractReTask";
	}

	@RequiresPermissions(value={"workcontractre:workContractRe:edit"},logical=Logical.OR)
	@RequestMapping(value = "revoke")
	public String revoke(HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
		HashMap<String, String> requestMap = findRequestMap(request);
		String processInstanceId = requestMap.get("processInstanceId");
		String id = requestMap.get("id");
		try {
			workContractReService.cancelProcess(id);
			addMessage(redirectAttributes, "撤回申请成功");
		}catch (Exception e){
			logger.info(e.getMessage());
			addMessage(redirectAttributes, "撤回申请失败");
		}
		return "redirect:" + Global.getAdminPath() + "/workcontractre/workContractRe/?repage";
	}


	@RequestMapping(value = "view")
	public String view(WorkContractRe workContractRe, Model model) {
		model.addAttribute("workContractRe", workContractRe);
		return "modules/workcontractre/workContractReView";
	}
}