package weaver.interfaces.secret.action;

import com.engine.secret.util.FlowUtil;
import org.apache.commons.lang.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * 审批复核 归档Action
 *
 * @author:dxfeng
 * @createTime: 2025/04/09
 * @version: 1.0
 */
public class ApprovalReviewEndAction implements Action {
    RecordSet rs = new RecordSet();

    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
            Property[] properties = mainTableInfo.getProperty();
            Map<String, String> mainDataMap = new HashMap<>();
            for (Property property : properties) {
                mainDataMap.put(property.getName(), property.getValue());
            }
            // 获取主流程ID
            String mainRequestId = mainDataMap.get("zlcid");
            if (StringUtils.isBlank(mainRequestId)) {
                requestInfo.getRequestManager().setMessagecontent("未获取到主流程请求ID");
                return FAILURE_AND_CONTINUE;
            }

            // 获取审批复核结论
            String conclusion = mainDataMap.get("spfhjl");

            // 更新主流程表单的审批复核结论
            String tableNameByRequestId = FlowUtil.getTableNameByRequestId(mainRequestId);
            if (StringUtils.isBlank(tableNameByRequestId)) {
                requestInfo.getRequestManager().setMessagecontent("主流程表单名称获取异常，请确认");
                return FAILURE_AND_CONTINUE;
            }
            String sql = "update " + tableNameByRequestId + " set spfhjl = ? where requestid = ?";

            rs.writeLog("mainRequestId==" + mainRequestId);
            rs.writeLog("conclusion==" + conclusion);
            rs.writeLog("tableNameByRequestId==" + tableNameByRequestId);
            rs.writeLog("sql==" + sql);

            rs.executeUpdate(sql, conclusion, mainRequestId);

            // 更新完成后，自动提交流程到下一节点
            rs.writeLog("mainRequestId==" + mainRequestId);
            String options = requestInfo.getCreatorid() + "-自动提交流程-" + DateUtil.getFullDate();
            String submitResult = FlowUtil.submitWorkflowRequest(mainRequestId, options);
            if (!"success".equals(submitResult)) {
                requestInfo.getRequestManager().setMessagecontent("requestId[" + mainRequestId + "],流程提交失败");
                return FAILURE_AND_CONTINUE;
            }

            return SUCCESS;
        } catch (Exception e) {
            rs.writeLog(e);
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return FAILURE_AND_CONTINUE;
        }
    }
}
