/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.flow.demo.leave.service.impl;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.flow.business.service.IFlowService;
import org.springblade.flow.core.constant.ProcessConstant;
import org.springblade.flow.core.entity.BladeFlow;
import org.springblade.flow.core.utils.FlowUtil;
import org.springblade.flow.core.utils.TaskUtil;
import org.springblade.flow.demo.leave.entity.ProcessLeave;
import org.springblade.flow.demo.leave.mapper.LeaveMapper;
import org.springblade.flow.demo.leave.service.ILeaveService;
import org.springblade.flow.engine.service.FlowEngineService;
import org.springblade.modules.flowable.examineInfo.service.impl.ExamineInfoServiceImpl;
import org.springblade.modules.flowable.processForm.pojo.entity.ProcessDefAuditStepEntity;
import org.springblade.modules.flowable.processForm.pojo.vo.ProcessDefReq;
import org.springblade.modules.flowable.processForm.service.impl.ProcessDefAuditStepServiceImpl;
import org.springblade.modules.flowable.processForm.utils.FormUtils;
import org.springblade.modules.operation.service.impl.PlatformEmployeeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Slf4j
@Service
@AllArgsConstructor
public class LeaveServiceImpl extends BaseServiceImpl<LeaveMapper, ProcessLeave> implements ILeaveService {

	private final IFlowService flowService;

	private final TaskService taskService;

	private final FlowEngineService flowEngineService;

	@Autowired
	private ProcessDefAuditStepServiceImpl auditStepService;

	@Autowired
	private PlatformEmployeeServiceImpl employeeService;

	@Autowired
	private ExamineInfoServiceImpl examineInfoService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean startProcess(ProcessLeave leave) {
		String businessTable = FlowUtil.getBusinessTable(ProcessConstant.LEAVE_KEY);
		if (Func.isEmpty(businessTable)) {
			throw new ServiceException("流程启动失败,未找到相关业务表");
		}
		if (Func.isEmpty(leave.getId())) {
			// 保存leave
			leave.setApplyTime(DateUtil.now());
			save(leave);
			// 启动流程
			Kv variables = Kv.create()
				.set(ProcessConstant.TASK_VARIABLE_CREATE_USER, AuthUtil.getUserName())
				.set("taskUser", TaskUtil.getTaskUser(leave.getTaskUser()))
				.set("days", DateUtil.between(leave.getStartTime(), leave.getEndTime()).toDays());
			BladeFlow flow = flowService.startProcessInstanceById(leave.getProcessDefinitionId(), FlowUtil.getBusinessKey(businessTable, String.valueOf(leave.getId())), variables);
			if (Func.isNotEmpty(flow)) {
				log.debug("流程已启动,流程ID:" + flow.getProcessInstanceId());
				// 返回流程id写入leave
				leave.setProcessInstanceId(flow.getProcessInstanceId());
				updateById(leave);
			} else {
				throw new ServiceException("开启流程失败");
			}
		} else {

			updateById(leave);
		}
		return true;
	}


	@Transactional(rollbackFor = Exception.class)
	public String startProcessFlowable(String applicationId, ProcessDefReq processDef, String formId, Date submitTime, String UserName, String content, String processInsName, String province, String city){
		log.info(" >>>>>>>>>>>>启动流程 startProcessFlowable  {applicationId}:{},formId:{};" ,applicationId,formId);
		Map<String,Object> map=new HashMap<>();
		map.put("applicationId",applicationId);
		map.put("formId",formId);
		map.put("reject","1");
		String processDefId= processDef.getId();
		List<ProcessDefAuditStepEntity> auditItems = auditStepService.findListByDefId(processDefId);
		Random rand = new Random();
		String oneAuditUseId="";
		for(ProcessDefAuditStepEntity r:auditItems){
			List<String> emps=new ArrayList<>();
			String userId="";
			if("1".equals(r.getAuditType())){  // 1平台角色 2 平台员工
				//根据角色，获取角色员工(要根据员工的数据权限分配)
				emps=employeeService.findEmpUserId(r.getRoleId(),province,city,"");
			}else{
				String str=r.getEmpUserId();
				//获取符合数据权限的员工id
				String ifOrder="1";
				if("3".equals(r.getAuditMethod())){  //3 依次审批  那么不需要排序
					ifOrder="";
				}
				emps=employeeService.getFitUserEmpId(str,province,city,"",ifOrder);
			}
			if(emps==null || emps.size()==0){
				throw new RuntimeException(r.getItemName()+" 该节点没有符合审批设置的员工审批，不能启动流程！");
			}
			if("1".equals(r.getAuditMethod())||"2".equals(r.getAuditMethod())||"3".equals(r.getAuditMethod())){  //1 或签 2会签  3 依次审批
				map.put("assigneeList"+r.getSort(),emps);
			}else{   //任意人
				int i=rand.nextInt(emps.size());
				userId=emps.get(i);
				map.put("assignee"+r.getSort(),userId);
			}
			if(r.getSort()==1){
				if(StringUtil.isNotBlank(userId)){
					oneAuditUseId=userId;
				}else {
					oneAuditUseId=String.join(",",emps);
				}
			}
		}
		processDef.setOneAuditUseId(oneAuditUseId);
		log.info(">>>>>>>>>>>>startProcessFlowable  map:{}",new Gson().toJson(map));
		BladeFlow flow= flowService.startProcessInstanceByKey("Process_"+processDefId,formId,map);
		if (Func.isNotEmpty(flow)) {
			log.debug("流程已启动,流程ID:" + flow.getProcessInstanceId());
			//log.info( " >>>> 流程提交成功.流程Id为：" + flow.getProcessInstanceId());
			String str=UserName+"，提交表单"+(StringUtil.isNotBlank(content)?"；"+content:"");
			//保存流程的过程信息
			examineInfoService.saveExamineInfo(applicationId,str,submitTime,UserName,formId);
			// 返回流程id写入leave
			return flow.getProcessInstanceId();

		} else {
			throw new ServiceException("开启流程失败");
		}

		//log.info(" >>>>>>>>>> 流程启动成功 startProcessFlowable  service  ");
		//return "";
	}


