package nckd.jimin.jyyy.fi.plugin.operate;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.entity.validate.AbstractValidator;
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 nckd.base.helper.CommonHelperUtils;
import nckd.jimin.jyyy.fi.common.FinanceCommonUtils;

import java.util.Date;
import java.util.List;

/**
 * 表单标识：外办单(用车申请单nckd_er_dailyvehicleb_ext)
 * @author wanghaiwu_kd
 * @date 2025/04/29
 */
public class DailyVehicleBillSubmitOpPlugin extends AbstractOperationServicePlugIn {
    private static final Log logger = LogFactory.getLog(DailyVehicleBillSubmitOpPlugin.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);

        List<String> fieldKeys = e.getFieldKeys();

        fieldKeys.add("applier");
        fieldKeys.add("startdate");
        fieldKeys.add("enddate");
        fieldKeys.add("nckd_ischange");
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);

        e.addValidator(new AbstractValidator() {
            @Override
            public void validate() {
                ExtendedDataEntity[] dataEntitys = this.getDataEntities();
                for (ExtendedDataEntity dataEntity : dataEntitys) {
                    if(dataEntity == null){
                        continue;
                    }
                    DynamicObject vehicleReqBillInfo = dataEntity.getDataEntity();

                    Date startDate = vehicleReqBillInfo.getDate("startdate");
                    Date endDate = vehicleReqBillInfo.getDate("enddate");

                    if(startDate == null || endDate == null){
                        this.addErrorMessage(dataEntity, "开始时间、结束时间不能为空!");
                    }

                    Long billId = vehicleReqBillInfo.getLong("id");
                    Long userId = vehicleReqBillInfo.getDynamicObject("applier").getLong("id");

                    String checkMsg = FinanceCommonUtils.checkDateIsExists(billId, userId, startDate, endDate);

                    if(checkMsg.length() > 0) {
                        this.addErrorMessage(dataEntity, "存在开始时间、结束时间重叠的单据!" + checkMsg);
                    }

                    //如果是变更行程，需要与变更前的做校验
                    QFilter qFilter = new QFilter("id", QCP.equals, vehicleReqBillInfo.getLong("id"));

                    String selectFields = "nckd_historyentry.nckd_historystartdate, nckd_historyentry.nckd_historyenddate, nckd_historyentry.nckd_changetime";

                    DynamicObjectCollection historyEntities = QueryServiceHelper.query(vehicleReqBillInfo.getDataEntityType().getName(), selectFields, qFilter.toArray(), "nckd_historyentry.nckd_changetime desc");

                    if (vehicleReqBillInfo.getBoolean("nckd_ischange") && historyEntities.size() > 0) {
                        DynamicObject historyEntry = historyEntities.get(0);
                        Date now = new Date();
                        Date curStartDate = vehicleReqBillInfo.getDate("startdate");
                        Date hisStartDate = historyEntry.getDate("nckd_historyentry.nckd_historystartdate");

                        Date curEndDate = vehicleReqBillInfo.getDate("enddate");
                        Date hisEndDate = historyEntry.getDate("nckd_historyentry.nckd_historyenddate");

                        String nowString = CommonHelperUtils.getDateFormatString(now, "yyyy-MM-dd HH:mm:ss");
                        String curStartDateString = CommonHelperUtils.getDateFormatString(curStartDate, "yyyy-MM-dd HH:mm:ss");
                        String hisStartDateString = CommonHelperUtils.getDateFormatString(hisStartDate, "yyyy-MM-dd HH:mm:ss");
                        String curEndDateString = CommonHelperUtils.getDateFormatString(curEndDate, "yyyy-MM-dd HH:mm:ss");
                        String hisEndDateString = CommonHelperUtils.getDateFormatString(hisEndDate, "yyyy-MM-dd HH:mm:ss");

                        if(hisStartDate.compareTo(now) > 0){
                            if(curStartDate.compareTo(now) < 0){
                                this.addErrorMessage(dataEntity, "出差前变更, 变更后的开始时间(" + curStartDateString + ")不能小于当前时间(" + nowString + ")");
                            }
                        } else {
                            if(curStartDate.compareTo(hisStartDate) < 0){
                                this.addErrorMessage(dataEntity, "出差后变更, 变更后的开始时间(" + curStartDateString + ")不能小于原开始时间(" + hisStartDateString + ")");
                            }
                        }

                        if(curEndDate.compareTo(hisEndDate) > 0){
                            this.addErrorMessage(dataEntity, "变更后的结束时间(" + curEndDateString + ")不能大于原结束时间(" + hisEndDateString + ")");
                        }
                    }
                }
            }
        });
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
    }
}
