package com.yem.wm.es.salesorder.op;

import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import com.yem.wm.utils.GiftAmount;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

public class SaleOrderBillCancelOp extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("billstatus");
    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntity : dataEntities) {
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            List list = new ArrayList<>();
            String billno = dataEntity.getString("billno");
            QFilter qFilter = new QFilter("yem_im_giftamount_o.yem_origintype", QCP.equals, "A");
            qFilter.and(new QFilter("yem_im_giftamount_o.yem_originno", QCP.equals, billno));
            DynamicObjectCollection yem_shippingdetails = QueryServiceHelper.query("yem_im_giftamount", "id,billno", new QFilter[]{qFilter}, null);
            if (yem_shippingdetails.size() > 0) {
                for (DynamicObject shippingdetails : yem_shippingdetails) {
                    String shippbillno = shippingdetails.getString("id");
                    list.add(shippbillno);
                }
            }
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Object o = list.get(i);
                    DynamicObject data = BusinessDataServiceHelper.loadSingle(o, "yem_im_giftamount");
                    if (data != null) {
                        DynamicObjectCollection entryentity = data.getDynamicObjectCollection("yem_im_giftamount_o");
                        for (int j = 0; j < entryentity.size(); j++) {
                            if (entryentity.get(j).getString("yem_originno").equals(billno)) {
                                entryentity.remove(j);
                            }
                        }
                        SaveServiceHelper.save(new DynamicObject[]{data});
                        GiftAmount.Calculate(data.getLong("yem_groupcusfields.id"),data.getLong("org.id"), data.getLong("yem_bd_products.id"));
                    }
                }
            }
        }
    }
}
