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

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
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.act.utils.ProcessDefCache;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workengineeringproject.entity.WorkEngineeringProject;
import com.jeeplus.modules.workengineeringproject.service.WorkEngineeringProjectService;
import com.jeeplus.modules.workfullmanage.dao.WorkFullManageDao;
import com.jeeplus.modules.workfullmanage.dao.WorkFullRecordDao;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.entity.WorkFullRecord;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全过程管理项目归档Service
 * @author mapengbo
 * @version 2017-11-01
 */
@Service
@Transactional(readOnly = true)
public class WorkFullRecordService extends CrudService<WorkFullRecordDao, WorkFullRecord> {

	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkFullRecordDao workFullRecordDao;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkEngineeringProjectService workEngineeringProjectService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkFullManageDao workFullManageDao;
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;

	public WorkFullRecord get(String id) {
		return  workFullRecordDao.findUniqueByProperty("work_full_manage_id",id);
//		return super.get(id);
	}
	public WorkFullRecord getById(String id) {
		return super.get(id);
	}
	public WorkFullRecord gett(String id) {
		WorkFullRecord workFullRecord = super.get(id);

		WorkClientAttachment workClientAttachment = new WorkClientAttachment();
		workClientAttachment.setAttachmentId(id);
		//workClientAttachment.setAttachmentFlag("66");
		workFullRecord.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));

		return workFullRecord;
	}

	public List<WorkFullRecord> findList(WorkFullRecord workFullRecord) {
		return super.findList(workFullRecord);
	}

	public Page<WorkFullRecord> findPage(Page<WorkFullRecord> page, WorkFullRecord workFullRecord) {
		return super.findPage(page, workFullRecord);
	}

	@Transactional(readOnly = false)
	public void save(WorkFullRecord workFullRecord) {
		super.save(workFullRecord);
		//附件信息
		for (WorkClientAttachment workClientAttachment : workFullRecord.getWorkAttachments()){
			if (workClientAttachment.getId() == null){
				continue;
			}
			if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())){
				workClientAttachment.setAttachmentId(workFullRecord.getId());
				workClientAttachment.setAttachmentFlag("66");
				if (StringUtils.isBlank(workClientAttachment.getId())  || "null".equals(workClientAttachment.getId())&&StringUtils.isNotBlank(workClientAttachment.getUrl()) && !workClientAttachment.getUrl().equals("null")){
					workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
					workClientAttachment.preInsert();
					workClientAttachmentDao.insert(workClientAttachment);
				}else{
					workClientAttachment.preUpdate();
					workClientAttachmentDao.update(workClientAttachment);
				}
			}else{
				workClientAttachmentDao.delete(workClientAttachment);
			}
		}
	}

	@Transactional(readOnly = false)
	public void startposs(WorkFullRecord workFullRecord,Map<String, Object> variables,boolean flag,String type,String roleEnname) {
		dao.insert(workFullRecord);
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(UserUtils.getUser().getId());
		// 启动流程
		String businessKey = workFullRecord.getId().toString();
		if(flag) {
			variables.put("type", "workfullrecord");
		}else{
			variables.put("type", "engineeringrecord");
		}
		variables.put("busId", businessKey);
		variables.put("title", "审批单："+workFullRecord.getWorkFullManage().getId());//设置标题；
		ProcessInstance processInstance = null;
		if(flag){
			processInstance = runtimeService.startProcessInstanceByKey(ActUtils.PD_WORKFULLREOCRD[0], businessKey, variables);
		}else{
			processInstance = runtimeService.startProcessInstanceByKey(ActUtils.PD_ENGINEERINGRECORD[0], businessKey, variables);
		}
		workFullRecord.setProcessInstance(processInstance);

		// 更新流程实例ID
		workFullRecord.setProcessInstanceId(processInstance.getId());
		workFullRecordDao.updateProcessInstanceId(workFullRecord);
		if(!flag){
			WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.get(workFullRecord.getWorkFullManage().getId());
			if(workEngineeringProject!=null) {
				workEngineeringProject.setRemarks("发起归档");
				workEngineeringProject.preUpdate();
				workEngineeringProjectService.update(workEngineeringProject);
			}
		}
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setNotifyId(workFullRecord.getId());
		workProjectNotify.setCompanyId(workFullRecord.getCompanyId());
		workProjectNotify.setTitle("项目归档审批申请");
		workProjectNotify.setNotifyRole(roleEnname);
		workProjectNotify.setContent(workFullRecord.getAct().getComment());
		workProjectNotify.setType(type);
		workProjectNotify.setStatus("0");
		workProjectNotify.setRemarks("待审批");
		workProjectNotifyService.save(workProjectNotify);
	}

	@Transactional(readOnly = false)
	public void delete(WorkFullRecord workFullRecord) {
		WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.get(workFullRecord.getWorkEngineeringProject().getId());
		workEngineeringProject.setStatus("5");
		workEngineeringProject.preUpdate();
		workEngineeringProjectService.save(workEngineeringProject);
		super.delete(workFullRecord);
	}

	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkFullRecord getByProcessInstanceId(String processInstanceId) {
		WorkFullRecord workFullRecord = workFullRecordDao.getByProcessInstanceId(processInstanceId);
		return workFullRecord;
	}

	/**
	 * 获取已办任务
	 * @return
	 */
	public List<WorkFullRecord> historicList(Act act){
		String userId = UserUtils.getUser().getId();
		HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().finished().taskAssignee(userId);
		// 设置查询条件
		if (StringUtils.isNotBlank(act.getProcDefKey())){
			query.processDefinitionKey(act.getProcDefKey());
		}
		if (act.getBeginDate() != null){
			query.taskCompletedAfter(act.getBeginDate());
		}
		if (act.getEndDate() != null){
			query.taskCompletedBefore(act.getEndDate());
		}
		List<HistoricTaskInstance> list = query.list();
		List<WorkFullRecord> list1 = new ArrayList<>();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		for (HistoricTaskInstance histTask : list) {
			WorkFullRecord workFullRecord = this.getByProcessInstanceId(histTask.getProcessInstanceId());
			if (workFullRecord != null && workFullRecord.getCompanyId().equals(companyId)) {
				workFullRecord.setCreateBy(UserUtils.get(workFullRecord.getCreateBy().getId()));
				historyService.getHistoricIdentityLinksForProcessInstance(histTask.getProcessInstanceId());
				act.setHistTask(histTask);
				act.setVars(histTask.getProcessVariables());
				act.setProcDef(ProcessDefCache.get(histTask.getProcessDefinitionId()));
				act.setStatus("finish");
				workFullRecord.setAct(act);
				list1.add(workFullRecord);
			}
		}
		return list1;
	}

	/**
	 * 审核流程
	 */
	@Transactional(readOnly = false)
	public void auditSave(WorkFullRecord workFullRecord, String status[],String type) {
		actTaskService.claim(workFullRecord.getAct().getTaskId(), UserUtils.getUser().getId());
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workFullRecord.getAct().getTaskDefKey();
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workFullRecord.setBackRecordStatus(("yes".equals(workFullRecord.getAct().getFlag())?status[1]:status[2]));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		Role role = UserUtils.getSelectRole().get(0);
		StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
		StringBuffer gly = DateUtils.getByEnnme(role.getEnname());
		buffer.append("bmzr");
		gly.append("glygd");
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setRemarks("待通知");
		// 审核环节
		String str = "";
		if ("deptLeaderAudit".equals(taskDefKey)){
			exp = "deptLeaderPass";
			workProjectNotify.setRemarks("待审批");
			if ("yes".equals(workFullRecord.getAct().getFlag())){
				workProjectNotify.setNotifyRole(gly.toString());
				str = "项目归档审核：待审批!";
			}else {
				str = "项目归档审核：被驳回!";
				workProjectNotify.setUser(workFullRecord.getCreateBy());
			}
		}
		else if ("recordUser".equals(taskDefKey)){
			exp = "recordPass";
			workFullRecord.setManageUser(UserUtils.getUser().getId());
			workProjectNotify.setUser(workFullRecord.getCreateBy());
			if ("yes".equals(workFullRecord.getAct().getFlag())){
				str = "项目归档审核: 已同意!";
				workFullRecord.setBackRecordStatus(status[3]);
			}else {
				str = "项目归档审核：被驳回!";
				workFullRecord.setBackRecordStatus(status[5]);
			}
		}
		else if ("modifyApply".equals(taskDefKey)){
			exp = "modifyApply";
			if ("yes".equals(workFullRecord.getAct().getFlag())){
				workProjectNotify.setNotifyRole(buffer.toString());
				workProjectNotify.setRemarks("待审批");
				str = "项目归档审核：待审批!";
			}
		}
		else if ("apply_end".equals(taskDefKey)){
		}
		// 未知环节，直接返回
		else{
			return;
		}
		// 设置意见
		workFullRecord.getAct().setComment(("yes".equals(workFullRecord.getAct().getFlag())?"[同意] ":"[驳回] ")+workFullRecord.getAct().getComment());
		workFullRecord.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(workFullRecord.getAct().getFlag())? true : false);
		// 提交流程任务
		actTaskService.complete(workFullRecord.getAct().getTaskId(), workFullRecord.getAct().getProcInsId(), workFullRecord.getAct().getComment(), vars);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workFullRecord.getId());
		workProjectNotifyService.readByNotifyId(notify);
		workFullRecordDao.update(workFullRecord);
		workProjectNotify.setNotifyId(workFullRecord.getId());
		workProjectNotify.setCompanyId(workFullRecord.getCompanyId());
		workProjectNotify.setContent(workFullRecord.getAct().getComment());
		workProjectNotify.setType(type);
		workProjectNotify.setStatus("0");
		boolean state = actTaskService.isProcessEnd(workFullRecord.getAct().getProcInsId());
		if(!state) {
			str = "yes".equals(workFullRecord.getAct().getFlag())?"您的项目归档审核：已通过":"您的项目归档审核：未通过";
			if("yes".equals(workFullRecord.getAct().getFlag())){
				if (StringUtils.isNotBlank(workFullRecord.getWorkFullManage().getId()) && type.equals("15")){
					WorkFullManage workFullManage = workFullManageDao.get(workFullRecord.getWorkFullManage().getId());
					workFullManage.setFullProjectStatus("6");
					workFullManage.preUpdate();
					workFullManageDao.update(workFullManage);
				}else if (StringUtils.isNotBlank(workFullRecord.getWorkEngineeringProject().getId()) && type.equals("4")){
					WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.get(workFullRecord.getWorkEngineeringProject().getId());
					workEngineeringProject.setRemarks("已归档");
					workEngineeringProject.preUpdate();
					workEngineeringProjectService.save(workEngineeringProject);
				}
			}
		}
		if (StringUtils.isNotBlank(str)) {
			workProjectNotify.setTitle(str);
			workProjectNotifyService.save(workProjectNotify);
		}
	}

	/**
	 * 查询文件管理员
	 * 公司编号和角色别名 @return
	 */
	public HashMap<Object,Object> queryWjgly(String company_id, String enname){
		HashMap<Object, Object> map = Maps.newHashMap();
		map.put("company_id",company_id);
		map.put("enname",enname);
		return workFullRecordDao.queryWjgly(map);
	}
}