package com.awspaas.user.apps.donenow_ctt.event;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.InterruptListener;
import com.actionsoft.bpms.bpmn.engine.listener.ListenerConst;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import static com.awspaas.user.apps.donenow_ctt.service.contractService.getLocalDate;

public class editServiceFormBeforeSave extends InterruptListener {
    public String getDescription() {
        return "合同服务调整保存前的事件测试";
    }

    /**
     *
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public boolean execute(ProcessExecutionContext param) throws Exception {

        String boId = param.getParameterOfString(ListenerConst.FORM_EVENT_PARAM_BOID);
        String boName = param.getParameterOfString(ListenerConst.FORM_EVENT_PARAM_BONAME);
        BO formData = (BO) param.getParameter(ListenerConst.FORM_EVENT_PARAM_FORMDATA);

        LocalDate EFFECTIVE_DATE = getLocalDate(formData.get("EFFECTIVE_DATE"));//服务生效日期
        String EFFECTIVE_DATE_STR = EFFECTIVE_DATE.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        if (DBSql.getInt("SELECT count(1) FROM BO_EU_DNCTT_CONTRACT_SERVICE_PERIOD WHERE APPROVE_AND_POST_USER_ID IS NOT NULL AND LENGTH(APPROVE_AND_POST_USER_ID)>1 AND APPROVE_AND_POST_DATE IS NOT NULL and CONTRACT_ID=? and CONTRACT_SERVICE_ID=? AND  PERIOD_END_DATE>=?", new Object[]{formData.get("CONTRACT_ID"), formData.get("CONTRACT_SERVICE_ID"), EFFECTIVE_DATE_STR}) > 0) {
            throw new BPMNError("500", EFFECTIVE_DATE_STR + "之后的服务周期已被审批，则不能修改到当前日期");
        }

        String IS_EFFECTIVE = formData.getString("IS_EFFECTIVE");
        if (!IS_EFFECTIVE.equals("未执行"))
            return false;

        dn.recordFormChanges.execute(param);
        return true;
    }
}
