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

import java.util.ArrayList;
import java.util.HashMap;
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.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.JPushClientUtil;
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.buydetails.entity.BuyDetails;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workapprovalcopy.entity.ApprovalCopy;
import com.jeeplus.modules.workapprovalcopy.service.ApprovalCopyService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
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 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.oaperformance.entity.OaPerformance;
import com.jeeplus.modules.oaperformance.service.OaPerformanceService;

/**
 * 绩效自评Controller
 * @author liuw
 * @version 2018-01-17
 */
@Controller
@RequestMapping(value = "${adminPath}/oaperformance/oaPerformance")
public class OaPerformanceController extends BaseController {

	@Autowired
	private OaPerformanceService oaPerformanceService;
	@Autowired
	private ApprovalCopyService approvalCopyService;
	@Autowired
	private PushinfoService pushinfoService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActAuditService actAuditService;
	@ModelAttribute
	public OaPerformance get(@RequestParam(required=false) String id) {
		OaPerformance entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = oaPerformanceService.get(id);
		}
		if (entity == null){
			entity = new OaPerformance();
		}
		return entity;
	}
	
	/**
	 * 绩效自评列表页面
	 */
	@RequiresPermissions("oaperformance:oaPerformance:list")
	@RequestMapping(value = {"list", ""})
	public String list(OaPerformance oaPerformance, HttpServletRequest request, HttpServletResponse response, Model model) {
		oaPerformance.setOfficeId(UserUtils.getSelectOffice().getId());
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			oaPerformance.setCompanyId(user.getComId());
			if (!UserUtils.isManager()){
				oaPerformance.setCreateBy(user);
			}
		}
		Page<OaPerformance> page = oaPerformanceService.findPage(new Page<OaPerformance>(request, response), oaPerformance); 
		model.addAttribute("page", page);
		return "modules/oaperformance/oaPerformanceList";
	}

	/**
	 * 查看，增加，编辑绩效自评表单页面
	 */
	@RequiresPermissions(value={"oaperformance:oaPerformance:view","oaperformance:oaPerformance:add","oaperformance:oaPerformance:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(OaPerformance oaPerformance, Model model,HttpServletRequest request) {
		String view = "oaPerformanceForm";
		String tabId = request.getParameter("tabId");
		if("0".equals(tabId)){
			view = "oaPerformanceView";
		}
		// 环节编号
		String taskDefKey = oaPerformance.getAct().getTaskDefKey();
		// 审核环节
		if ("audit1".equals(taskDefKey)){
			if (org.apache.commons.lang3.StringUtils.isBlank(oaPerformance.getAct().getStatus())){
				model.addAttribute("disabled","true");
				oaPerformance.getAct().setProcInsId(oaPerformance.getProcessInstanceId());
			}else {
				model.addAttribute("disabled","false");
			}
			view = "oaPerformanceAudit";
		}else if ("apply_end".equals(taskDefKey)){
			view = "oaPerformanceAudit";
		}
		//
		else if ("modifyApply".equals(taskDefKey)){
			view = "oaPerformanceForm";
		}
		model.addAttribute("oaPerformance", oaPerformance);
		return "modules/oaperformance/"+ view;

		/*model.addAttribute("oaPerformance", oaPerformance);
		return "modules/oaperformance/oaPerformanceForm";*/
	}

	/**
	 * 保存绩效自评
	 */
	@RequiresPermissions(value={"oaperformance:oaPerformance:add","oaperformance:oaPerformance:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(OaPerformance oaPerformance, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (StringUtils.isNotBlank(oaPerformance.getId())) {
			OaPerformance t = oaPerformanceService.get(oaPerformance.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(oaPerformance, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			if (t.getStatus().equals("3") || t.getStatus().equals("4")){
				addMessage(redirectAttributes, "已结束流程不能修改！");
			}else {
				oaPerformanceService.save(t);
			}
		} else {
			try {
				oaPerformance.setStatus("1");
				String approverId = "";
				List<String> adds = oaPerformance.getAdds();
				for(int i = 0;i<adds.size();i++){
					if(i + 1 == adds.size()){
						approverId += adds.get(i);
					}else{
						approverId += adds.get(i) + ",";
					}
				}
				oaPerformance.setIds(approverId);

				Map<String, Object> variables = Maps.newHashMap();
				String alias = "1";
				List<String> assigneeList = new ArrayList<String>(); //分配任务的人员
				if (approverId != null && !approverId.equals("")) {
					if (!UserUtils.getUser().isAdmin() && approverId.contains(UserUtils.getUser().getId())) {
						logger.error("启动绩效自评流程失败：");
						addMessage(redirectAttributes, "申请失败,审批人不能为本人！");
						return "redirect:" + adminPath + "/oaperformance/oaPerformance";
					}
					String[] approverIds = approverId.split(",");
					for (int i = 0; i < approverIds.length; i++) {
						assigneeList.add(approverIds[i]);
					}
					alias = approverIds[0];
				}
				variables.put("assigneeList", assigneeList);
				variables.put("count", assigneeList.size());
				User CC = new User();
				CC.setId(oaPerformance.getCCId());
				User user = UserUtils.getUser();
				//oaBuy.setUser(user);
				oaPerformance.setCreateBy(user);
				oaPerformance.setUpdateBy(user);
				oaPerformance.setStatus("1");
				oaPerformance.setDelFlag("0");
				oaPerformance.setCompanyId(UserUtils.getSelectCompany() == null ? "" : UserUtils.getSelectCompany().getId());
				oaPerformance.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
				oaPerformanceService.save(oaPerformance, variables);
				ApprovalCopy approvalCopy = new ApprovalCopy();
				approvalCopy.setCCId(oaPerformance.getCCId());
				approvalCopy.setUserId(user.getId());
				approvalCopy.setType("oaPerformance");
				approvalCopy.setApprovalId(oaPerformance.getId());
				approvalCopy.setApproverId(approverId);
				approvalCopy.setReadFlag("0");
				approvalCopyService.save(approvalCopy);

				//给抄送人、审批人发送通知
				if(approvalCopy!=null && org.apache.commons.lang3.StringUtils.isNotBlank(approvalCopy.getId())){
					String chaosongIds = approvalCopy.getCCId();//给所有抄送人发送通知
					String shenpiIds = alias;//给审批流程的第一个人发送通知
					oaPerformanceService.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
					String content = "审批信息 申请人:" + user.getName() + ",绩效自评申请: 待审批!";
					UserUtils.pushIm(alias,content);
				}


				//推送
				String title = "审批";
				String content = UserUtils.getUser().getName() + "的绩效自评申请需要你审批";
				String status = "待审批";
				String remarks = "绩效自评申请内容类型：" + oaPerformance.getLastPerformance();
				Map extras = new HashMap();
				extras.put("type", "4001");
				extras.put("id", oaPerformance.getId());
				extras.put("procDefKey", "oaPerformance");

				boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
				Pushinfo pushinfo = new Pushinfo();
				pushinfo.setCurrentUser(UserUtils.getUser());
				pushinfo.setRemarks(remarks);
				pushinfo.setUserId(UserUtils.getUser().getId());
				pushinfo.setType("4001");
				pushinfo.setPushId(oaPerformance.getId());
				pushinfo.setTitle(title);
				pushinfo.setContent(content);
				pushinfo.setStatus(status);
				pushinfo.setAddcontent("oaPerformance");
				pushinfo.setPushUserId(alias);
				pushinfo.setParentType("singleApproval");
				pushinfo.setMobile("ios,android");
				pushinfo.setCompanyId(UserUtils.getSelectCompany() == null ? "" : UserUtils.getSelectCompany().getId());
				pushinfoService.save(pushinfo);
				if (b) {
					addMessage(redirectAttributes, "绩效自评申请已经提交");
				} else {
					logger.error("启动绩效自评申请流程失败：");
					addMessage(redirectAttributes, "绩效自评申请失败,绩效自评申请推送失败！");
					return "redirect:" + adminPath + "/oaperformance/oaPerformance";
				}
			} catch (Exception e) {
				logger.error("启动绩效自评申请流程失败：", e);
				addMessage(redirectAttributes, "系统内部错误！");
			}
		}
		return "redirect:"+Global.getAdminPath()+"/oaperformance/oaPerformance/?repage";
		/*addMessage(redirectAttributes, "保存绩效自评成功");
		return "redirect:"+Global.getAdminPath()+"/oaperformance/oaPerformance/?repage";*/
	}
	
	/**
	 * 删除绩效自评
	 */
	@RequiresPermissions("oaperformance:oaPerformance:del")
	@RequestMapping(value = "delete")
	public String delete(OaPerformance oaPerformance, RedirectAttributes redirectAttributes) {
		oaPerformanceService.delete(oaPerformance);
		addMessage(redirectAttributes, "删除绩效自评成功");
		return "redirect:"+Global.getAdminPath()+"/oaperformance/oaPerformance/?repage";
	}
	
	/**
	 * 批量删除绩效自评
	 */
	@RequiresPermissions("oaperformance:oaPerformance:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			oaPerformanceService.delete(oaPerformanceService.get(id));
		}
		addMessage(redirectAttributes, "删除绩效自评成功");
		return "redirect:"+Global.getAdminPath()+"/oaperformance/oaPerformance/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("oaperformance:oaPerformance:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(OaPerformance oaPerformance, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "绩效自评"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<OaPerformance> page = oaPerformanceService.findPage(new Page<OaPerformance>(request, response, -1), oaPerformance);
    		new ExportExcel("绩效自评", OaPerformance.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出绩效自评记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/oaperformance/oaPerformance/?repage";
    }

	/**
	 * 导入Excel数据

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

	/**
	 * 待办任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"oaPerformanceTodoList"})
	public String oaPerformanceTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("oaPerformance");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<OaPerformance> lists = new ArrayList<OaPerformance>();
		for (Act a : list) {
			OaPerformance oaAll = oaPerformanceService.getByProcessInstanceId(a.getProcInsId());
			if (oaAll != null && oaAll.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());
					}
				}
				oaAll.setAct(a);
//				if (com.jeeplus.common.utils.StringUtils.isNotBlank(oaAll.getId())){
//					oaAll.setName(officeService.get(oaAll.getCompanyId()).getName());
//				}
				lists.add(oaAll);
			}
		}
		model.addAttribute("list", lists);
		return "modules/oaperformance/oaPerformanceTodoList";
	}


	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"oaPerformanceHistoricList"})
	public String oaPerformanceHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("oaPerformance");
		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<OaPerformance> lists = new ArrayList<OaPerformance>();
		for (Act a : list) {
			OaPerformance oaAll = oaPerformanceService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (oaAll != null && oaAll.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				oaAll.setAct(a);
//				if (StringUtils.isNotBlank(a.getId())){
//					oaAll.setName(officeService.get(oaAll.getCompanyId()).getName());
//				}
//				if (oaAll.getCreateDate()!=null){
//					oaAll.setTime(sdf.format(oaAll.getCreateDate()));
//				}
				lists.add(oaAll);
			}
		}
		model.addAttribute("list", lists);
		return "modules/oaperformance/oaPerformanceHistoricList";
	}

	/**
	 * 工单执行（完成任务）
	 * @param
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(OaPerformance oaPerformance, Model model) {
		//oaPerformanceService.auditSave(oaPerformance);
		Act act = oaPerformance.getAct();
		actAuditService.saveAudit(act, act.getProcInsId(), "oaPerformance", oaPerformance.getAct().getComment(), oaPerformance.getId(), "2");
		if (oaPerformance!=null && org.apache.commons.lang3.StringUtils.isNotBlank(oaPerformance.getHome()) && oaPerformance.getHome().equals("home")){
			return "redirect:" + adminPath + "/home";
		}
		return "redirect:" + adminPath + "/oaperformance/oaPerformance";
	}
	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnLeave")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		//String formKey = "/oa/leave/applyOnLeave";
		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);
	}

	@RequestMapping(value = "getProcess")
	public String getProcess(OaPerformance oaPerformance, Model model) {
		model.addAttribute("processInstanceId", oaPerformance.getProcessInstanceId());
		return "modules/oaperformance/oaPerformanceTrack";
	}

	/**
	 * 采购申请撤销
	 * @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");
		AjaxJson j = new AjaxJson();
		try {
			OaPerformance oaAll = oaPerformanceService.getById(id);
			oaAll.setStatus("5");
			oaAll.preUpdate();
			oaPerformanceService.update(oaAll);
			Map map = oaPerformanceService.getBuyById(id,"1");
			j.put("data",map);
			actTaskService.endProcessInstance(processInstanceId, "");
			j.setMsg("撤销申请成功");

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

}