package nckd.jxccl.hrmp.hbpm.plugin.operate.hr;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.common.util.HRStringUtils;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.hrmp.hbpm.business.hr.service.impl.PositionBillServiceHelper;
import nckd.jxccl.hrmp.hbpm.common.hr.PositionBillConstant;
import nckd.jxccl.hrmp.hbpm.plugin.operate.hr.validator.PositionBillDeleteStatusValidator;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 岗位申请单删除操作插件
 * @entity: nckd_positionbill
 * @from: kd.hr.homs.opplugin.web.orgbatch.AdminOrgBatchBillDeleteOpPlugin
 * @operate: delete
 * @author: jtd
 * @date: 2025/12/31 21:29
 */
public class PositionBillDeleteOpPlugin extends AbstractOperationServicePlugIn {

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new PositionBillDeleteStatusValidator());
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs args) {
        super.beginOperationTransaction(args);
        DynamicObject[] datas = args.getDataEntities();
        if (datas.length > 0) {
            List<Long> selectedRows = Arrays.stream(datas).map((dyn) -> dyn.getLong(PositionBillConstant.ID_KEY)).collect(Collectors.toList());
            HRBaseServiceHelper positionBillEntryHelper = new HRBaseServiceHelper(PositionBillConstant.NCKD_POSITIONBILLENTRY_ENTITY);
            QFilter billIdFilter = new QFilter(PositionBillConstant.NCKD_BILLID, QCP.in, selectedRows);
            String selectProperties = QueryFieldBuilder.create().add(PositionBillConstant.ID_KEY)
                    .add(PositionBillConstant.NUMBER_KEY)
                    .add(PositionBillConstant.NCKD_CHANGETYPE, PositionBillConstant.NUMBER_KEY)
                    .add(PositionBillConstant.NCKD_POSITION_KEY)
                    .buildSelect();
            DynamicObject[] positionBillEntryDyns = positionBillEntryHelper.query(selectProperties, new QFilter[]{billIdFilter});
            List<Long> addPositionEntryIdList = Arrays.stream(positionBillEntryDyns).filter((dyn) -> HRStringUtils.equals(dyn.getDynamicObject(PositionBillConstant.NCKD_CHANGETYPE).getString(PositionBillConstant.NUMBER_KEY), PositionBillConstant.ADD_TAG)).map((dyn) -> dyn.getLong(String.join(".", PositionBillConstant.NCKD_POSITION_KEY, PositionBillConstant.ID_KEY))).collect(Collectors.toList());
            PositionBillServiceHelper.delAddMaster(addPositionEntryIdList);
        }

    }
}
