package com.yem.wm.im.debcrednote.list;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.exception.KDBizException;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.ListShowParameter;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouc
 * @date 2024/4/16 11:28
 * @className DebCredNoteListEdit
 * @description 贷记单列表插件
 */
public class DebCredNoteListEdit extends AbstractListPlugin {
    @Override
    public void setFilter(SetFilterEvent e) {
        super.setFilter(e);
        ListShowParameter parameter = (ListShowParameter) this.getView().getFormShowParameter();
        String billFormId = parameter.getBillFormId();
        if("yem_debcrednote_d".equals(billFormId)){
            e.addCustomQFilter(new QFilter("yem_billtype.number", QCP.equals,"yem_debcrednote_d"));
        }
        if("yem_debcrednote_j".equals(billFormId)){
            e.addCustomQFilter(new QFilter("yem_billtype.number", QCP.equals,"yem_debcrednote_j"));
        }
        if("yem_debcrednote_a".equals(billFormId)){
            e.addCustomQFilter(new QFilter("yem_billtype.number", QCP.equals,"yem_debcrednote_a"));
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        FormOperate source = (FormOperate) e.getSource();
        String operateKey = source.getOperateKey();
        if ("unaudit".equals(operateKey)) {
            ListSelectedRowCollection rows = this.getSelectedRows();
            List<Long> list = new ArrayList<>();
            for (ListSelectedRow row : rows) {
                list.add((Long) row.getPrimaryKeyValue());
            }
            StringBuilder sb = new StringBuilder();
            DynamicObject[] load = BusinessDataServiceHelper.load("yem_debcrednote", "id, billno, yem_generate", new QFilter[]{new QFilter("id", QCP.in, list)});
            for (DynamicObject dynamicObject : load) {
                String generate = dynamicObject.getString("yem_generate");
                String billno = dynamicObject.getString("billno");
                if ("B".equals(generate)) {//订单生成
                    sb.append(String.format("[ %s ] 贷记单生成方式为订单生成，不允许反审核！！", billno)).append("\r\n");
                }
            }
            if (sb.length() > 0) {
                throw new KDBizException(sb.toString());
            }
        }
    }
}
