package com.engine.recruit.util;

import com.engine.recruit.exception.CustomizeRunTimeException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author:dxfeng
 * @createTime: 2023/10/12
 * @version: 1.0
 */
public class RecruitFlowUtil {
    private static final Pattern URL_REG = Pattern.compile("\\$(.*?)\\$");


    /**
     * 解析url中参数信息
     *
     * @param urlString url地址
     * @return
     */
    public static Map<String, String> parseURL(String urlString) {
        Map<String, String> params = new HashMap<>();
        try {
            if (StringUtils.isNotBlank(urlString)) {
                if (urlString.contains("?")) {
                    urlString = urlString.split("\\?")[1];
                }
                String[] paramPairs = urlString.split("&");
                for (String paramPair : paramPairs) {
                    String[] keyValue = paramPair.split("=");
                    if (keyValue.length == 2) {
                        String key = URLDecoder.decode(keyValue[0], "UTF-8");
                        String value = URLDecoder.decode(keyValue[1], "UTF-8");
                        params.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            throw new CustomizeRunTimeException(urlString + "解析失败");
        }

        return params;
    }

    /**
     * 替换URL中Id字段
     *
     * @param urlString
     * @param billId
     * @return
     */
    public static String replaceURL(String urlString, String billId) {
        Matcher matcher = URL_REG.matcher(urlString);
        Set<String> matches = new HashSet<>();
        while (matcher.find()) {
            matches.add(matcher.group(1));
        }
        matches.remove("parentid");
        if (CollectionUtils.isNotEmpty(matches)) {
            String fields = StringUtils.join(matches, ",");
            RecordSet rs = new RecordSet();
            rs.executeQuery("select " + fields + " from uf_jcl_yppc where id = ? ", billId);
            if (rs.next()) {
                for (String match : matches) {
                    urlString = urlString.replaceAll("\\$" + match + "\\$", rs.getString(match));
                }
            }
        }
        return urlString.replaceAll("\\$parentid\\$", billId);
    }
}
