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

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import java.util.EventObject;

/**
 * 费用单据，【合同主体】字段值的默认
 * @author wanghaiwu_kd
 * @date 2026/01/09
 */
public class ErSetContractOrgBaseEditPlugin extends AbstractBillPlugIn {
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);

        resetDefaultValue();
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);

        String fieldKey = e.getProperty().getName();
        if("applier".equals(fieldKey)){
            resetDefaultValue();
        }
    }

    private void resetDefaultValue(){
        IDataModel model = this.getModel();

        if(model.getValue("applier") == null){
            return;
        }

        DynamicObject applier = (DynamicObject) model.getValue("applier");

        String entityName = "hrpi_empentrel";
        String selectFields = "enterprise";

        QFilter qFilter = new QFilter("person.number", QCP.equals, applier.getString("number"));
        qFilter.and(new QFilter("iscurrentversion", QCP.equals, "1"));
        qFilter.and(new QFilter("businessstatus", QCP.equals, "1"));

        DynamicObject[] emps = BusinessDataServiceHelper.load(entityName, selectFields, qFilter.toArray(), "enddate desc");
        if(emps.length > 0 && emps[0].getDynamicObject("enterprise") != null){
            String companyName = emps[0].getDynamicObject("enterprise").getString("name");
            qFilter = new QFilter("enable", QCP.equals, "1");
            //数据状态=已审核
            qFilter.and(new QFilter("status", QCP.equals, "C"));
            //属性核算组织=是
            qFilter.and(new QFilter("fisaccounting", QCP.equals, "1"));
            qFilter.and(new QFilter("name", QCP.equals, companyName));
            DynamicObject orgDy = BusinessDataServiceHelper.loadSingle("bos_org", "id, number", qFilter.toArray());

            model.setValue("nckd_appliervcompany", orgDy);
        }
    }
}
