package nckd.jimin.jyyy.fi.mservice;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.IFormView;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.fi.er.business.servicehelper.CommonServiceHelper;
import kd.fi.er.mservice.ext.IErService4Ext;
import java.util.Map;

/**
 * 报销类单据初始化数据包
 * @wanghaiwu_kd
 * @date 2025/09/11
 */
public class ErService4Ext implements IErService4Ext {
    @Override
    public void initNewDataMap(IFormView view, Map<String, Object> billMap) {
        if(billMap.get("applier") != null) {
            resetCostCompanyValue(billMap);
        }
    }

    private void resetCostCompanyValue(Map billMap){
        Long userId = Long.valueOf(billMap.get("applier").toString());
        if(userId == 0L){
            return;
        }

        DynamicObject userInfo = CommonServiceHelper.getUser(userId);
        String entityName = "hrpi_empentrel";
        String selectFields = "enterprise";

        QFilter qFilter = new QFilter("person.number", QCP.equals, userInfo.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());

            if(orgDy != null){
                billMap.put("costcompany", orgDy);
            }
        }
    }
}
