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

import kd.bos.dataentity.resource.ResManager;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.control.Control;
import kd.bos.form.control.events.BeforeClickEvent;
import kd.bos.workflow.design.plugin.AbstractWorkflowPlugin;
import kd.bos.workflow.engine.WfUtils;
import kd.bos.workflow.util.WfCommonUtil;
import org.apache.commons.lang.ObjectUtils;
import java.util.EventObject;
import java.util.Map;
import static kd.bos.workflow.taskcenter.plugin.util.ApprovalPluginUtil.isPCShow;

/**
 * 手写签名校验
 * 表单标识：审批处理页面(nckd_wf_approvalpage__ext)
 * @author wanghaiwu_kd
 * @date 2025/06/04
 */
public class ApprovalPageCheckSignatureCusPlugin extends AbstractWorkflowPlugin {
    public void initialize() {
        super.initialize();

        addClickListeners("btnsubmit_approval", "btnsubmit_taskcoordinate", "mbaritemap_submit", "mbaritemap_coordinate");
    }

    @Override
    public void beforeClick(BeforeClickEvent evt) {
        super.beforeClick(evt);

        IFormView view = this.getView();
        boolean isPcShow = isPCShow(view.getFormShowParameter());

        if (!WfUtils.isNullObject(view)) {
            IPageCache pageCache;
            if (isPcShow) {
                pageCache = view.getPageCache();
            } else {
                IFormView parentView = view.getParentView();
                if (WfUtils.isNullObject(parentView)) {
                    return;
                }
                pageCache = parentView.getPageCache();
            }

            String control = pageCache.get("taskcontrol");
            Map<String, Object> controlMap = WfCommonUtil.getValueFromMapJson(control);
            Boolean isAllowSignature = WfCommonUtil.getBooleanValueFromJson(controlMap, "aS");
            Boolean isForceSignature = WfCommonUtil.getBooleanValueFromJson(controlMap, "fS");

            String key = ((Control)evt.getSource()).getKey();
            if(isAllowSignature && !isForceSignature) {
                String fieldKey = "";
                if ("btnsubmit_approval".equals(key) || "mbaritemap_submit".equals(key) || "mbaritemap_coordinate".equals(key)) {
                    fieldKey = "signaturefield";
                } else if ("btnsubmit_taskcoordinate".equals(key)) {
                    fieldKey = "signaturefield_crd";
                }

                Object auditSignatureObj = view.getModel().getValue(fieldKey);
                String auditSignature = ObjectUtils.toString(auditSignatureObj);

                if (WfUtils.isEmptyString(auditSignature)) {
                    evt.setCancel(true);
                    this.getView().showErrorNotification(ResManager.loadKDString("请填写手写签名。", "ApprovalPluginNew_56", "bos-wf-formplugin", new Object[0]));
                }
            }
        }
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
    }
}
