package com.kingdee.eas.base.message.app;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectCollection;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.eas.base.message.BMCMessageInfo;
import com.kingdee.eas.base.message.MsgStatus;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.weaverTodo.WeaverMessageWebServiceDao;
import org.apache.log4j.Logger;

/**
 * BMC 普通消息新建后补推待阅到泛微。
 * 落库仍走产品父类；这里只在成功后触发 MessageWebServiceDao.updateMessages(UNREADED)。
 */
public class BMCMessageControllerBeanEx extends BMCMessageControllerBean {
    private static final Logger logger = Logger.getLogger(BMCMessageControllerBeanEx.class);

    private final WeaverMessageWebServiceDao weaverDao = new WeaverMessageWebServiceDao();

    @Override
    protected IObjectPK[] _addnewBatchData(Context ctx, IObjectCollection colls)
            throws BOSException, EASBizException {
        IObjectPK[] batchData = super._addnewBatchData(ctx, colls);
        if (colls == null || batchData == null) {
            return batchData;
        }
        for (int i = 0; i < colls.size(); i++) {
            BMCMessageInfo messageInfo = (BMCMessageInfo) colls.getObject(i);
            String msgId;
            if (messageInfo != null && messageInfo.getId() != null) {
                msgId = messageInfo.getId().toString();
            } else if (i < batchData.length && batchData[i] != null) {
                msgId = batchData[i].toString();
            } else {
                continue;
            }
            pushUnread(ctx, msgId, "_addnewBatchData");
        }
        return batchData;
    }

    @Override
    protected void _addnew(Context ctx, IObjectPK pk, IObjectValue model)
            throws BOSException, EASBizException {
        BMCMessageInfo messageInfo = (BMCMessageInfo) model;
        super._addnew(ctx, pk, model);
        String msgId;
        if (pk != null) {
            msgId = pk.toString();
        } else if (messageInfo != null && messageInfo.getId() != null) {
            msgId = messageInfo.getId().toString();
        } else {
            logger.warn("BMC 单条新增无法解析 msgId，跳过待阅推送");
            return;
        }
        pushUnread(ctx, msgId, "_addnew(pk)");
    }

    @Override
    protected IObjectPK _addnew(Context ctx, IObjectValue model)
            throws BOSException, EASBizException {
        IObjectPK pk = super._addnew(ctx, model);
        if (pk != null) {
            pushUnread(ctx, pk.toString(), "_addnew(model)");
        }
        return pk;
    }

    private void pushUnread(Context ctx, String msgId, String from) {
        try {
            logger.info("BMC 新建触发待阅推送 from=" + from + " msgId=" + msgId);
            weaverDao.updateMessages(msgId, MsgStatus.UNREADED, ctx);
        } catch (Exception e) {
            // 推送失败不影响消息落库
            logger.error("BMC 新建待阅推送异常 from=" + from + " msgId=" + msgId, e);
        }
    }
}
