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

import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
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.StrFormatter;
import nckd.jxccl.hr.psms.common.PositionStructureConstant;
import nckd.jxccl.hr.psms.common.bo.PositionAppointmentBO;
import nckd.jxccl.hr.psms.helper.PositionFileHelper;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.EventObject;
import java.util.Map;
import java.util.Objects;

/**
* 新入职人员初定（弹窗）-弹窗页面插件
* @author W.Y.C
* @date 2025/9/15 14:17
* @version 1.0
*/
public class NewHireInitialFormPlugin 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) {
            this.getModel().setValue(FormConstant.NCKD_PERSON, personId);
            this.getView().updateView(FormConstant.NCKD_PERSON);

            initValue(ConvertUtil.toLong(personId),null);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String fieldKey = e.getProperty().getName();
        ChangeData[] changeSet = e.getChangeSet();

        //【员工】或【调整日期】发生变更则重新获取员工任职信息
        if (PositionStructureConstant.NCKD_BEGINDATE.equalsIgnoreCase(fieldKey) || FormConstant.NCKD_PERSON.equalsIgnoreCase(fieldKey)) {
            if (changeSet != null && changeSet.length > 0) {
                ChangeData changeData = changeSet[0];
                Object oldValue = changeData.getOldValue();
                Object newValue = changeData.getNewValue();
                if (!Objects.equals(oldValue, newValue)) {
                    Date beginDate = ConvertUtil.toDate(this.getModel().getValue(PositionStructureConstant.NCKD_BEGINDATE));
                    DynamicObject person = ConvertUtil.toDynamicObject(this.getModel().getValue(PositionStructureConstant.NCKD_PERSON));
                    if(person.getDataEntityType() != null) {
                        initValue(person.getLong(FormConstant.ID_KEY), beginDate);
                    }
                }
            }
        }
    }

    /**
     * 初始化表单信息
     * @param personId 人员ID
     * @param date 日期
     * @return: void
     * @author W.Y.C
     * @date: 2025/09/25 21:40
     */
    private void initValue(Long personId, Date date){
        if(date == null){
            date = new Date();
        }
        PositionAppointmentBO positionAppointMen = PositionFileHelper.positionAppointmentQuery(personId, date);
        if(positionAppointMen != null) {
            //学历
            DynamicObject perEduExp = positionAppointMen.getPerEduExp();
            if(perEduExp != null) {
                long diplomaId = perEduExp.getLong(String.join(".", FormConstant.EDUCATION_KEY, FormConstant.ID_KEY));
                this.getModel().setValue(PositionStructureConstant.NCKD_DIPLOMA, diplomaId == 0?null:diplomaId);
            }

            //岗位、职位序列、组织分配、任职信息、本次加入集团日期
            DynamicObject empPosOrgRel = positionAppointMen.getEmpPosOrgRel();
            if(empPosOrgRel != null) {
                long positionId = empPosOrgRel.getLong(String.join(".", FormConstant.POSITION_KEY, FormConstant.ID_KEY));
                this.getModel().setValue(PositionStructureConstant.NCKD_POSITIONHR, positionId == 0 ? null : positionId);

                long jobSeqId = empPosOrgRel.getLong(String.join(".", FormConstant.HBPM_POSITIONHR, FormConstant.NCKD_JOBSEQ, FormConstant.ID_KEY));
                this.getModel().setValue(PositionStructureConstant.NCKD_JOBSEQ, jobSeqId == 0 ? null : jobSeqId);
            }

            //职称名称和职称等级
            DynamicObject perProTitle = positionAppointMen.getPerProTitle();
            if(perProTitle != null) {
                String rankName = perProTitle.getString(String.join(".", FormConstant.PROFESSIONAL_KEY, FormConstant.NAME_KEY));
                this.getModel().setValue(PositionStructureConstant.NCKD_RANKNAME, rankName);

                long proLevelId = perProTitle.getLong(String.join(".",  FormConstant.PROLEVEL_KEY, FormConstant.ID_KEY));
                this.getModel().setValue(PositionStructureConstant.NCKD_PROTITLELEVEL, proLevelId == 0 ? null : proLevelId);
            }

            //技能名称和技能等级
            DynamicObject perOcpQual = positionAppointMen.getPerOcpQual();
            if(perOcpQual != null) {
                String jobStatusName = perOcpQual.getString(String.join(".",  FormConstant.QUALIFICATION_KEY, FormConstant.NAME_KEY));
                this.getModel().setValue(PositionStructureConstant.NCKD_JOBSTATUSNAME, jobStatusName);

                long quaLevelId = perOcpQual.getLong(String.join(".", FormConstant.QUALEVEL_KEY, FormConstant.ID_KEY));
                this.getModel().setValue(PositionStructureConstant.NCKD_OCPQUALLEVEL, quaLevelId == 0 ? null : quaLevelId);
            }
            if(positionAppointMen.getExcellent() != null && positionAppointMen.getExcellent()){
                this.getModel().setValue(PositionStructureConstant.NCKD_EXCELLENT, true);
            }

            if(affirm){
                String personName = positionAppointMen.getEmpPosOrgRel().getString(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.NAME_KEY));
                //新入职确认操作，获取入职日期
                QFilter filter = new QFilter(FormConstant.EMPLOYEE_KEY, QCP.equals, personId).and(new QFilter(FormConstant.ISCURRENTDATA, QCP.equals, EnableEnum.YES.getCode()));
                DynamicObject query = QueryServiceHelper.queryOne(FormConstant.HRPI_EMPENTREL, FormConstant.ENTRYDATE, new QFilter[]{filter});
                Date entryDate = query.getDate(FormConstant.ENTRYDATE);
                //获取入职日期次年1月1号
                LocalDateTime nextYearDate = DateUtil.addYears(DateUtil.toLocalDateTime(entryDate), 1);
                LocalDateTime beginYear = DateUtil.beginOfYear(nextYearDate);
                //判断beginYear是否大于当前日期
                Date current = new Date();
                if(DateUtil.toLocalDateTime(current).isBefore(beginYear)){
                    this.getView().showTipNotification(StrFormatter.format("人员【{}】的入职时间为【{}】初定日期为【{}】，初定日期不能大于当前日期。",personName,
                            DateUtil.format(entryDate,DateUtil.NORM_DATE_PATTERN),
                            DateUtil.format(beginYear,DateUtil.NORM_DATE_PATTERN)));
                }
                this.getModel().setValue(PositionStructureConstant.NCKD_BEGINDATE, beginYear);
            }
        }

    }

    @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);
        }
    }
}