package weaver.interfaces.secret.action;

import com.engine.secret.util.ConfigUtil;
import com.engine.secret.util.FlowUtil;
import org.apache.commons.collections.CollectionUtils;
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.*;

import java.util.*;

/**
 * @author:dxfeng
 * @createTime: 2025/04/14
 * @version: 1.0
 */
public class MeetingConveningEndAction implements Action {
    RecordSet rs = new RecordSet();
    private static final String MAIN_FLOW_TABLE = ConfigUtil.getConfig("xqxksqlc_table");

    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
            Property[] properties = mainTableInfo.getProperty();
            Map<String, String> mainDataMap = new HashMap<>();
            List<Map<String, String>> detailMapList = new ArrayList<>();
            for (Property property : properties) {
                mainDataMap.put(property.getName(), property.getValue());
            }

            DetailTableInfo detailTableInfo = requestInfo.getDetailTableInfo();
            DetailTable detailTable = detailTableInfo.getDetailTable(0);
            String detailTableName = detailTable.getTableDBName();
            String updateDetailSql = "update " + detailTableName + " set zlctjzt = ? where id = ?";
            Row[] rows = detailTable.getRow();
            for (Row row : rows) {
                Map<String, String> detailDataMap = new HashMap<>(mainDataMap);
                Cell[] cells = row.getCell();
                String detailId = row.getId();
                for (Cell cell : cells) {
                    detailDataMap.put(cell.getName(), cell.getValue());
                }
                detailDataMap.put("detailId", detailId);
                detailMapList.add(detailDataMap);
            }

            Set<String> errorMsg = new HashSet<>();
            if (CollectionUtils.isNotEmpty(detailMapList)) {
                for (Map<String, String> detail : detailMapList) {
                    dealMainFlow(requestInfo, detail, updateDetailSql, errorMsg);
                }
            }

            // 根据错误信息，返回提示
            if (CollectionUtils.isNotEmpty(errorMsg)) {
                requestInfo.getRequestManager().setMessagecontent(StringUtils.join(errorMsg, "<br/>"));
                return FAILURE_AND_CONTINUE;
            }


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

    /**
     * 提交主流程
     *
     * @param requestInfo
     * @param detail
     * @param updateDetailSql
     * @param errorMsg
     */
    private void dealMainFlow(RequestInfo requestInfo, Map<String, String> detail, String updateDetailSql, Set<String> errorMsg) {
        String mainId = detail.get("xzxksqdh");


        String conclusion = detail.get("spfhjl");
        String detailId = detail.get("detailId");
        String submitStatus = detail.get("zlctjzt");
        if ("1".equals(submitStatus)) {
            // 已经提交成功的流程，不重复处理
            return;
        }

        String mainRequestId = "";
        rs.executeQuery("select requestid from " + MAIN_FLOW_TABLE + " where id = ?", mainId);
        if (rs.next()) {
            mainRequestId = rs.getString("requestid");
        }
        if (StringUtils.isBlank(mainRequestId)) {
            errorMsg.add("主流程ID[" + mainId + "],主流程requestId获取异常，请确认");
            rs.executeUpdate(updateDetailSql, "2", detailId);
            return;
        }

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

        rs.executeUpdate("update " + MAIN_FLOW_TABLE + " set spfhjl = ? where requestid = ?", conclusion, mainRequestId);

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