package nckd.jxccl.hr.sdm.plugin.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.hr.hbp.common.util.HRStringUtils;
import nckd.jxccl.hr.sdm.common.SanDingConstant;

/**
 * 三定任务表单插件
 * @entity: nckd_sandingtask
 * @author: jtd
 * @date: 2025/12/18 20:12
 */
public class SanDingTaskFormPlugin extends AbstractFormPlugin {

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);

        FormOperate formOperate = (FormOperate)args.getSource();
        String operateKey = formOperate.getOperateKey();
        if (HRStringUtils.equals(SanDingConstant.SUBMIT_OP, operateKey)) {
            AttachmentPanel attachmentPanel = getControl(SanDingConstant.ATTACHMENTPANEL_KEY);
            if (attachmentPanel.getAttachmentData().isEmpty()) {
                getView().showTipNotification("请按要求上传附件。");
                args.setCancel(true);
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);

        String operateKey = afterDoOperationEventArgs.getOperateKey();
        switch (operateKey) {
            case SanDingConstant.SUBMIT_OP:
                setSubmitter(afterDoOperationEventArgs);
        }
    }

    private void setSubmitter(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        OperationResult operationResult = afterDoOperationEventArgs.getOperationResult();
        if (!operationResult.isSuccess() || operationResult.getSuccessPkIds().isEmpty()) {
            return;
        }

        DynamicObject dataEntity = getModel().getDataEntity();
        dataEntity.set(SanDingConstant.NCKD_SUBMITTER_KEY, UserServiceHelper.getCurrentUserId());
        SaveServiceHelper.save(new DynamicObject[]{dataEntity});
    }
}
