package com.yem.em.bd.asscomponent.op;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author zhouc
 * @date 2023/11/13 17:25
 * @className AsscomPonentSaveEdit
 * @description 总成图册部件【保存】服务插件
 */
public class AsscomPonentSaveEdit extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> keys = e.getFieldKeys();
//        keys.add("yem_importstatus");
//        keys.add("yem_componentsentity.yem_syncstatus");
//        keys.add("yem_partentity.yem_syncstatusd");

    }

    public void endOperationTransaction(EndOperationTransactionArgs e) {
        if (e.getDataEntities() != null && e.getDataEntities().length != 0) {
            DynamicObject[] bills = e.getDataEntities();
            for (DynamicObject bill : bills) {
                List list = new ArrayList<>();
                List urllist = new ArrayList<>();
                bill = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
                List<Map<String, Object>> yemAttachmentpanelap =
                        AttachmentServiceHelper.getAttachments(bill.getDynamicObjectType().getName(), bill.getPkValue(), "yem_attachmentpanelap");
                for (int i = 0; i < yemAttachmentpanelap.size(); i++) {
                    Map<String, Object> stringObjectMap = yemAttachmentpanelap.get(i);
                    list.add(stringObjectMap.get("uid"));
                }
                if (list.size() > 0) {
                    QFilter qFilter = new QFilter("fnumber", QCP.in, list);
                    DynamicObjectCollection collection = QueryServiceHelper.query("bos_attachment",
                            "id,ffileid", new QFilter[]{qFilter}, null);
                    if (collection.size() > 0) {
                        for (int i = 0; i < collection.size(); i++) {
                            urllist.add(collection.get(i).getString("ffileid"));
                        }
                    }
                    bill.set("yem_imageurl", String.join(";", urllist) + ";");
                } else {
                    bill.set("yem_imageurl", null);
                }
                SaveServiceHelper.save(new DynamicObject[]{bill});
            }
        }
    }
}