	/**
	 * 流程审批通过
	 * @param content   审核备注
	 * @param applicationId  当前申请的id
	 * @param currentUser     当前用户
	 */
	@Transactional(rollbackFor = Exception.class)
	public void approveTask(Task task, String content, String applicationId, BladeUser currentUser, String formId){
		Date date=new Date();
		log.info(">>>>>>>>>>>>>>>>>applicationId:{},task:{}",applicationId,task);

		String UserName = currentUser.getUserName();
		String type="；";
		if (!"编辑后提交".equals(content)) {
			type="，同意 ；";
		}
		String str = UserName + type+ (StringUtil.isNotBlank(content) ?content : "");
		//保存流程的过程信息
		examineInfoService.saveExamineInfo(applicationId,str,date,UserName,formId);
		if (task != null) {
			taskService.claim(task.getId(),currentUser.getUserId().toString());  //领取任务
			log.info(UserName+" >>>>>> 审批流程通过 {task} :" +task.getId());
			taskService.setOwner(task.getId(),UserName);
			Map<String, Object> map =new HashMap<>();
			map.put("approve", true);
			map.put("reject","1");
			taskService.complete(task.getId(),map);
		}

	}

	/**
	 * 驳回一个流程
	 * @param content   审核备注
	 * @param applicationId  当前申请的id
	 * @param currentUser    当前用户
	 */
	@Transactional(rollbackFor = Exception.class)
	public void rejectTask(Task task, String content, String applicationId, BladeUser currentUser,String formId,String createBy){
		log.info(">>>>>>>>>>>>>>>>rejectTask  taskId:{},applicationId:{}",task.getId(),applicationId);
		String UserName = currentUser.getNickName();

		Date date=new Date();
		String str=UserName+"，驳回"+(StringUtil.isNotBlank(content)?"；"+content:"");
		examineInfoService.saveExamineInfo(applicationId,str,date,UserName,formId);
		taskService.claim(task.getId(),currentUser.getUserId().toString());  //领取任务
		log.info(" >>>>>> 审批流程驳回 {task} :" +task);
		Map<String, Object> map = new HashMap<>();
		map.put("approve",false);
		map.put("reject","2");
		map.put("assigneeUserId",createBy);
		taskService.complete(task.getId(), map);
	}

	public void deleteApplication(String applicationId,String processInstanceId,String UserName,String status,String formId){
		log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>删除申请  deleteApplication applicationId:{};processInstanceId:{}",applicationId,processInstanceId);
		//删除任务
		if("2".equals(status) || "3".equals(status)){ //处理中的申请  才删除流程
			List<Task> taskList=taskService.createTaskQuery().processInstanceId(processInstanceId).list();
			if(taskList.size()>0){
				log.info(">>>>>>>>>>>>> 开始删除任务  {} ",processInstanceId);
				//删除任务
				flowEngineService.deleteProcessInstance(processInstanceId,"删除任务！");
				log.info(">>>>>>>>>>>  删除任务成功  ");
			}
		}
		//保存流程的过程信息
		examineInfoService.saveExamineInfo(applicationId,UserName +" (撤销申请)",new Date(),UserName,formId);
	}

}
