package nc.bs.arap.busireg;

import nc.bs.arap.util.SqlUtils;
import nc.bs.businessevent.BusinessEvent;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.bs.dao.BaseDAO;
import nc.bs.logging.Logger;
import nc.jdbc.framework.SQLParameter;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nccloud.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 收款单保存后更新到账通知的收款生成状态
 */
public class GatheringBillAfterUpdateInformer implements IBusinessListener {
    @Override
    public void doAction(IBusinessEvent event) throws BusinessException {
        String eventType = event.getEventType();
        BusinessEvent e = (BusinessEvent) event;
        AggregatedValueObject[] aggVOs = this.dealUserObj(e.getUserObject());
        // EventType是事件编码
        if ("1002".equals(eventType)) {
            // 新增后
            updateInformerGenerateFlag(aggVOs, "hasgenerate");
        } else if ("1006".equals(eventType)) {
            // 删除后
            updateInformerGenerateFlag(aggVOs, "hasnogenerate");
        }
    }

    /**
     * 更新收款单对应的到账通知 cmp_informer 的 generateflag 生成状态
     *
     * @param aggVos       收款单vo数组
     * @param generateFlag 目标状态（例如 "hasgenerate" 或 "hasnogenerate"）
     */
    private void updateInformerGenerateFlag(AggregatedValueObject[] aggVos, String generateFlag) {
        if (aggVos == null || aggVos.length == 0) {
            return; // 参数为空时直接返回
        }
        try {
            Set<String> codeSet = new LinkedHashSet<>();
            for (AggregatedValueObject aggVo : aggVos) {
                CircularlyAccessibleValueObject[] bvos = aggVo.getChildrenVO();
                for (CircularlyAccessibleValueObject bvo : bvos) {
                    String bankrelatedCode = (String) bvo.getAttributeValue("bankrelated_code");
                    if (StringUtils.isNotEmpty(bankrelatedCode) && !"~".equals(bankrelatedCode)) {
                        codeSet.add(bankrelatedCode);
                    }
                }
            }
            String[] codes = codeSet.toArray(new String[0]);
            Logger.error("updateInformerGenerateFlag-codes = " + Arrays.toString(codes));
            if (codes.length == 0) {
                return;
            }
            BaseDAO baseDAO = new BaseDAO();
            String inStr = SqlUtils.getInStr("bankrelated_code", codes, true);
            String sql = "UPDATE cmp_informer SET generateflag = ? WHERE " + inStr;
            Logger.error("updateInformerGenerateFlag-sql = " + sql);
            SQLParameter params = new SQLParameter();
            params.addParam(generateFlag);
            baseDAO.executeUpdate(sql, params);
        } catch (Exception e) {
            Logger.error("updateInformerGenerateFlag-exp:", e);
        }
    }

    private AggregatedValueObject[] dealUserObj(Object obj) {
        if (obj instanceof BusinessEvent.BusinessUserObj) {
            obj = ((BusinessEvent.BusinessUserObj) obj).getUserObj();
        }

        AggregatedValueObject[] retvos = null;
        if (obj.getClass().isArray()) {
            retvos = (AggregatedValueObject[]) obj;
        } else {
            retvos = new AggregatedValueObject[]{(AggregatedValueObject) obj};
        }

        return retvos;
    }
}
