package com.blueland.bpm.manage.service;

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

import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blueland.bpm.common.util.DateUtil;
import com.blueland.bpm.engine.core.model.ActivityInstanceModel;
import com.blueland.bpm.engine.util.BaseSpringJdbcDao;

import groovy.util.logging.Slf4j;

/**
 * @作者     lw
 * @创建时间  2018年10月11日
 * @说明     
 */
@Slf4j
@Service
public class ProcessUpdateTimeService extends BaseSpringJdbcDao<String,String>{
	@Autowired
	HistoryService historyService;
	/**
	 * 更新环节实例时间
	 */
	public boolean updateActInstTime(List<ActivityInstanceModel> actInstList) {
		if (actInstList == null || actInstList.isEmpty()) {
			return false;
		}
		String uptTaskSql = "update  ACT_HI_TASKINST h set h.end_time_=:endTime,h.start_time_=:createTime,h.DURATION_=:duration,h.sender=:sendUserId,h.send_user_name=:sendUserName,h.sender_org_id=:senderOrgId,h.sender_org_name=:senderOrgName   WHERE h.id_=:actInstId";
		String uptActSql = "update  ACT_HI_ACTINST h set h.end_time_=:endTime,h.start_time_=:createTime,h.DURATION_=:duration,h.sender=:sendUserId,h.send_user_name=:sendUserName,h.sender_org_id=:senderOrgId,h.sender_org_name=:senderOrgName   WHERE h.task_id_=:actInstId";
		String uptUniteTaskSql = "update  t_unitework_history h set h.unite_deal_time=:endTime,h.unite_send_time=:createTime,h.unite_send_userid=:sendUserId,h.unite_send_username=:sendUserName,h.unite_send_orgid=:senderOrgId,h.unite_send_orgname=:senderOrgName where h.UNITE_CUR_ACTINSTID=:actInstId";
		String uptUniteHisSql = "update  t_unitework_task h set h.unite_deal_time=:endTime,h.unite_send_time=:createTime,h.unite_send_userid=:sendUserId,h.unite_send_username=:sendUserName,h.unite_send_orgid=:senderOrgId,h.unite_send_orgname=:senderOrgName where h.UNITE_CUR_ACTINSTID=:actInstId";
		String uptActEndSql = "update  ACT_HI_ACTINST h set h.end_time_=:endTime,h.start_time_=:createTime   WHERE h.id_=:actInstId";
		String uptActRuTask = "UPDATE ACT_RU_TASK t set t.CREATE_TIME_=:createTime,t.SEND_USER_ID=:sendUserId,t.SEND_USER_NAME=:sendUserName,t.SENDER_ORG_ID=:senderOrgId,t.SENDER_ORG_NAME=:senderOrgName  WHERE t.ID_=:actInstId";
		for (ActivityInstanceModel model : actInstList) {
			try {
				if (StringUtils.isEmpty(model.getActInstId())) {
					continue;
				}
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("actInstId", model.getActInstId());
				if (model.getCreateTime() == null) {
					params.put("createTime", null);
				}else{
					params.put("createTime", model.getCreateTime());
				}
				if (model.getFinishTime() == null) {
					params.put("endTime", null);
				}else{
					params.put("endTime", model.getFinishTime());
				}
				if (model.getCreateTime() == null || model.getFinishTime() == null) {
					params.put("duration", 0);
				}else{
					params.put("duration", model.getFinishTime().getTime()-model.getCreateTime().getTime());
				}
				params.put("sendUserId", model.getSendUserId());
				params.put("sendUserName", model.getSendUserName());
				params.put("senderOrgId", model.getSenderOrgId());
				params.put("senderOrgName", model.getSenderOrgName());
				if(model.getActState().equals("0")){
					this.namedParameterJdbcTemplate.update(uptTaskSql, params);
					this.namedParameterJdbcTemplate.update(uptActSql, params);
					this.namedParameterJdbcTemplate.update(uptUniteTaskSql, params);
					this.namedParameterJdbcTemplate.update(uptUniteHisSql, params);
					this.namedParameterJdbcTemplate.update(uptActRuTask, params);
				}else{
					this.namedParameterJdbcTemplate.update(uptActEndSql, params);
				}
			} catch (Exception e) {
				log.error("updateActInstTime error ,actInstModel:" + model, e);
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 更新流程实例时间
	 */
	public boolean updateProcTime(String procInstId, String  createTime, String endTime) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("procInstId", procInstId);
		params.put("createTime", createTime);
		params.put("endTime", endTime);
		try {
			if(createTime=="" || endTime==""){
				params.put("duration", 0);
			}else{
				params.put("duration", DateUtil.convertStringToDate("yyyy-mm-dd HH:mm:ss", endTime).getTime()-DateUtil.convertStringToDate("yyyy-mm-dd HH:mm:ss", createTime).getTime());
			}
		} catch (Exception e1) {
			log.error("updateActInstTime duration error ,actInstModel:" + params, e1);
		}
		String uptProcSql = "update  ACT_HI_PROCINST h set h.end_time_=to_date(:endTime,'yyyy-mm-dd hh24:mi:ss'),h.start_time_=to_date(:createTime,'yyyy-mm-dd hh24:mi:ss'),DURATION_=:duration WHERE h.id_=:procInstId";
		try {

			this.namedParameterJdbcTemplate.update(uptProcSql, params);
		} catch (Exception e) {
			log.error("updateActInstTime error ,actInstModel:" + params, e);
			return false;
		}
		return true;
	}
	
	public List<ActivityInstanceModel> getAllHistTaskByProcess(String procInstId) {
		if (StringUtils.isEmpty(procInstId)) {
			return null;
		}
		List<HistoricTaskInstance> historicTaskInstances = historyService
				.createHistoricTaskInstanceQuery()
				.processInstanceId(procInstId)
				.orderByHistoricTaskInstanceEndTime().asc().list();
		if (historicTaskInstances == null || historicTaskInstances.isEmpty())
			return null;
		List<ActivityInstanceModel> activityInstanceModels = new ArrayList<ActivityInstanceModel>();
		for (HistoricTaskInstance task : historicTaskInstances) {
			activityInstanceModels.add(ActivityInstanceModel.buildAndActDef(
					(HistoricTaskInstance) task, null));
		}
		return activityInstanceModels;
	}
	/**
	 * 删除当前流程环节
	 * @param actInstList
	 * @return
	 */
	public boolean delActInst(List<ActivityInstanceModel> actInstList) {
		if (actInstList == null || actInstList.isEmpty()) {
			return false;
		}
		String delTaskSql = "DELETE  ACT_HI_TASKINST h   WHERE h.id_=:actInstId";
		String delActSql = "DELETE  ACT_HI_ACTINST h   WHERE h.task_id_=:actInstId";
		String delUniteTaskSql = "DELETE  t_unitework_history h  where h.UNITE_CUR_ACTINSTID=:actInstId";
		String delUniteHisSql = "DELETE  t_unitework_task h where h.UNITE_CUR_ACTINSTID=:actInstId";
		for (ActivityInstanceModel model : actInstList) {
			try {
				if (StringUtils.isEmpty(model.getActInstId())) {
					continue;
				}
				Map<String, Object> params = new HashMap<String, Object>();
			
				params.put("actInstId", model.getActInstId());
				this.namedParameterJdbcTemplate.update(delTaskSql, params);
				this.namedParameterJdbcTemplate.update(delActSql, params);
				this.namedParameterJdbcTemplate.update(delUniteTaskSql, params);
				this.namedParameterJdbcTemplate.update(delUniteHisSql, params);
			} catch (Exception e) {
				log.error("updateActInstTime error ,actInstModel:" + model, e);
				return false;
			}
		}
		return true;
	}
	public static void main(String[] args) {
		System.out.println(DateUtils.addDays(new Date(),9).getTime()-new Date().getTime());
	}
	/**
	 * 改当前流程环节信息
	 * @param actInstList
	 * @return
	 */
	public Boolean updateActInst(List<ActivityInstanceModel> actInstList) {
		if (actInstList == null || actInstList.isEmpty()) {
			return false;
		}
		for (ActivityInstanceModel model : actInstList) {
			try {
				if (StringUtils.isEmpty(model.getActInstId())) {
					continue;
				}
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("actInstId", model.getActInstId());
				params.put("sendUserId", model.getSendUserId());
				params.put("sendUserName", model.getSendUserName());
				params.put("senderOrgId", model.getSenderOrgId());
				params.put("senderOrgName", model.getSenderOrgName());
				params.put("prevActInstId", model.getPrevActInstId());
				params.put("prevActDefName", model.getPrevActDefName());
				params.put("prevActDefId", model.getPrevActDefId());
				params.put("startTime", model.getCreateTime());
				String uptTaskSql = " update ACT_HI_ACTINST  h set h.sender=:sendUserId,h.send_user_name=:sendUserName,h.sender_org_id=:senderOrgId,h.sender_org_name=:senderOrgName,h.pre_act_id=:prevActDefId,h.pre_act_name=:prevActDefName,h.pre_act_inst_id=:prevActInstId ";
				if(model.getCreateTime()!=null){
					uptTaskSql=uptTaskSql+ ",h.start_time_=:startTime  ";
				}	
				uptTaskSql=uptTaskSql+ " WHERE h.task_id_=:actInstId";
				String uptActSql = " update ACT_HI_TASKINST  h set h.sender=:sendUserId,h.send_user_name=:sendUserName,h.sender_org_id=:senderOrgId,h.sender_org_name=:senderOrgName,h.pre_task_def_key=:prevActDefId,h.pre_task_def_name=:prevActDefName,h.pre_task_id=:prevActInstId ";
				if(model.getCreateTime()!=null){
					uptActSql=uptActSql+ ",h.start_time_=:startTime   ";
				}
				uptActSql=uptActSql+ " WHERE h.id_=:actInstId";
				String uptUniteTaskSql = " update t_unitework_history h set h.unite_send_userid=:sendUserId,h.unite_send_username=:sendUserName,h.unite_send_orgid=:senderOrgId,h.unite_send_orgname=:senderOrgName,h.unite_prev_actdefid=:prevActDefId,h.unite_prev_actdefname=:prevActDefName,h.unite_prev_actinstid=:prevActInstId ";
				if(model.getCreateTime()!=null){
					uptUniteTaskSql=uptUniteTaskSql+ ",h.unite_send_time=:startTime ";
				}
				uptUniteTaskSql=uptUniteTaskSql+ " where h.UNITE_CUR_ACTINSTID=:actInstId ";
				String uptUniteHisSql = " update t_unitework_task h set h.unite_send_userid=:sendUserId,h.unite_send_username=:sendUserName,h.unite_send_orgid=:senderOrgId,h.unite_send_orgname=:senderOrgName,h.unite_prev_actdefid=:prevActDefId,h.unite_prev_actdefname=:prevActDefName,h.unite_prev_actinstid=:prevActInstId ";
				if(model.getCreateTime()!=null){	
					uptUniteHisSql=uptUniteHisSql+ ",h.unite_send_time=:startTime ";
				}
				uptUniteHisSql=uptUniteHisSql+ " where h.UNITE_CUR_ACTINSTID=:actInstId";
				this.namedParameterJdbcTemplate.update(uptTaskSql, params);
				this.namedParameterJdbcTemplate.update(uptActSql, params);
				this.namedParameterJdbcTemplate.update(uptUniteTaskSql, params);
				this.namedParameterJdbcTemplate.update(uptUniteHisSql, params);
				
			} catch (Exception e) {
				log.error("updateActInstTime error ,actInstModel:" + model, e);
				return false;
			}
		}
		return true;
	}
	
}
