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

import kd.bos.dataentity.entity.DynamicObject;
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.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author ljw
 * @date 2024/9/23 20:35
 * @description SalesContracUnauditOp
 * 删除衣总签章
 */
public class SalesContracUnauditOp extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        e.getFieldKeys().addAll(this.billEntityType.getAllFields().keySet());
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            clearManagerSign(dataEntitie);
            createPdf(dataEntitie);
        }
    }

    /**
     * 反审核的时候，清空外销合同-经理签章；
     *
     * @param dataEntitie
     */
    private void clearManagerSign(DynamicObject dataEntitie) {
        dataEntitie.set("yem_managersign", null);
        dataEntitie.set("yem_sigstatus", false);
        dataEntitie.set("yem_siguser", null);
        dataEntitie.set("yem_sigdatetime", null);
        dataEntitie.set("yem_sigforminstid", "");
        dataEntitie.set("yem_sigflowinstid", "");
        dataEntitie.set("yem_sigmag", "");
        SaveServiceHelper.save(new DynamicObject[]{dataEntitie});
    }


    private void createPdf(DynamicObject dataEntitie) {
        List<Map<String, Object>> salesorder = AttachmentServiceHelper.getAttachments("yem_es_salescontrac", dataEntitie.getLong("id"), "yem_approval");
        for (Map<String, Object> map : salesorder) {
            DeleteServiceHelper.delete("bos_attachment", new QFilter[]{new QFilter("id", QCP.equals, map.get("attPkId"))});
        }
    }

}
