package com.codvision.workflow.listener.task;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.codvision.workflow.entity.WorkFlowData;
import com.codvision.workflow.entity.WorkFlowForm;
import com.codvision.workflow.service.WorkFlowDataService;
import com.codvision.workflow.service.WorkFlowFormService;
import lombok.RequiredArgsConstructor;
import org.flowable.task.service.delegate.DelegateTask;
import org.flowable.task.service.delegate.TaskListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 清除当前任务节点历史填写的表单数据（任务监听器 事件类型 -> create）
 * @author hxl
 */
@RequiredArgsConstructor
@Component(value = "workFlowCleanHistoricalFormDataListener")
public class WorkFlowCleanHistoricalFormDataListener implements TaskListener {

    private final static String AUTH_NUM = "3";
    private final WorkFlowFormService workFlowFormService;
    private final WorkFlowDataService workFlowDataService;

    @Override
    public void notify(DelegateTask delegateTask) {
        WorkFlowData workFlowData = workFlowDataService.getFormDataByInstanceId(delegateTask.getProcessInstanceId());
        if (workFlowData == null) {
            return;
        }

        WorkFlowForm workFlowForm = workFlowFormService.getTaskFormAuth(delegateTask.getProcessDefinitionId(), delegateTask.getTaskDefinitionKey());
        if (workFlowForm == null) {
            return;
        }

        Map<String, Object> formDataMap = JSONUtil.parseObj(workFlowData.getFormDataJson());
        Map<String, Object> formAuthMap = JSONUtil.parseObj(workFlowForm.getFormAuthJson());
        if (ObjectUtil.isEmpty(formDataMap) || ObjectUtil.isEmpty(formAuthMap)) {
            return;
        }

        for (Map.Entry<String, Object> it : formAuthMap.entrySet()) {
            if (AUTH_NUM.equals(it.getValue())) {
                formDataMap.remove(it.getKey());
            }
        }

        workFlowData.setFormDataJson(JSONUtil.toJsonStr(formDataMap));
        workFlowDataService.updateById(workFlowData);
    }
}
