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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.common.json.AjaxJson;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
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.DictUtils;
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.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workreimbursement.service.WorkReimbursementService;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
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.workrelationship.entity.WorkRelationship;
import com.jeeplus.modules.workrelationship.service.WorkRelationshipService;

/**
 * 劳动关系Controller
 * @author lw
 * @version 2018-07-31
 */
@Controller
@RequestMapping(value = "${adminPath}/workrelationship/workRelationship")
public class WorkRelationshipController extends BaseController {

	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	protected 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 WorkProjectUserDao workProjectUserDao;
	@Autowired
	private WorkRelationshipService workRelationshipService;
	
	@ModelAttribute
	public WorkRelationship get(@RequestParam(required=false) String id) {
		WorkRelationship entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workRelationshipService.get(id);
		}
		if (entity == null){
			entity = new WorkRelationship();
		}
		return entity;
	}
	
	/**
	 * 劳动关系列表页面
	 */
	@RequiresPermissions("workrelationship:workRelationship:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkRelationship workRelationship, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkRelationship> page = workRelationshipService.findPage(new Page<WorkRelationship>(request, response), workRelationship); 
		model.addAttribute("page", page);
		return "modules/workrelationship/workRelationshipList";
	}

	/**
	 * 查看，增加，编辑劳动关系表单页面
	 */
	//@RequiresPermissions(value={"workrelationship:workRelationship:view","workrelationship:workRelationship:add","workrelationship:workRelationship:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkRelationship workRelationship, Model model) {

		String view = "workRelationshipForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workRelationshipView";
		}else if("3".equals(tabId)&& "1".equals(workRelationship.getRemarks())){
			ProcessInstance processInstance = actTaskService.getProcIns(workRelationship.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);
				workRelationship.setAct(act);
				view = "workRelationshipModify";
			}
		}
		// 环节编号
		if("rlzybzr".equals(workRelationship.getAct().getTaskDefKey())){
			view = "workRelationshipAudit";
		}else if("rlzy".equals(workRelationship.getAct().getTaskDefKey())){
			workRelationship.setTransactTime(new Date());
			view = "workRelationshiprlzyAudit";
		}
		else if("qyr".equals(workRelationship.getAct().getTaskDefKey())){
			if("1".equals(workRelationship.getRemarks())){
				view = "workRelationshipqyrAuditFirst";
			}else{
				view = "workRelationshipqyrAudit";
			}
		}
		model.addAttribute("workRelationship", workRelationship);
		return "modules/workrelationship/"+view;

	}

	@RequestMapping(value = "store")
	public String store(WorkRelationship workRelationship,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workRelationship)){
			return form(workRelationship, model);
		}
		User user = workRelationship.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workRelationship.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
		}
		workRelationship.setStatus("1"); //暂存状态
		workRelationship.setCompanyId(UserUtils.getSelectCompany().getId());
		workRelationship.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workRelationship.getProcessInstanceId()) && workRelationship.getProcessInstanceId().equals("NULL")){
			workRelationship.setProcessInstanceId("");
		}
		if(!workRelationship.getIsNewRecord()){//编辑表单保存
			WorkRelationship t = workRelationshipService.get(workRelationship.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workRelationship, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			if(t!=null && StringUtils.isNotBlank(t.getContractType()) && t.getContractType().contains(",")){
				t.setContractType(t.getContractType().replace(",",""));
			}
			workRelationshipService.save(t);//保存
		}else{//新增表单保存
			if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
				workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
			}
			if(workRelationship!=null && workRelationship.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workRelationship.getWorkStaffBasicInfo().getId())){
				WorkRelationship w = new WorkRelationship();
				w.setWorkStaffBasicInfo(workRelationship.getWorkStaffBasicInfo());
				w.setStatus("5");
				List<WorkRelationship> list = workRelationshipService.findList(w);
				if(list == null || list.size() == 0){
					//首次签约
					workRelationship.setRemarks("1");
				}
			}
				workRelationshipService.save(workRelationship);//保存
		}
		addMessage(redirectAttributes, "保存劳动关系成功");
		return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
	}

	/**
	 * 保存劳动关系
	 */
	@RequiresPermissions(value={"workrelationship:workRelationship:add","workrelationship:workRelationship:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkRelationship workRelationship, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workRelationship)){
			return form(workRelationship, model);
		}
		User user = workRelationship.getCreateBy();
		String sta = workRelationship.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
		}
		//状态设置为审核中
		workRelationship.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workRelationshipService.get(workRelationship.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workRelationship.setCompanyId(UserUtils.getSelectCompany().getId());
			workRelationship.setOfficeId(UserUtils.getSelectOffice().getId());
			if(workRelationship!=null && StringUtils.isNotBlank(workRelationship.getContractType()) && workRelationship.getContractType().contains(",")){
				workRelationship.setContractType(workRelationship.getContractType().replace(",",""));
			}
			if(workRelationship!=null && workRelationship.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workRelationship.getWorkStaffBasicInfo().getId())){
				WorkRelationship w = new WorkRelationship();
				w.setWorkStaffBasicInfo(workRelationship.getWorkStaffBasicInfo());
				w.setStatus("5");
				List<WorkRelationship> list = workRelationshipService.findList(w);
				if(list == null || list.size() == 0){
					//首次签约
					workRelationship.setRemarks("1");
				}
			}
			String str = null;
			if("1".equals(workRelationship.getRemarks())){
				 str = workRelationshipService.saves(workRelationship, variables,processInstanceId);
			}else{
				str = workRelationshipService.save(workRelationship, variables,processInstanceId);
			}
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "劳动关系提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "劳动关系申请已经提交");
			}

		} catch (Exception e) {
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "劳动关系申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkRelationship workRelationship, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workRelationship.getAct().getTaskDefKey();
			Office office = null;
			if(workRelationship.getWorkStaffBasicInfo()!=null){
				String sid = workRelationship.getWorkStaffBasicInfo().getId();
				if(StringUtils.isNotBlank(sid)){
					WorkStaffBasicInfo w = workStaffBasicInfoService.getAchives(sid);
					if(w!=null){
						office = w.getOffice();
					}
				}
			}
			if("1".equals(workRelationship.getRemarks())){
				List<User> users = UserUtils.getByProssType(workRelationship.getProcessInstanceId(),1);
				String flag = workRelationship.getAct().getFlag();
				if ("yes".equals(flag) && (users==null || users.size()==0)){
					addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
				}else {
					String str = workRelationshipService.auditSaves(workRelationship,users);
					addMessage(redirectAttributes, str);
				}
			}else{
				List<User> users = null;
				if ("rlzybzr".equals(taskDefKey)){
					users = UserUtils.getByProssType(workRelationship.getProcessInstanceId(),2);
					if (users==null )
						users = UserUtils.getByRoleActivityEnname("rlzy",3,office.getId(),"18",workRelationship.getCreateBy());
				}else  if ("rlzy".equals(taskDefKey)){
					String sid = workRelationship.getWorkStaffBasicInfo().getUserId();
					User u = UserUtils.get(sid);
					List<User> list = new ArrayList<>();
					list.add(u);
					users = list;
				}
				else if ("qyr".equals(taskDefKey)){
					users = UserUtils.getByProssType(workRelationship.getProcessInstanceId(),3);
				}
				String flag = workRelationship.getAct().getFlag();
				if ("1".equals(flag) && users==null){
					addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
				}else {
					String str = workRelationshipService.auditSave(workRelationship,users);
					addMessage(redirectAttributes, str);
				}
			}
		}catch (Exception e){
			logger.info("Exception e:"+e);
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workRelationship.getHome()) && "home".equals(workRelationship.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workrelationship/workRelationship/?repage";
		}
	}
	/**
	 * 删除劳动关系
	 */
	@RequiresPermissions("workrelationship:workRelationship:del")
	@RequestMapping(value = "delete")
	public String delete(WorkRelationship workRelationship, RedirectAttributes redirectAttributes) {
		workRelationshipService.delete(workRelationship);
		addMessage(redirectAttributes, "删除劳动关系成功");
		return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
	}
	
	/**
	 * 批量删除劳动关系
	 */
	@RequiresPermissions("workrelationship:workRelationship:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workRelationshipService.delete(workRelationshipService.get(id));
		}
		addMessage(redirectAttributes, "删除劳动关系成功");
		return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workrelationship:workRelationship:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkRelationship workRelationship, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "劳动关系"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkRelationship> page = workRelationshipService.findPage(new Page<WorkRelationship>(request, response, -1), workRelationship);
    		new ExportExcel("劳动关系", WorkRelationship.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出劳动关系记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workrelationship:workRelationship: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<WorkRelationship> list = ei.getDataList(WorkRelationship.class);
			for (WorkRelationship workRelationship : list){
				try{
					workRelationshipService.save(workRelationship);
					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()+"/workrelationship/workRelationship/?repage";
    }
	
	/**
	 * 下载导入劳动关系数据模板
	 */
	@RequiresPermissions("workrelationship:workRelationship:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "劳动关系数据导入模板.xlsx";
    		List<WorkRelationship> list = Lists.newArrayList(); 
    		new ExportExcel("劳动关系数据", WorkRelationship.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
    }
	
	
	/**
	 * 选择人员主键
	 */
	@RequestMapping(value = "selectworkStaffBasicInfo")
	public String selectworkStaffBasicInfo(WorkStaffBasicInfo workStaffBasicInfo, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkStaffBasicInfo> page = workRelationshipService.findPageByworkStaffBasicInfo(new Page<WorkStaffBasicInfo>(request, response),  workStaffBasicInfo);
		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("obj", workStaffBasicInfo);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}

	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkRelationship workRelationship,Model model) {
		model.addAttribute("processInstanceId", workRelationship.getProcessInstanceId());
		return "modules/workrelationship/Track";
	}
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkRelationship workRelationship,RedirectAttributes redirectAttributes){
		workRelationshipService.cancelInvalidate(workRelationship);
		return "redirect:"+Global.getAdminPath()+"/workrelationship/workRelationship/?repage";
	}

	/**
	 *
	 */
	@ResponseBody
	@RequestMapping(value = "selectStaffUser")
	public AjaxJson selectLinkman(String sId, String rId, HttpServletRequest request, HttpServletResponse response, Model model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		AjaxJson j = new AjaxJson();
		if(StringUtils.isBlank(sId)){
			sId = "1";
		}
		List<WorkRelationship> list = workRelationshipService.getWorkRelationships(rId,sId);
		if(list!=null && list.size()>0){
			for (WorkRelationship w:
				 list) {
				if(StringUtils.isNotBlank(w.getContractType())){
					w.setContractType(DictUtils.getDictLabel(w.getContractType(),"relsp_cType",""));
				}
				if(StringUtils.isNotBlank(w.getContractLimit())){
					w.setContractLimit(DictUtils.getDictLabel(w.getContractLimit(),"contract_limit",""));
				}
				if(w.getContractEndTime()!=null){
					w.setEndDate(sdf.format(w.getContractEndTime()));
				}
				if(w.getContractStartTime()!=null){
					w.setStartDate(sdf.format(w.getContractStartTime()));
				}
				if(w.getTransactTime()!=null){
					w.settDate(sdf.format(w.getTransactTime()));
				}
				if(w.getWorkAttachments()!=null && w.getWorkAttachments().size()>0){
					WorkClientAttachment workClientAttachment= w.getWorkAttachments().get(0);
					if(workClientAttachment!=null){
						w.setUrl(workClientAttachment.getUrl());
						w.setuName(workClientAttachment.getAttachmentName());
					}
				}
			}
		}
		j.put("list", list);


		return j;
	}
}