package nckd.jxccl.sit.hcsi.formplugin.web.tp;

import nckd.jxccl.base.common.utils.DateTimeUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.events.BeforeClosedEvent;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.Date;
import java.util.Map;

/**
 * Tyx 2025-10-21
 * 外部数据中间表数据列表插件 nckd_sinsurtempdata
 */
public class SinsurTempDataListPlugin extends AbstractListPlugin implements Plugin {

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        Long importTaskId = (Long)this.getView().getFormShowParameter().getCustomParam("importTaskId");
        String creatorId = (String)this.getView().getFormShowParameter().getCustomParam("creator");
        FormOperate formOperate = (FormOperate)args.getSource();
        String opKey = formOperate.getOperateKey();
        switch (opKey) {
            case "donothing_import":
                this.opeanImportStartPage();
                break;
        }
    }

    @Override
    public void beforeClosed(BeforeClosedEvent arg) {
        IFormView parentView = this.getView().getParentView();
        if (parentView != null) {
            parentView.invokeOperation("close");
            this.getView().sendFormAction(parentView);
        }

    }

    /**
     * 打开选择导入模板界面
     */
    private void opeanImportStartPage() {
        if (!this.checkTaskStatus(false, true)) {
            FormShowParameter formShowParameter = new FormShowParameter();
            formShowParameter.setShowTitle(false);
            formShowParameter.setFormId("nckd_taskguideimport");
            formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            formShowParameter.setCustomParam("importTaskName", this.getView().getFormShowParameter().getCustomParam("importTaskName"));
            formShowParameter.setCustomParam("sinsurTplId", this.getView().getFormShowParameter().getCustomParam("sinsurTplId"));
            formShowParameter.setCustomParam("importTaskId", this.getView().getFormShowParameter().getCustomParam("importTaskId"));
            formShowParameter.setCustomParam("periodId", this.getView().getFormShowParameter().getCustomParam("periodId"));
            formShowParameter.setCustomParam("welfarepayerId", this.getView().getFormShowParameter().getCustomParam("welfarepayerId"));
            formShowParameter.setCustomParam("orgId", this.getView().getFormShowParameter().getCustomParam("orgId"));
            formShowParameter.setCustomParam("periodNumber", this.getView().getFormShowParameter().getCustomParam("periodNumber"));
            formShowParameter.setCloseCallBack(new CloseCallBack(this, "importData"));
            this.getView().showForm(formShowParameter);
        }
    }

    private boolean checkTaskStatus(boolean checkIsRunning, boolean checkIsClosed) {
        Long importTaskId = (Long)this.getView().getFormShowParameter().getCustomParam("importTaskId");
        HRBaseServiceHelper helper = new HRBaseServiceHelper("nckd_sinsurimptask");
        DynamicObject importTask = helper.queryOriginalOne("id,nckd_taskstatus", new QFilter[]{new QFilter("id", "=", importTaskId)});
        String taskStatus = importTask.getString("nckd_taskstatus");
        String msg = null;
        if (checkIsRunning) {
            if (StringUtils.equals(taskStatus, "4")) {
                msg = ResManager.loadKDString("当前任务后台执行校验中，请稍后再试。", "ImportTaskGuideOpereateBillList_13", "swc-hsas-formplugin", new Object[0]);
            } else if (StringUtils.equals(taskStatus, "3")) {
                msg = ResManager.loadKDString("当前任务后台执行预处理中，请稍后再试。", "ImportTaskGuideOpereateBillList_14", "swc-hsas-formplugin", new Object[0]);
            } else if (StringUtils.equals(taskStatus, "6")) {
                msg = ResManager.loadKDString("当前任务后台执行反写中，请稍后再试。", "ImportTaskGuideOpereateBillList_15", "swc-hsas-formplugin", new Object[0]);
            } else if (StringUtils.equals(taskStatus, "5")) {
                msg = ResManager.loadKDString("当前任务后台执行写入中，请稍后再试。", "ImportTaskGuideOpereateBillList_16", "swc-hsas-formplugin", new Object[0]);
            } else if (StringUtils.equals(taskStatus, "9")) {
                msg = ResManager.loadKDString("当前任务后台执行清除中间表数据中，请稍后再试。", "ImportTaskGuideOpereateBillList_36", "swc-hsas-formplugin", new Object[0]);
            }

            if (msg != null) {
                this.getView().showTipNotification(msg);
                return true;
            }
        }

        if (!checkIsClosed || !StringUtils.equals(taskStatus, "7") && !StringUtils.equals(taskStatus, "8")) {
            return false;
        } else {
            msg = ResManager.loadKDString("任务已关闭，无法操作。", "ImportTaskGuideOpereateBillList_35", "swc-hsas-formplugin", new Object[0]);
            this.getView().showErrorNotification(msg);
            return true;
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        super.closedCallBack(closedCallBackEvent);
        String actionId = closedCallBackEvent.getActionId();
        Map returnData;
        if ("importData".equals(actionId)) {
            returnData = (Map)closedCallBackEvent.getReturnData();
            if (returnData == null) {
                return;
            }
            if ((Boolean)returnData.get("isOk")) {
                int totalCount = Integer.parseInt(returnData.get("totalCount").toString());
                Long importTaskId = (Long)returnData.get("importTaskId");
                String cacheKey = (String)returnData.get("cacheKey");
                String caption = ResManager.loadKDString("导入看板", "ImportTaskGuideOpereateBillList_33", "swc-hsas-formplugin", new Object[0]);
                this.openProgressPage(totalCount, importTaskId, "22", "importingData", caption, cacheKey);
            }
        }
        else if ("importingData".equals(actionId)) {
            returnData = (Map)closedCallBackEvent.getReturnData();
            if (returnData != null && !returnData.isEmpty()) {
                this.openImportingView(returnData);
            } else {
                this.getView().invokeOperation("refresh");
            }
        } else if (!"checkprogress".equals(actionId) && !"dataPreDeal".equals(actionId)) {
            if ("donothing_writein".equals(actionId)) {
                this.getView().invokeOperation("refresh");
            } else if ("donothing_unwritein".equals(actionId)) {
                this.getView().invokeOperation("refresh");
            }
        } else {
            this.getView().invokeOperation("refresh");
        }
    }

    private void openProgressPage(int totalCount, Long importTaskId, String progressType, String closeCalBackId, String caption, String verifyId) {
        FormShowParameter formShowParameter = new FormShowParameter();
        formShowParameter.setFormId("hsas_datacheckprogress");
        formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        formShowParameter.setCaption(caption);
        formShowParameter.setCustomParam("importTaskId", importTaskId);
        formShowParameter.setCustomParam("totalCount", totalCount);
        formShowParameter.setCustomParam("verifyId", verifyId);
        formShowParameter.setCustomParam("startTime", DateTimeUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        formShowParameter.setCustomParam("progressType", progressType);
        formShowParameter.setCloseCallBack(new CloseCallBack(this, closeCalBackId));
        this.getView().showForm(formShowParameter);
    }

    private void openImportingView(Map<String, Object> dataMap) {
        FormShowParameter formShowParameter = new FormShowParameter();
        formShowParameter.setFormId("hsas_taskguideimportret");
        formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        formShowParameter.setCustomParam("importTaskId", dataMap.get("importTaskId"));
        formShowParameter.setCustomParam("successCout", dataMap.get("successCout"));
        formShowParameter.setCustomParam("failCout", dataMap.get("failCout"));
        formShowParameter.setCustomParam("cacheKey", dataMap.get("cacheKey"));
        formShowParameter.setCloseCallBack(new CloseCallBack(this, "importErrorData"));
        this.getView().showForm(formShowParameter);
    }
}