package nckd.jimin.jyyy.fi.plugin.workflow;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.logging.BizLog;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.workflow.api.AgentExecution;
import kd.bos.workflow.api.AgentTask;
import kd.bos.workflow.engine.extitf.IWorkflowPlugin;

/**
 * 流程插件，更新一级审批人、二级审批人
 * @author wanghaiwu_kd
 * @date 2025/07/01
 */
public class UpdateAuditWorkflowPlugin implements IWorkflowPlugin {
    @Override
    public void notify(AgentExecution e) {
        IWorkflowPlugin.super.notify(e);

        String businessKey = e.getBusinessKey();
        String entityNumber = e.getEntityNumber();
        //获取当前工作流节点
        AgentTask currentTask = e.getCurrentTask();
        //获取当前节点实际审批人ID
        Long assigneeId = currentTask.getAssigneeId();
        BizLog.log("工作流当前审批人：" + assigneeId);

        if(e.getCurrentWFPluginParams() != null && e.getCurrentWFPluginParams().get("nckd_filename") != null){
            String fieldNumber = "";
            String fieldName = "";
            String taskName = (String) e.getCurrentWFPluginParams().get("nckd_filename");

            if(taskName.contains("一审")){
                fieldNumber = "nckd_oneapprover";
                fieldName = "一审";
            } else if(taskName.contains("二审")){
                fieldNumber = "nckd_twoapprover";
                fieldName = "二审";
            } else {
                BizLog.log(String.format("参数【nckd_filename】值不是【一审】或【二审】"));
                return;
            }

            DynamicObjectType entityType = EntityMetadataCache.getDataEntityType(entityNumber);
            if(!entityType.getProperties().containsKey(fieldNumber)){
                BizLog.log(String.format("单据类型【%s】没有" + fieldName + "字段，无需更新", entityNumber));
                return;
            }

            DynamicObject assignee = BusinessDataServiceHelper.loadSingleFromCache(assigneeId, "bos_user");

            DynamicObject billInfo = BusinessDataServiceHelper.loadSingle(businessKey, entityNumber, "id, billno, nckd_oneapprover, nckd_twoapprover");
            billInfo.set(fieldNumber, assignee);

            SaveServiceHelper.update(new DynamicObject[]{ billInfo });
        } else {
            BizLog.log(String.format("插件未配置参数【nckd_filename】"));
        }
    }
}
