package nckd.jxccl.hr.homs.plugin.form.orgbatch;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.StyleCss;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import nckd.jxccl.hr.homs.common.orgbatch.OrgBatchConstant;

import java.util.Locale;

/**
 * 组织调整申请界面插件
 * @entity: nckd_homs_orgbatchchg_ext
 * @author: jtd
 * @date: 2025-09-26 15:16
 */
public class OrgBatchChgBillListPlugin extends AbstractListPlugin {

    private final String no_root_msg = ResManager.loadKDString("无根组织，请先完成根组织初始化！初始化根组织的路径：系统服务云>调度中心>调度计划>组织发展云，执行“根行政组织生成调度计划”。", "AdminOrgDetailHelper_2", "hrmp-haos-business", new Object[0]);
    private final String disable_chargepersonset_msg = ResManager.loadKDString("%1$s：只能对已启用的行政组织进行部门负责人设置。", "AdminOrgDetailHelper_13", "hrmp-haos-business", new Object[0]);
    private final String chargepersonset_msg = ResManager.loadKDString("%1$s-部门负责人设置", "AdminOrgDetailHelper_14", "hrmp-haos-business", new Object[0]);

    public boolean checkRootInit(IFormView iFormView) {
        long rootOrgId = this.getRootOrgId();
        HRBaseServiceHelper rootHelper = new HRBaseServiceHelper("haos_adminorgdetail");
        QFilter qFilter = new QFilter("boid", "=", rootOrgId);
        qFilter.and("iscurrentversion", "=", '1');
        boolean exists = rootHelper.isExists(qFilter);
        if (!exists) {
            iFormView.showErrorNotification(this.no_root_msg);
            return false;
        } else {
            return true;
        }
    }

    public void showDeptLeaderSet(AbstractFormPlugin formPlugin, Long orgId) {
        HRBaseServiceHelper helper = new HRBaseServiceHelper("haos_adminorgdetail");
        DynamicObject adminOrgInfo = helper.queryOne("id, boid, name, number, enable, establishmentdate, org", orgId);
        if ("0".equals(adminOrgInfo.getString("enable"))) {
            formPlugin.getView().showTipNotification(String.format(String.format(Locale.ROOT, this.disable_chargepersonset_msg, adminOrgInfo.getString("number"))));
        } else {
            FormShowParameter formShowParameter = new FormShowParameter();
            formShowParameter.setCaption(String.format(Locale.ROOT, this.chargepersonset_msg, adminOrgInfo.getString("name")));
            formShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
            formShowParameter.setFormId("homs_chargepersonset");
            String mainPageId = "";
            if (formPlugin.getView().getMainView() != null) {
                mainPageId = formPlugin.getView().getMainView().getPageId();
            }

            formShowParameter.setPageId("homs_chargepersonset_" + adminOrgInfo.getLong("id") + "_" + mainPageId);
            formShowParameter.setCustomParam("adminorg", adminOrgInfo.getString("boid"));
            formShowParameter.setCustomParam("org", adminOrgInfo.getString("org"));
            formShowParameter.setCustomParam("establishmentdate", adminOrgInfo.getDate("establishmentdate"));
            formPlugin.getView().showForm(formShowParameter);
        }
    }

    private Long getRootOrgId() {
        String selectProperties = "org,view";
        QFilter viewFilter = new QFilter("view", "=", 15L);
        QFilter parentFilter = new QFilter("parent", "=", 0);
        QFilter[] filters = new QFilter[]{viewFilter, parentFilter};
        HRBaseServiceHelper rootHelper = new HRBaseServiceHelper("bos_org_structure");
        DynamicObject[] rootOrgs = rootHelper.load(selectProperties, filters, "longnumber");
        if (rootOrgs == null) {
            return 100000L;
        } else {
            for(DynamicObject rootOrg : rootOrgs) {
                DynamicObject viewObj = rootOrg.getDynamicObject("view");
                DynamicObject orgObj = rootOrg.getDynamicObject("org");
                if (viewObj != null && orgObj != null && viewObj.getLong("id") == 15L) {
                    return orgObj.getLong("id");
                }
            }

            return 100000L;
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);

        AbstractOperate operate = (AbstractOperate)args.getSource();
        String operateKey = operate.getOperateKey();
        if (OrgBatchConstant.SHOW_CHARGE_PERSON_OP.equals(operateKey)) {
            // 使用标品校验逻辑
            boolean rootInit = checkRootInit(getView());
            if (!rootInit) {
                args.setCancel(true);
            } else {
                openOperationPage(operateKey, args);
            }
        }
    }

    private void openOperationPage(String opKey, BeforeDoOperationEventArgs args) {
        if (OrgBatchConstant.SHOW_CHARGE_PERSON_OP.equals(opKey)) {
            // 创建弹出列表界面对象
            ListShowParameter listShowParameter = new ListShowParameter();
            // 设置F7列表表单模板（根据基础资料类型选择）
            listShowParameter.setFormId(OrgBatchConstant.HAOS_ADMINORGTREELISTF7_ENTITY);
            // 设置基础资料标识
            listShowParameter.setBillFormId(OrgBatchConstant.HAOS_ADMINORGHRF7_ENTITY);
            // 设置打开方式为模态窗口
            listShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            // 设置界面大小
            StyleCss inlineStyleCss = new StyleCss();
            inlineStyleCss.setHeight("580");
            inlineStyleCss.setWidth("960");
            listShowParameter.getOpenStyle().setInlineStyleCss(inlineStyleCss);
            // 必须设置为true，表示是可选择界面
            listShowParameter.setLookUp(true);
            // 不控权
            listShowParameter.setHasRight(true);
            // 设置是否多选
            listShowParameter.setMultiSelect(false);
            // 设置是否显示标题
            listShowParameter.setShowTitle(false);
            // 设置回调（不设置会导致空指针）
            listShowParameter.setCloseCallBack(new CloseCallBack(this, OrgBatchConstant.CHARGE_PERSON_DIALOG));
            // 弹出F7选择界面
            this.getView().showForm(listShowParameter);
        }

        if (OrgBatchConstant.ADMINORG_COPY_OP.equals(opKey)) {
            // 创建弹出参数对象
            FormShowParameter formShowParameter = new FormShowParameter();
            // 设置要弹出的动态表单标识
            formShowParameter.setFormId(OrgBatchConstant.NCKD_ADMINORG_COPY_DIALOG_FORMID);
            // 设置打开方式为模态框
            formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            // 执行弹出操作
            this.getView().showForm(formShowParameter);
        }

    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        super.closedCallBack(closedCallBackEvent);

        String actionId = closedCallBackEvent.getActionId();
        ListSelectedRowCollection returnData = (ListSelectedRowCollection) closedCallBackEvent.getReturnData();
        if (returnData == null || returnData.isEmpty()) {
            return;
        }

        // 设置部门负责人回调
        if (OrgBatchConstant.CHARGE_PERSON_DIALOG.equals(actionId)) {
            showDeptLeaderSet(this, (Long) returnData.get(0).getPrimaryKeyValue());
        }
    }
}
