/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.workorder.publicevent.service.impl;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.flow.core.constant.ProcessConstant;
import org.springblade.flow.core.entity.BladeFlow;
import org.springblade.flow.core.feign.IFlowClient;
import org.springblade.flow.core.utils.FlowUtil;
import org.springblade.flow.core.utils.TaskUtil;
import org.springblade.workorder.common.FlowStepConst;
import org.springblade.workorder.publicevent.dto.PublicEventDTO;
import org.springblade.workorder.publicevent.entity.PublicEvent;
import org.springblade.workorder.publicevent.vo.PublicEventVO;
import org.springblade.workorder.publicevent.mapper.PublicEventMapper;
import org.springblade.workorder.publicevent.service.IPublicEventService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static org.springblade.workorder.common.FlowStepConst.*;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-04-09
 */
@Service
@Slf4j
@AllArgsConstructor
public class PublicEventServiceImpl extends BaseServiceImpl<PublicEventMapper, PublicEvent> implements IPublicEventService {
	private final IFlowClient flowClient;

	@Override
	public IPage<PublicEventVO> selectPublicEventPage(IPage<PublicEventVO> page, PublicEventVO publicEvent) {
		return page.setRecords(baseMapper.selectPublicEventPage(page, publicEvent));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean startProcess(PublicEvent publicEvent) {
		String businessTable = FlowUtil.getBusinessTable(ProcessConstant.PUBLIC_EVENT);
		if (Func.isEmpty(publicEvent.getId())) {
			publicEvent.setFlag(STEP_1.step);
			// 保存表单实体类
			save(publicEvent);
			// 启动流程
			Kv variables = Kv.create()
				.set("auditor", TaskUtil.getTaskUser(publicEvent.getAuditor()))
				.set(ProcessConstant.TASK_VARIABLE_CREATE_USER, AuthUtil.getUserName());
			R<BladeFlow> result = flowClient.startProcessInstanceById(publicEvent.getProcessDefinitionId(), FlowUtil.getBusinessKey(businessTable, String.valueOf(publicEvent.getId())), variables);
			if (result.isSuccess()) {
				publicEvent.setProcessInstanceId(result.getData().getProcessInstanceId());
				updateById(publicEvent);
			} else {
				throw new ServiceException("开启流程失败");
			}
		} else {
			updateById(publicEvent);
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean completeProcess(PublicEventDTO publicEventDTO) {
		try{
			PublicEvent publicEvent = Objects.requireNonNull(BeanUtil.copy(publicEventDTO, PublicEvent.class));
			R<Map<String, Object>> variablesRes = flowClient.taskVariables(publicEventDTO.getTaskId());
			if(variablesRes.isSuccess()){
				Map<String, Object> variables = variablesRes.getData();
				if (variables == null) {
					variables = Kv.create();
				}
				switch ((FlowStepConst)flowStep.get(publicEventDTO.getFlag())){
					/*
					  	step1 : 网格员或园区管理员审批
						step2 : 事件受理人处理
					   	step3 : 用户重新修改提交
					   	step4 : 事件处理完成
					* */
					case STEP_1:
						variables.put("pass", publicEventDTO.getPass());
						if(!publicEventDTO.getPass()){
							variables.put("appUser", TaskUtil.getTaskUser(publicEventDTO.getAppUser()));
							publicEvent.setFlag(STEP_3.step);
						}else {
							variables.put("handlePerson", TaskUtil.getTaskUser(publicEventDTO.getHandlePerson()));
							publicEvent.setFlag(STEP_2.step);
						}
						break;
					case STEP_2:
						variables.put("success", publicEventDTO.getSuccess());
						if(publicEventDTO.getSuccess()){
							publicEvent.setFinish("finish");
						}else{
							publicEvent.setFinish("fail");
						}
						publicEvent.setFlag(STEP_4.step);
						break;
					case STEP_3:
						variables.put("submit", publicEventDTO.getSubmit());
						if(!publicEventDTO.getSubmit()){
							publicEvent.setFlag(STEP_1.step);
						}else {
							variables.put("handlePerson", TaskUtil.getTaskUser(publicEventDTO.getHandlePerson()));
							publicEvent.setFlag(STEP_4.step);
						}
						break;
					default:
						log.error("查找当前步骤表单失败！");
						return false;
				}
				baseMapper.updateById(publicEvent);
				R res = flowClient.completeTask(publicEventDTO.getTaskId(), publicEventDTO.getProcessInstanceId(), Func.isEmpty(publicEventDTO.getComment())? "同意":publicEventDTO.getComment(),variables);
				return  res.isSuccess();
			}
			return false;
		}catch (Exception e){
			log.error("公共事件流程处理异常：" + e.getMessage());
			throw e;
		}
	}

}
