package nckd.jxccl.wtc.wtabm.vaapply;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.IFormView;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.hr.hbp.formplugin.web.HRDataBaseEdit;
import nckd.jxccl.wtc.wtabm.web.common.util.WtcUtils;

import java.util.Date;

/**
 * Tyx 2025-10-13
 *
 * 休假信息_单人单类型【wtabm_vainfosingle】表单插件
 */
public class VaInfoEditEx extends HRDataBaseEdit {

    private static final Log log = LogFactory.getLog(VaInfoEditEx.class);

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        DynamicObject dataEntity = this.getModel().getDataEntity();
        if(name.equals("datechange") || name.equals("vacationtype")) {
            String typeNumber = dataEntity.getString("vacationtype.number");
            Date startDate = dataEntity.getDate("startdate");
            Date endDate = dataEntity.getDate("enddate");
            // 如果这些都不为空
            if(!(ObjectUtils.isEmpty(typeNumber) || ObjectUtils.isEmpty(startDate) || ObjectUtils.isEmpty(endDate))) {
                // 获取父页面的employeeId
                IFormView parentView = this.getView().getParentView();
                IDataModel parentModel = parentView.getModel();
                DynamicObject parentDataEntity = parentModel.getDataEntity();
                Long employeeId = parentDataEntity.getLong("attfilebasef7.employee.id");
                log.info("-------- 开始查询历史休假明细 empId：{}, typeNumber：{}", employeeId, typeNumber);
                DynamicObjectCollection historyBillCols = WtcUtils.getHistoryVaApplyInfos(employeeId, startDate, typeNumber);
                log.info("-------- 结束查询历史休假明细 条数：{}", historyBillCols.size());

                // 先删除现有的历史休假明细数据
                parentModel.deleteEntryData("nckd_hisentryentity");
                for (DynamicObject historyDyn : historyBillCols) {
                    int row = parentModel.createNewEntryRow("nckd_hisentryentity");
                    parentModel.setValue("nckd_hisvaltype", historyDyn.getString("entryentity.entryvacationtype.name"), row);
                    parentModel.setValue("nckd_hisstartdate", historyDyn.getDate("startdate"), row);
                    parentModel.setValue("nckd_hisenddate", historyDyn.getDate("enddate"), row);
                    parentModel.setValue("nckd_hisapplytime", historyDyn.getBigDecimal("applytime"), row);
                }
                // 刷新父页面
                this.getView().sendFormAction(parentView);
            }
        }
    }
}
