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

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IBillModel;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.IPageCache;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.fi.er.business.ext.enums.ErExtcaseEnum;
import kd.fi.er.business.ext.helper.ErExtHelper;
import kd.fi.er.business.invoicecloud.util.InvoicePackageUtil;
import kd.fi.er.business.servicehelper.CommonServiceHelper;
import kd.fi.er.business.servicehelper.CoreBaseBillServiceHelper;
import kd.fi.er.business.utils.ErCostCenterUtil;
import kd.fi.er.business.utils.ErEntityTypeUtils;
import kd.fi.er.formplugin.daily.web.ErExpenseBaseEdit;
import org.apache.commons.lang3.StringUtils;
import java.util.EventObject;
import java.util.Map;

/**
 * 报销单据，处理费用承担公司及支付公司问题
 * @author wanghaiwu_kd
 * @date 2025/09/03
 */
public class ErExpenseBaseCusEditPlugin extends ErExpenseBaseEdit {
    private static Log logger = LogFactory.getLog(ErExpenseBaseCusEditPlugin.class);

    @Override
    public void afterCreateNewData(EventObject e) {
//        super.afterCreateNewData(e);
        loadDataExt();
    }

    private void loadDataExt() {
        IDataModel model = this.getView().getModel();
        Long currentUserID = 0L;
        IPageCache pageCache = (IPageCache)this.getView().getService(IPageCache.class);
        if (pageCache.get("consignorId") != null) {
            currentUserID = Long.valueOf(pageCache.get("consignorId"));
            pageCache.remove("consignorId");
        } else if (((IBillModel)model).isFromImport()) {
            currentUserID = (Long)model.getValue("applier_id");
        } else {
            RequestContext requestContext = RequestContext.get();
            currentUserID = Long.valueOf(requestContext.getUserId());
        }

        Map billMap;
        if (StringUtils.isNotEmpty((CharSequence)this.getView().getFormShowParameter().getCustomParam("package_import_pc"))) {
            billMap = InvoicePackageUtil.createNewData(this.getView().getFormShowParameter().getCustomParams());
        } else {
            billMap = CoreBaseBillServiceHelper.createNewData(currentUserID);
            //从HR职业信息获取用人单位
            resetCostCompanyValue(billMap, currentUserID);
        }

        CoreBaseBillServiceHelper.extService(this.getView(), billMap);
        CoreBaseBillServiceHelper.initObjByMap(model, billMap);
        ErExtHelper.invokeExpandPlugin(this.getView(), ErExtcaseEnum.ER_EXTCASE_BILLINIT);
        ErCostCenterUtil.initHeadCostCenter(this.getView(), false);
        ErCostCenterUtil.checkCostOrg(this, "1");
        String billtype = (String)this.getModel().getValue("formid");
        if (!ErEntityTypeUtils.isDailyVehicleBill(billtype) && model.getValue("company") != null && model.getValue("currency") == null) {
            this.getView().showTipNotification(ResManager.loadKDString("请联系管理员设置本位币。", "ErExpenseBaseEdit_3", "fi-er-formplugin", new Object[0]));
        }

        this.setFundingOrgExt();
    }

    private void resetCostCompanyValue(Map billMap, Long userId){
        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);
            }
        }
    }

    private void setFundingOrgExt() {
        IDataModel model = this.getModel();
        Object costCompany = model.getValue("costcompany");
        if (this.isNeedToSetPayCompanyExt() && costCompany != null) {
            DynamicObject fundingCompany = CoreBaseBillServiceHelper.getFundingOrg((DynamicObject)costCompany);
            model.setValue("paycompany", fundingCompany);
        }

    }

    private boolean isNeedToSetPayCompanyExt() {
        String formId = this.getView().getEntityId();
        boolean flag = ErEntityTypeUtils.isPrePayBill(formId) || ErEntityTypeUtils.isDailyLoanBill(formId) || ErEntityTypeUtils.isApplyPayBill(formId) || ErEntityTypeUtils.isDailyReimburseBill(formId) || ErEntityTypeUtils.isPublicReimburseBill(formId);
        logger.info("是否在需要设置支付公司的单据范围：" + flag);
        return flag;
    }
}
