package nckd.jxccl.hr.htm.plugin.form.quitapply;

import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.hr.hbp.business.servicehelper.HRMServiceHelper;
import nckd.jxccl.hr.htm.common.quitapply.QuitApplyConstant;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 离职申请单表单插件
 * @entity: nckd_htm_quitapply_ext
 * @author: jtd
 * @date: 2025/11/18 22:53
 */
public class QuitApplyFormPlugin extends AbstractFormPlugin {
    private static final Log log = LogFactory.getLog(QuitApplyFormPlugin.class);

    /** 培养协议合同类型编码 */
    private static final String CONTRACTTYPE_NUMBER = "JT01";

    /*@Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        super.preOpenForm(e);

        // 如果打开的是退休页面，则一定要携带isFromRetire参数才允许，否则表示来自离职页面
        BillShowParameter showParameter = (BillShowParameter) e.getFormShowParameter();
        String formId = showParameter.getFormId();
        Map<String, Object> customParams = showParameter.getCustomParams();
        if (!QuitApplyConstant.NCKD_RETIREAPPLY_ENTITY.equals(formId) && customParams == null || !customParams.containsKey("isFromRetire")) {
            e.setCancel(true);
        }
    }*/

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);

        String propertyName = e.getProperty().getName();
        Object newValue = e.getChangeSet()[0].getNewValue();
        switch (propertyName) {
            case QuitApplyConstant.CONTRACTENDDATE_KEY:
                DynamicObject quitPersonDy = (DynamicObject) getModel().getValue(QuitApplyConstant.BB_EM_TID_KEY);
                Date contractEndDate = (Date) newValue;
                if (quitPersonDy == null || contractEndDate == null) {
                    getModel().setValue(QuitApplyConstant.NCKD_UNUSEDANNUALLEAVE_KEY, 0);
                    return;
                }
                Long employeeId = quitPersonDy.getLong(QuitApplyConstant.ID_KEY);
                setUnUsedAnnualLeave(employeeId, contractEndDate);
                setTrainingAgmtStat(employeeId, contractEndDate);

                break;
            case QuitApplyConstant.BB_EM_TID_KEY:
                // 获取员工确认退休日期
                if (newValue != null) {
                    DynamicObject newValueDy = (DynamicObject) newValue;
                    Date empcfmretdt = newValueDy.getDate(QuitApplyConstant.NCKD_EMPCFMRETDT_KEY);
                    if (empcfmretdt != null) {
                        getModel().setValue(QuitApplyConstant.CONTRACTENDDATE_KEY, empcfmretdt);
                    }
                }
        }
    }

    /**
     * 设置应休未休剩余年假
     * @param employeeId 离职人员
     * @param contractEndDate 离职日期
     */
    private void setUnUsedAnnualLeave(Long employeeId, Date contractEndDate) {
        log.info("设置应休未休剩余年假>>>nckd.jxccl.hr.htm.plugin.form.quitapply.QuitApplyFormPlugin.setUnUsedAnnualLeave");
        // 获取人员考勤档案
        //String attFileSerializedString = DispatchServiceHelper.invokeService("nckd.jxccl.wtc.wtp.servicehelper", QuitApplyConstant.WTP_APP, "IWTPCustomerService", "getAttFile", new Object[]{contractEndDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), employeeId});
        Object attFileObj = HRMServiceHelper.invokeBizService(QuitApplyConstant.WTC_CLOUD, QuitApplyConstant.WTBS_APP, "IAttFileQueryService", "attFileQuery", new Object[]{contractEndDate, employeeId});
        log.info("设置应休未休剩余年假>>>attFileObj:::"+attFileObj);
        if (attFileObj == null) {
            getView().showTipNotification("未获取到应休未休剩余年假，请检查离职人员是否存在离职时间内有效的考勤档案");
            return;
        }
        Map<String, Object> attFile = SerializationUtils.fromJsonString(SerializationUtils.toJsonString(attFileObj), HashMap.class);

        List<DynamicObject> quotaList = HRMServiceHelper.invokeBizService(QuitApplyConstant.WTC_CLOUD, QuitApplyConstant.WTP_APP, "IQTService", "queryQuota", new Object[]{attFile.get("boId"), Collections.singletonList(1666695290893207552L), 0, contractEndDate, contractEndDate});
        //List<DynamicObject> quotaList = DispatchServiceHelper.invokeService("nckd.jxccl.wtc.wtp.servicehelper", QuitApplyConstant.WTP_APP, "IWTPCustomerService", "queryQuota", new Object[]{attFile.get("boId"), Collections.singletonList(1666695290893207552L), 0, contractEndDate, contractEndDate});
        log.info("设置应休未休剩余年假>>>quotaList.size:::"+(quotaList.isEmpty() ? 0 : quotaList.size()));
        if (quotaList != null && !quotaList.isEmpty()) {
            BigDecimal quota = BigDecimal.ZERO;
            for (DynamicObject quotaDy : quotaList) {
                quota = quota.add(quotaDy.getBigDecimal(QuitApplyConstant.USABLEVALUE_KEY) == null ? BigDecimal.ZERO : quotaDy.getBigDecimal(QuitApplyConstant.USABLEVALUE_KEY));
            }
            getModel().setValue(QuitApplyConstant.NCKD_UNUSEDANNUALLEAVE_KEY, quota);
        } else {
            getModel().setValue(QuitApplyConstant.NCKD_UNUSEDANNUALLEAVE_KEY, 0);
        }
    }

    /**
     * 设置是否还在培养协议期内
     * @param employeeId
     * @param contractEndDate
     */
    private void setTrainingAgmtStat(Long employeeId, Date contractEndDate) {
        // 过滤员工
        QFilter qFilter = new QFilter(String.format("%s.id", QuitApplyConstant.EMPLOYEE_KEY), QCP.equals, employeeId);
        // 过滤合同类型
        qFilter.and(new QFilter(String.format("%s.number", QuitApplyConstant.CONTRACTTYPE_KEY), QCP.equals, CONTRACTTYPE_NUMBER));
        // 过滤日期
        qFilter.and(new QFilter(QuitApplyConstant.STARTDATE_KEY, QCP.less_equals, contractEndDate));
        qFilter.and(new QFilter(QuitApplyConstant.PLANENDDATE_KEY, QCP.large_equals, contractEndDate));
        // 过滤状态
        qFilter.and(new QFilter(QuitApplyConstant.CONTRACTSTATUS_KEY, QCP.equals, EnableEnum.YES.getCode()));
        boolean exists = QueryServiceHelper.exists(QuitApplyConstant.HLCM_CONTRACTFILEOTHER_ENTITY, new QFilter[]{qFilter});
        if (exists) {
            getModel().setValue(QuitApplyConstant.NCKD_TRAINING_AGMT_STAT_KEY, Boolean.TRUE);
        } else {
            getModel().setValue(QuitApplyConstant.NCKD_TRAINING_AGMT_STAT_KEY, Boolean.FALSE);
        }
    }
}
