package com.engine.secret.util;

import com.weaver.formmodel.data.model.Formfield;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.GenericValidator;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.definedfield.HrmFieldManager;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:dxfeng
 * @createTime: 2025/04/02
 * @version: 1.0
 */
public class FieldConvertUtil {

    /**
     * 转换存入数据库的值
     *
     * @param formfield
     * @param value
     * @return
     * @throws Exception
     */
    public static Object getReallyValue(Formfield formfield, String value) throws Exception {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        RecordSet rs = new RecordSet();
        Object object = null;
        String type = Util.null2String(formfield.getType());
        switch (formfield.getFieldhtmltype()) {
            case "1":
                // INPUT
                if ("2".equals(type)) {
                    object = new BigDecimal(value).intValue();
                } else if ("3".equals(type)) {
                    object = new BigDecimal(value).floatValue();
                } else if ("1".equals(type)) {
                    object = value;
                } else {
                    try {
                        object = new BigDecimal(value).toPlainString();
                    } catch (NumberFormatException ignore) {
                        object = value;
                    }
                }
                break;
            case "3":
                // BROWSER
                org.json.JSONObject jsonObject = new org.json.JSONObject();
                jsonObject.put("fieldhtmltype", formfield.getFieldhtmltype());
                jsonObject.put("type", type);
                jsonObject.put("fieldvalue", value);
                if ("161".equals(type) || "162".equals(type)) {
                    jsonObject.put("dmlurl", formfield.getFielddbtype());
                } else {
                    jsonObject.put("dmlurl", type);
                }

                jsonObject.put("fieldid", 0);
                object = HrmFieldManager.getReallyFieldvalue(jsonObject);
                // 如果是日期,校验日期的合法性
                if ("2".equals(type)) {
                    boolean isDate = GenericValidator.isDate(Util.null2String(object), "yyyy-MM-dd", true);
                    if (!isDate) {
                        rs.writeLog("日期格式校验失败，object==" + Util.null2String(object));
                        object = "";
                    }
                }
                break;
            case "5":
                // 区分单选、复选、下拉框
                switch (type) {
                    case "1":
                    case "3":
                        // 下拉框、单选框
                        object = ModeUtil.getSelectValue(formfield, value);
                        if (StringUtils.isBlank(Util.null2String(object))) {
                            if (isNumberOrCommaSeparatedNumbers(value)) {
                                object = value;
                            }
                        }
                        break;
                    case "2":
                        if (StringUtils.isNotBlank(value)) {
                            List<String> selectValues = new ArrayList<>();
                            // 兼容分隔符
                            String separator = ",";
                            if (value.contains("、")) {
                                separator = "、";
                            }
                            String[] split = value.split(separator);
                            for (String s : split) {
                                selectValues.add(ModeUtil.getSelectValue(formfield, s));
                            }
                            object = StringUtils.join(selectValues, ",");
                            if (StringUtils.isBlank(Util.null2String(object))) {
                                if (isNumberOrCommaSeparatedNumbers(value)) {
                                    object = value;
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }

                break;
            case "4":
                // CHECKBOX
            case "6":
                // FILEUPLOAD
                break;
            case "7":
                // TEXT
            case "2":
                // TEXTAREA
            default:
                object = value;
                break;
        }
        return object;
    }


    /**
     * 执行转换SQL
     *
     * @param convertSql
     * @param value
     * @return
     */
    public static String executeConvertSql(String convertSql, String value) {
        RecordSet rs = new RecordSet();
        value = Util.null2String(value);
        long count = convertSql.chars().filter(c -> c == '?').count();
        List<String> paramsList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            paramsList.add(value);
        }
        rs.executeQuery(convertSql, paramsList);
        if (rs.next()) {
            return rs.getString(1);
        }
        return "";
    }


    /**
     * 校验字符串是否为纯数字或逗号分隔的数字
     *
     * @param str
     * @return
     */
    public static boolean isNumberOrCommaSeparatedNumbers(String str) {
        // 正则表达式匹配纯数字或逗号分隔的数字
        // 允许前后有空格，数字之间用逗号分隔
        String regex = "^\\s*\\d+(\\s*,\\s*\\d+)*\\s*$";
        return str.matches(regex);
    }
}
