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

import com.alibaba.fastjson.JSON;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
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.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.common.model.UserCurrentDeptInfo;
import kd.fi.er.formplugin.util.DataCopyUtils;
import kd.fi.er.formplugin.web.TripReimburseBillEdit;
import org.apache.commons.lang3.StringUtils;
import java.util.EventObject;
import java.util.Map;

/**
 * 处理费用承担公司及支付公司问题
 * 差旅报销单（nckd_er_tripreimburse_ext）
 * @author wanghaiwu_kd
 * @date 2025/09/10
 */
public class TripReimburseBillCusEditPlugin extends TripReimburseBillEdit {
    private static Log logger = LogFactory.getLog(TripReimburseBillCusEditPlugin.class);

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

        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 {
            RequestContext requestContext = RequestContext.get();
            currentUserID = Long.valueOf(requestContext.getUserId());
        }

        Map billMap;
        if (org.apache.commons.lang.StringUtils.isNotEmpty((String)this.getView().getFormShowParameter().getCustomParam("package_import_pc"))) {
            billMap = InvoicePackageUtil.createNewData(this.getView().getFormShowParameter().getCustomParams());
        } else {
            billMap = CoreBaseBillServiceHelper.createNewData(currentUserID);

            //从HR职业信息获取用人单位
            resetCostCompanyValue(billMap, currentUserID);
        }

        Map<String, Object> custom = this.getView().getFormShowParameter().getCustomParams();
        Object parameterStr = custom.get("userInfo");
        if (parameterStr != null && StringUtils.isNotBlank(parameterStr.toString())) {
            UserCurrentDeptInfo userInfo = (UserCurrentDeptInfo) JSON.parseObject(parameterStr.toString(), UserCurrentDeptInfo.class);
            logger.info("CoreBaseBillEdit>>>获取到的userInfo为：" + parameterStr.toString());
            billMap = CoreBaseBillServiceHelper.createNewData(userInfo.getUserId(), userInfo.getDeptId());

            //从HR职业信息获取用人单位
            resetCostCompanyValue(billMap, currentUserID);

            logger.info("CoreBaseBillEdit>>>根据userInfo生成的billmap为：" + billMap.toString());
        }

        CoreBaseBillServiceHelper.extService(this.getView(), billMap);
        CoreBaseBillServiceHelper.initObjByMap(this.getView().getModel(), billMap);

        ErCostCenterUtil.initHeadCostCenter(this.getView(), false);
        ErCostCenterUtil.checkCostOrg(this, "1");
        Object currency = model.getValue("currency");
        if (model.getValue("company") != null && currency == null) {
            this.getView().showErrorNotification(ResManager.loadKDString("请联系管理员设置本位币。", "CoreBaseBillEdit_2", "fi-er-formplugin", new Object[0]));
        }

        DataCopyUtils.setOriginValue(this.getView());

        CommonServiceHelper.setMulWayToVisible(this.getModel(), this.getView());
        CommonServiceHelper.setIsMulTravelers(this.getModel(), this.getView());
        this.setFundingOrgExt();
    }

    private void setFundingOrgExt() {
        IDataModel model = this.getModel();
        Object costCompany = model.getValue("costcompany");
        if (this.isNeedToSetFundingOrg() && costCompany != null) {
            logger.info("开始设置支付公司");
            DynamicObject fundingCompany = CoreBaseBillServiceHelper.getFundingOrg((DynamicObject)costCompany);
            this.getModel().setValue("paycompany", fundingCompany);
        }

    }

    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);
            }
        }
    }
}
