/*
 *      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.deviceorder.service.impl;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
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.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.deviceorder.dto.DeviceOrderDTO;
import org.springblade.workorder.deviceorder.entity.DeviceOrder;
import org.springblade.workorder.deviceorder.mapper.DeviceOrderMapper;
import org.springblade.workorder.deviceorder.service.IDeviceOrderService;
import org.springblade.workorder.deviceorder.vo.DeviceOrderVO;
import org.springblade.workorder.publicevent.entity.PublicEvent;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

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

import static org.springblade.workorder.common.FlowStepConst.STEP_1;
import static org.springblade.workorder.common.FlowStepConst.flowStep;

/**
 * 设备工单 服务实现类
 *
 * @author BladeX
 * @since 2021-04-21
 */
@Service
@Slf4j
@AllArgsConstructor
public class DeviceOrderServiceImpl extends BaseServiceImpl<DeviceOrderMapper, DeviceOrder> implements IDeviceOrderService {
	private final IFlowClient flowClient;

	@Override
	public IPage<DeviceOrderVO> selectDeviceOrderPage(IPage<DeviceOrderVO> page, DeviceOrderVO deviceOrder) {
		return page.setRecords(baseMapper.selectDeviceOrderPage(page, deviceOrder));
	}
	@Override
	public Integer getUntreatedCount() {
		return baseMapper.getUntreatedCount();
	}

	@Override
	@Transactional
	public boolean startProcess(DeviceOrder deviceOrder) {
		String businessTable = FlowUtil.getBusinessTable(ProcessConstant.DEVICE_ORDER);
		if (Func.isEmpty(deviceOrder.getId())){
			deviceOrder.setFlag(STEP_1.step);
			deviceOrder.setJobStatus(1);
			this.save(deviceOrder);
			// 启动流程
			Kv variables = Kv.create()
				.set("handlePerson", TaskUtil.getTaskUser(deviceOrder.getHandlePerson()))
				.set(ProcessConstant.TASK_VARIABLE_CREATE_USER, AuthUtil.getUserName());
			R<BladeFlow> result = flowClient
				.startProcessInstanceById(deviceOrder.getProcessDefinitionId(), FlowUtil.getBusinessKey(businessTable, String.valueOf(deviceOrder.getId())), variables);
			if (result.isSuccess()) {
				deviceOrder.setProcessInstanceId(result.getData().getProcessInstanceId());
				updateById(deviceOrder);
			} else {
				throw new ServiceException("开启流程失败");
			}
		}else {
			this.updateById(deviceOrder);
		}
		return true;
	}

	@Override
	@Transactional
	public boolean completeProcess(DeviceOrderDTO deviceOrderDTO) {
		try {
			DeviceOrder deviceOrder = Objects.requireNonNull(BeanUtil.copy(deviceOrderDTO, DeviceOrder.class));
			R<Map<String, Object>> variablesRes = flowClient.taskVariables(deviceOrderDTO.getTaskId());
			if (variablesRes.isSuccess()){
				Map<String, Object> variables = variablesRes.getData();
				if (variables == null) {
					variables = Kv.create();
				}
				switch ((FlowStepConst)flowStep.get(deviceOrder.getFlag())){
					case STEP_1:
						break;
					case STEP_2:
						break;
					case STEP_3:
						break;
					default:
						log.error("查找当前步骤表单失败！");
						return false;
				}
				this.updateById(deviceOrder);
				R res = flowClient.completeTask(deviceOrderDTO.getTaskId(), deviceOrderDTO.getProcessInstanceId(),
					Func.isEmpty(deviceOrderDTO.getComment()) ? "同意" : deviceOrderDTO.getComment(), variables);
				return res.isSuccess();
			}
			return false;
		}catch (Exception e){
			log.error("公共事件流程处理异常：" + e.getMessage());
			throw e;
		}
	}

}
