package org.example.Entity.Control.Fields;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.example.Entity.Control.Fields.Field;
import org.example.Entity.Control.Container.Column;
import org.example.Enums.SystemTypeEnums;
import org.example.Utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.example.Utils.DataTableUtil.get;

/**
 * ==============================================================================
 * 功能描述：ComboBox
 * ==============================================================================
 */

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ComboBox extends Field {

    public static final Pattern RECORD_PATTERN_1 = Pattern.compile("#([^#])+#");
    public static final Pattern RECORD_PATTERN_2 = Pattern.compile("\\{([^{])+}");


    public ComboBox(Map<String, Object> row) {
        super(row);
        this.defaultXtype = "combobox";
    }

    public ComboBox(Map<String, Object> row, IPublicUtil util) {
        this(row);
        this.setUtil(util);
    }

    /**
     * 联动，触发该控件刷新的上级控件名称
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public String[] getLinkParentNames() {
        if (!isIsPostRecord()) {
            return null;
        }
        String[] names = PublicUtil.getParamValue(getDataSource())
                .stream()
                .map(str -> str.replaceAll("[{}]", "").toLowerCase())
                .toArray(String[]::new);
        if (names.length == 0) {
            return null;
        }
        return names;
    }

    /**
     * 是否是带参数的下拉框
     */
    @JsonIgnore
    public boolean parmbox;

    /**
     * 是否可输入
     */
    public boolean editable;

    /**
     * 是否可以多选
     */
    public boolean multiSelect;

    /**
     * 查询的参数名
     */
    public String queryParam;

    /**
     * 查询时，是否需要把自身的recordpost到服务器
     */
    public boolean isIsPostRecord() {
        String dataSource = getDataSource();
        if (dataSource == null || dataSource.isEmpty()) {
            return false;
        }
        Matcher matcher1 = RECORD_PATTERN_1.matcher(dataSource);
        Matcher matcher2 = RECORD_PATTERN_2.matcher(dataSource);
        return matcher1.find() || matcher2.find();
    }

    public String emptyText;

    private boolean autoSelect = true;

    public boolean isAutoSelect() {
        return autoSelect;
    }

    public void setAutoSelect(boolean autoSelect) {
        this.autoSelect = autoSelect;
    }

    /**
     * 其他字段 格式:字段|显示名称,字段2|显示名称
     */
    private List<Column> _otherMember;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    public List<Column> getColumns() {
        if (_otherMember == null) {
            List<Column> list = new ArrayList<>();
            String omembers = (String) get(_row, "OtherMember", null);

            // 处理OtherMember配置的列
            if (omembers != null && !omembers.trim().isEmpty()) {
                String[] ms = omembers.split(",");
                for (String m : ms) {
                    if (m == null || m.trim().isEmpty()) {
                        continue;
                    }
                    String[] kv = (m + "|").split("\\|");
                    Column column = new Column();
                    column.text = kv.length > 1 ? kv[1].trim() : ""; // 处理没有|分隔的情况
                    column.dataIndex = kv[0].trim();
                    column.setWidth(1);
                    list.add(column);
                }
                if (!list.isEmpty()) {
                    _otherMember = list;
                } else {
                    return null; // 对应C#的 list.Count == 0 逻辑
                }
            }
            // 处理数据源SQL获取的列
            else if (getDataSource() != null && !getDataSource().isEmpty() && !isReadOnly()) {
                String sql = getDataSource();
                List<Map<String, Object>> tbVal = null;
                Set<String> columnNames = new HashSet<>();

                try {
                    // 处理SQL：移除#符号并添加and 1!=1条件
                    String processedSql = sql.replace("#", "");
                    SqlAnalyzer sqlAnalyzer = new SqlAnalyzer(processedSql);
                    Map<String, String> paramMap = new HashMap<>();
                    paramMap.put("a", "and 1!=1");
                    sql = sqlAnalyzer.InsertWhere(paramMap, false, false, false);

                    // 执行查询并收集列名（通过ResultSetMetaData）
                    this.getDbOperator().query(
                            PublicUtil.ReqSqlPmsByRow(null, null, sql, SystemTypeEnums.PmType.sql),
                            new ResultSetExtractor<Void>() {
                                @Override
                                public Void extractData(ResultSet rs) throws SQLException, DataAccessException {
                                    // 无论是否有行数据，先获取元数据
                                    ResultSetMetaData metaData = rs.getMetaData();
                                    int columnCount = metaData.getColumnCount();
                                    for (int i = 1; i <= columnCount; i++) {
                                        columnNames.add(metaData.getColumnName(i));
                                    }
                                    // 如需处理行数据，再循环 rs.next()
                                    return null;
                                }
                            }
                    );
                } catch (Exception e) {
//                    err.printf("解析下拉框列时执行sql错误：SQL=%s, 错误信息=%s%n", sql, e.getMessage());
                }

                // 处理列过滤和转换
                if (!columnNames.isEmpty()) {
                    List<Column> otherMemberList = new ArrayList<>();
                    String valueMember = DataTableUtil.getStringValue(_row, "ValueMember", "");
                    String displayField = getDisplayField();
                    String valueField = getValueField();
                    String xtype = getXtype() != null ? getXtype().toLowerCase() : "";
                    for (String colName : columnNames) {
                        // 过滤条件：wincombobox类型或非特殊列，且列名不以_开头
                        boolean isWinComboBox = "wincombobox".equals(xtype);
                        boolean isNotSpecialColumn = !colName.equals(displayField)
                                && !colName.equals(valueField)
                                && !colName.equals(valueMember);
                        boolean condition = (isWinComboBox || isNotSpecialColumn)
                                && !colName.startsWith("_");

                        if (condition) {
                            Column column = new Column();
                            // 设置列文本（对应C#的三元表达式逻辑）
                            if ("dm".equals(colName)) {
                                column.text = "编码";
                            } else if ("mc".equals(colName)) {
                                column.text = "名称";
                            } else if ("remark".equals(colName)) {
                                column.text = "备注";
                            } else {
                                column.text = colName;
                            }
                            // 设置数据索引和宽度
                            column.dataIndex = colName;
                            column.setWidth(getColumnWidth(colName));

                            otherMemberList.add(column);
                        }
                    }

                    // 空列集合处理
                    if (otherMemberList.isEmpty()) {
                        _otherMember = null;
                    } else {
                        _otherMember = otherMemberList;
                    }

                    // 单列或可编辑状态下添加显示列和值列
                    if ((_otherMember != null && _otherMember.size() == 1) || this.editable) {
                        if (_otherMember == null) {
                            _otherMember = new ArrayList<>();
                        }
                        // 添加显示列（名称）
                        if (displayField != null && !displayField.startsWith("_")) {
                            Column displayColumn = new Column();
                            displayColumn.text = "名称";
                            displayColumn.dataIndex = displayField;
                            displayColumn.setWidth(1);
                            _otherMember.add(0, displayColumn);
                        }
                        // 添加值列（编号）
                        if (displayField != null && valueField != null
                                && !displayField.equals(valueField)
                                && !valueField.startsWith("_")) {
                            Column valueColumn = new Column();
                            valueColumn.text = "编号";
                            valueColumn.dataIndex = valueField;
                            valueColumn.setWidth(1);
                            _otherMember.add(0, valueColumn);
                        }
                    }
                }
            }
        }
        return _otherMember;
    }

    public void setColumns(List<Column> columns) {
        this._otherMember = columns;
    }

    public String getColumnText(String colName) {
        switch (colName) {
            case "dm":
                return "编码";
            case "mc":
                return "名称";
            case "remark":
                return "备注";
            default:
                return colName;
        }
    }

    private int getColumnWidth(String colName) {
        if ("dm".equals(colName) || "编码".equals(colName)) {
            return 1;
        } else if ("mc".equals(colName) || "名称".equals(colName)
                || "remark".equals(colName) || "备注".equals(colName)) {
            return 2;
        } else {
            return 2;
        }
    }

    /**
     * 下拉框的类型
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public String pickxtype;

    /**
     * 下拉框的类型
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public Object pickerCfg;

    /**
     * 是否在获取值的时候，获取匹配的下拉值
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public Boolean MValue;

    @JsonIgnore
    public boolean isDoNotSpelling() {
        return NativeExtensionUtils.toBoolean(DataTableUtil.getIntValue(_row, "donotspelling", 0));
    }
}