package nckd.jxccl.opmc.pm.plugin.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.control.Control;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.EventObject;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: KpiTutorHeadFormPlugin
 * @Description: 绩效辅导负责人表单插件
 * @Author: PJJ
 * @Date: 2026/1/14 上午10:59
 * @Version: 1.0
 */
public class KpiTutorHeadFormPlugin extends AbstractFormPlugin implements BeforeF7SelectListener {
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit user = this.getView().getControl("nckd_responsibleuser");
        user.addBeforeF7SelectListener(this);
        BasedataEdit specialUser = this.getView().getControl("nckd_specialuser");
        specialUser.addBeforeF7SelectListener(this);
        BasedataEdit specialResponsible = this.getView().getControl("nckd_specialresponsible");
        specialResponsible.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        if (StringUtils.equalsAny(name, "nckd_responsibleuser", "nckd_specialuser", "nckd_specialresponsible")) {
            Object orgValue = this.getModel().getValue("nckd_org");
            if (ObjectUtils.isEmpty(orgValue)) {
                e.setCancel(true);
                this.getView().showTipNotification("请先选择绩效组织!");
                return;
            }
            DynamicObject org = (DynamicObject) orgValue;
            List<Long> orgIds = OrgUnitServiceHelper.getAllSubordinateOrgs(1L, Collections.singletonList(org.getLong("id")), true);
            QFilter qFilter = new QFilter("entryentity.ispartjob", QCP.equals, false);
            qFilter.and("status", QCP.equals, "C");
            qFilter.and("enable", QCP.equals, "1");
            if (StringUtils.equals(name, "nckd_responsibleuser")) {
                qFilter.and("entryentity.dpt", QCP.equals, org.getPkValue());
                e.getCustomQFilters().add(qFilter);
            } else if (StringUtils.equals(name, "nckd_specialuser")) {
                qFilter.and("entryentity.dpt", QCP.in, orgIds);
                e.getCustomQFilters().add(qFilter);
            } else if (StringUtils.equals(name, "nckd_specialresponsible")) {

            }
        }
    }
}
