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.ExecuteListener;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;

import java.sql.Connection;

public class costProductFormAfterSave extends ExecuteListener {
    public String getDescription() {
        return "合同产品新增后，创建采购审批";
    }

    /**
     * 执行合同成本状态更新操作
     * @param processExecutionContext 流程执行上下文，用于获取业务对象和其他流程相关数据
     * @throws Exception 当数据库操作失败或业务逻辑异常时抛出
     */
    @Override
    public void execute(ProcessExecutionContext processExecutionContext) throws Exception {

        Connection conn = null;
        try {
            // 开启数据库事务连接
            conn = DBSql.open();
            conn.setAutoCommit(false);

            // 获取合同产品业务对象并设置初始状态为"待采购/待拣货"
            BO costBO = processExecutionContext.getBO("BO_EU_DNCTT_CONTRACT_COST");
            costBO.set("STATUS_ID", "1234");

            // 检查产品是否为无需采购类型，如果是则直接将状态改为"已配送"
            if (DBSql.getInt(conn, "select DOES_NOT_REQUIRE_PROCUREMENT from BO_EU_DNIVT_PRODUCT where ID=?", new Object[]{costBO.get("PRODUCT_ID")}) == 1) {
                costBO.set("STATUS_ID", "1237");
            }

            // 更新合同成本业务对象状态
            SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT_COST", costBO, conn);

            // 提交事务
            conn.commit();
        } catch (Exception e) {
            // 发生异常时回滚事务并抛出自定义BPMN错误
            conn.rollback();
            throw new BPMNError("550", "库存转移失败");
        } finally {
            // 关闭数据库连接
            DBSql.close(conn);
        }

    }

}
