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


import com.kingdee.bos.util.backport.Collections;
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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.util.CollectionUtils;
import kd.bos.workflow.api.AgentExecution;
import kd.bos.workflow.api.AgentTask;
import kd.bos.workflow.engine.extitf.IWorkflowPlugin;
import nckd.jimin.jyyy.fi.common.constant.ErReimBurseBillConstant;

import java.util.List;

/**
 * 共享审核节点设置审核人
 */
public class TaskApproverWorkflowPlugin 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().containsKey("istaskapprove")){
            updateBillTaskApprover(businessKey,entityNumber, null);
        }else{
            updateBillTaskApprover(businessKey,entityNumber, Collections.singletonList(assigneeId));
        }

    }

    /**
     * 更新共享审核人
     * @param billId
     * @param formId
     */
    protected void updateBillTaskApprover(Object billId,String formId,List<Long> currentApprover){
        DynamicObjectType entityType = EntityMetadataCache.getDataEntityType(formId);
        if(!entityType.getProperties().containsKey(ErReimBurseBillConstant.KEY_NCKD_TASKAPPROVER)){
            BizLog.log(String.format("单据类型【%1&s】没有共享审核人字段，无需更新",formId));
            return;
        }

        DynamicObject billInfo = BusinessDataServiceHelper.loadSingle(billId, formId, String.join(",",ErReimBurseBillConstant.KEY_NCKD_TASKAPPROVER,"billno"));
        if(CollectionUtils.isNotEmpty(currentApprover) && currentApprover.get(0) != 0L){
            billInfo.set(ErReimBurseBillConstant.KEY_NCKD_TASKAPPROVER,currentApprover.get(0));
        }else{
            // 按完成时间倒叙，取最晚的一条 如果共享被驳回，再次审核通过时反写
            DynamicObject[] taskTaskhistories = BusinessDataServiceHelper.load("task_taskhistory", "billnumber,id,apprevalmessage,personid,tasktypeid,state", new QFilter[]{
                    new QFilter("billnumber", QCP.equals,billInfo.getString("billno"))
            },"completetime desc");
            BizLog.log("taskTaskhistories length：" + taskTaskhistories.length);
            billInfo.set(ErReimBurseBillConstant.KEY_NCKD_TASKAPPROVER,taskTaskhistories[0].getDynamicObject("personid"));
        }
        SaveServiceHelper.save(new DynamicObject[]{ billInfo });
    }
}
