package nckd.jxccl.hr.psms.plugin.form.initial;

import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.FormShowParameter;
import kd.bos.form.MessageBoxOptions;
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.QueryServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
* 新入职人员初定（弹窗）-弹窗页面插件
* @author W.Y.C
* @date 2025/9/15 14:17
* @version 1.0
*/
public class NewHireInitialBatchFormPlugin extends AbstractFormPlugin implements Plugin {

    private boolean affirm = false;

    @Override
    public void afterCreateNewData(EventObject e) {
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        //获取列表选择的人员
        Object personId = showParameter.getCustomParam("personId");
        affirm = ConvertUtil.toBoolean(showParameter.getCustomParam("affirm"),false);
        if(personId != null) {
            initValue(ConvertUtil.toList(personId));
        }
    }


    /**
     * 初始化表单信息
     * @param personIds 人员ID
     * @return: void
     * @author W.Y.C
     * @date: 2025/09/25 21:40
     */
    private void initValue(List<Long> personIds){
        if(!personIds.isEmpty()) {
            this.getModel().batchCreateNewEntryRow(FormConstant.NCKD_ENTRYENTITY, personIds.size() - 1);
        }
        Map<Long, DynamicObject> personNextYearDateMap = new HashMap<>();
        if(affirm && !personIds.isEmpty()){
            //新入职确认操作，获取入职日期
            QFilter filter = new QFilter(FormConstant.EMPLOYEE_KEY, QCP.in, personIds).and(new QFilter(FormConstant.ISCURRENTDATA, QCP.equals, EnableEnum.YES.getCode()));
            QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                    .add(FormConstant.ENTRYDATE)
                    .addIdNumberName(FormConstant.EMPLOYEE_KEY);
            DynamicObjectCollection query = QueryServiceHelper.query(FormConstant.HRPI_EMPENTREL, queryFieldBuilder.buildSelect(), new QFilter[]{filter});
            personNextYearDateMap = query.stream()
                    .collect(Collectors.toMap(
                            obj -> obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY)),
                            obj -> obj
                    ));

        }
        StringJoiner notification = new StringJoiner(StrFormatter.LINE_SEPARATOR);
        Date current = new Date();
        for (int i = 0; i < personIds.size(); i++) {
            this.getModel().setValue(FormConstant.NCKD_PERSON,personIds.get(i), i);

            if(personNextYearDateMap.get(personIds.get(i)) != null) {
                DynamicObject dynamicObject = personNextYearDateMap.get(personIds.get(i));
                Date entryDate = dynamicObject.getDate(FormConstant.ENTRYDATE);
                //获取入职日期次年1月1号
                LocalDateTime nextYearDate = DateUtil.addYears(DateUtil.toLocalDateTime(entryDate), 1);
                LocalDateTime beginYear = DateUtil.beginOfYear(nextYearDate);

                this.getModel().setValue(PositionStructureConstant.NCKD_BEGINDATE, beginYear,i);

                //判断beginYear是否大于当前日期
                if (DateUtil.toLocalDateTime(current).isBefore(beginYear)) {
                    String personName = dynamicObject.getString(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.NAME_KEY));
                    notification.add(StrFormatter.format("人员【{}】的入职时间为【{}】初定日期为【{}】，初定日期不能大于当前日期；",personName,
                            DateUtil.format(entryDate,DateUtil.NORM_DATE_PATTERN),
                            DateUtil.format(beginYear,DateUtil.NORM_DATE_PATTERN)));

                }
            }


        }
        if(notification.length() > 0){
            this.getView().showTipNotification(notification.toString());
        }


        this.getView().updateView(FormConstant.NCKD_ENTRYENTITY);
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        String operateKey = afterDoOperationEventArgs.getOperateKey();
        boolean success = afterDoOperationEventArgs.getOperationResult() != null && afterDoOperationEventArgs.getOperationResult().isSuccess();
        if(success && PositionStructureConstant.OP_CONFIRMINITIAL.equalsIgnoreCase(operateKey)){
            Map<String, String> customData = afterDoOperationEventArgs.getOperationResult().getCustomData();
            String jobLeveStr = customData.get(PositionStructureConstant.NCKD_JOBLEVELHR);
            this.getView().returnDataToParent("true");
            this.getView().showConfirm("提示","初定成功，职位档案已生成。",jobLeveStr, MessageBoxOptions.OK,null,null,null,null);
        }
    }
}