package com.engine.secret.service.impl;

import com.engine.core.impl.Service;
import com.engine.secret.exception.CustomizeRunTimeException;
import com.engine.secret.service.AuthorityChangeService;
import com.engine.secret.util.FlowUtil;
import com.engine.secret.util.ModeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;

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

/**
 * @author:dxfeng
 * @createTime: 2025/04/09
 * @version: 1.0
 */
public class AuthorityChangeServiceImpl extends Service implements AuthorityChangeService {
    @Override
    public Map<String, Object> delegateToProvincialAuthority(Map<String, Object> param) {
        RecordSet rs = new RecordSet();
        String ids = Util.null2String(param.get("ids"));
        if (StringUtils.isBlank(ids)) {
            throw new CustomizeRunTimeException("请至少选择一条数据");
        }
        String customId = Util.null2String(param.get("customId"));
        if (StringUtils.isBlank(customId)) {
            throw new CustomizeRunTimeException("未获取到查询列表ID");
        }
        String modeTableName = ModeUtil.getTableNameByCustomId(customId);
        rs.writeLog("ids==" + ids);
        rs.writeLog("customId==" + customId);
        rs.writeLog("modeTableName==" + modeTableName);
        String options = user.getLastname() + "-自动提交流程-";

        // 查询对应的流程,并更新
        String[] split = ids.split(",");
        for (String s : split) {
            rs.writeLog("id==" + s);
            // 更新事权类别为省级事权
            rs.executeUpdate("update " + modeTableName + " set bmzzzgsqlb = ?,tjdqjd = ? where id =? ", 0, 1, s);
            // 查询对应的requestId
            rs.executeQuery("select requestId from " + modeTableName + " where id = ?", s);
            if (rs.next()) {
                String requestId = rs.getString("requestId");
                rs.writeLog("requestId==" + requestId);
                List<Integer> currentUserIds = FlowUtil.getCurrentUserIds(requestId);
                if (CollectionUtils.isEmpty(currentUserIds)) {
                    throw new CustomizeRunTimeException("requestId[" + requestId + "],流程提交失败，未获取到当前节点处理人");
                }

                String submitResult = FlowUtil.submitWorkflowRequest(requestId, currentUserIds.get(0), options + DateUtil.getFullDate());
                if (!"success".equals(submitResult)) {
                    throw new CustomizeRunTimeException("requestId[" + requestId + "],流程提交失败");
                }
            }
        }


        return new HashMap<>();
    }
}
