package nckd.jxccl.opmc.pm.plugin.form.print;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.FormShowParameter;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
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 kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.opmc.pm.common.PerfManagerFormConstant;

import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
* 批量修改文件印发及盖章时间
* 实体标识：nckd_batchmoddocstamppopu
* @author W.Y.C
* @date 2025/12/7 21:20
* @version 1.0
*/
public class BatchModDocstampPopupFormPlugin extends AbstractFormPlugin implements Plugin {


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        String operateKey = e.getOperateKey();
        if(e.getOperationResult() != null && e.getOperationResult().isSuccess()) {
            FormShowParameter showParameter = this.getView().getFormShowParameter();
            //获取列表选择的人员
            Object personIds = showParameter.getCustomParam("personIds");
            List<Object> list = ConvertUtil.toList(personIds);
            if (FormConstant.AFFIRM_OP.equalsIgnoreCase(operateKey)) {
                Date fileIssueTime = this.getModel().getDataEntity(true).getDate(PerfManagerFormConstant.NCKD_FILEISSUETIME);
                Date stampTime = this.getModel().getDataEntity(true).getDate(PerfManagerFormConstant.NCKD_STAMPTIME);
                DynamicObjectCollection query = QueryServiceHelper.query(PerfManagerFormConstant.DOCSTAMP_ENTITYID,
                        FormConstant.ID_KEY,
                        new QFilter[]{new QFilter(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY), QCP.in, list)});
                List<Long> ids = query.stream().map(dynamicObject -> dynamicObject.getLong(FormConstant.ID_KEY)).collect(Collectors.toList());
                MainEntityType docStampEntityType = EntityMetadataCache.getDataEntityType(PerfManagerFormConstant.DOCSTAMP_ENTITYID);
                DynamicObject[] load = BusinessDataServiceHelper.load(ids.toArray(new Long[0]), docStampEntityType);
                // 提取查询结果中的人员ID
                List<DynamicObject> save = new java.util.ArrayList<>();
                java.util.Set<Long> foundPersonIds = new java.util.HashSet<>();
                for (DynamicObject dynamicObject : load) {
                    Long personId = dynamicObject.getLong(String.join(".", FormConstant.NCKD_PERSON, FormConstant.ID_KEY));
                    foundPersonIds.add(personId);
                    dynamicObject.set(PerfManagerFormConstant.NCKD_STAMPTIME, stampTime);
                    dynamicObject.set(PerfManagerFormConstant.NCKD_FILEISSUETIME, fileIssueTime);
                    save.add(dynamicObject);
                }

                // 计算不在查询结果中的人员ID（即没有文档印章记录的人员ID）
                java.util.List<Long> missingPersonIds = new java.util.ArrayList<>();
                for (Object personId : list) {
                    Long id = ConvertUtil.toLong(personId);
                    if (!foundPersonIds.contains(id)) {
                        missingPersonIds.add(id);
                    }
                }
                for (Long missingPersonId : missingPersonIds) {
                    DynamicObject dynamicObject = EntityHelper.newEntity(PerfManagerFormConstant.DOCSTAMP_ENTITYID);
                    DynamicObject employee = EntityHelper.newEntity(FormConstant.HRPI_EMPLOYEE,missingPersonId);
                    dynamicObject.set(FormConstant.NCKD_PERSON,employee);
                    dynamicObject.set(PerfManagerFormConstant.NCKD_STAMPTIME, stampTime);
                    dynamicObject.set(PerfManagerFormConstant.NCKD_FILEISSUETIME, fileIssueTime);
                    save.add(dynamicObject);

                }
                OperationResult operationResult = SaveServiceHelper.saveOperate(
                        PerfManagerFormConstant.DOCSTAMP_ENTITYID,
                        save.toArray(new DynamicObject[0]),
                        OperateOption.create());

                if (!operationResult.isSuccess()) {
                    StringJoiner errorMsg = new StringJoiner("\n");
                    for (IOperateInfo error : operationResult.getAllErrorOrValidateInfo()) {
                        errorMsg.add(error.getMessage());
                    }
                    if (!ObjectUtils.isEmpty(operationResult.getMessage())) {
                        errorMsg.add(operationResult.getMessage());
                    }
                    throw new ValidationException("保存失败" + errorMsg.toString());
                }else{
                    this.getView().returnDataToParent("true");
                    this.getView().close();
                }



               /* Date fileIssueTime = this.getModel().getDataEntity(true).getDate("nckd_fileissuetime");
                Date stampTime = this.getModel().getDataEntity(true).getDate("nckd_stamptime");
                Map<String, Date> returnDate = new HashMap<>();
                returnDate.put("nckd_fileissuetime", fileIssueTime);
                returnDate.put("nckd_stamptime", stampTime);
                this.getView().returnDataToParent(returnDate);
                this.getView().close();*/
            }
        }
    }
}