package com.tofly.feesapi.common.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.bjgl.entity.YhCbkxx;
import com.tofly.feesapi.bmgl.entity.SysChildCode;
import com.tofly.feesapi.bmgl.service.BmYmjzConfigLsService;
import com.tofly.feesapi.bmgl.service.BmYmjzConfigService;
import com.tofly.feesapi.bmgl.service.SysChildCodeService;
import com.tofly.feesapi.common.constant.FmztEnum;
import com.tofly.feesapi.common.constant.YhztEnum;
import com.tofly.feesapi.common.core.vo.FieldDiffVO;
import com.tofly.feesapi.common.dbhelper.DbHelper;
import com.tofly.feesapi.yhgl.entity.YhKhjbxx;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ToolsUtils {
    @Autowired
    private SysChildCodeService sysChildCodeService;
    public static List<Map> convertList(ResultSet rs) throws SQLException {
        List<Map> list = new ArrayList<>();
        ResultSetMetaData md = rs.getMetaData();//获取键名
        int columnCount = md.getColumnCount();//获取列的数量
        while (rs.next()) {
            Map<String, Object> rowData = new HashMap<>();//声明Map
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnName(i), rs.getObject(i));//获取键名及值
            }
            list.add(rowData);
        }
        return list;
    }

    /**
     * 转为大写guid
     */
    public static String getGuid() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "").toUpperCase();
    }

    /**
     * 转为大写Lsbh
     */
    public static String getLsbh() {
        return DateUtils.formatDate(new Date(), "yyyyMMddHHmmssssss");
    }

    public static String getFirstLetters(String input) {
        StringBuilder result = new StringBuilder();
        for (char c : input.toCharArray()) {
            String s = PinyinUtil.getPinyin(c);
            result.append(Character.toUpperCase(s.charAt(0)));
        }
        return result.toString();
    }

    /**
     * 获取对象不同值字段,可以选择是否比较父类的字段
     */
    public static <T> List<String> compareObjects(T obj1, T obj2, boolean includeSuperClass) {
        List<String> differentFields = new ArrayList<>();

        if (obj1 == null || obj2 == null) {
            return differentFields;
        }

        Class<?> clazz = obj1.getClass();

        if (!clazz.equals(obj2.getClass())) {
            throw new IllegalArgumentException("两个对象的类型必须相同");
        }

        // 获取所有字段（包括父类）
        List<Field> allFields = new ArrayList<>();
        Class<?> currentClass = clazz;

        while (currentClass != null && (includeSuperClass || currentClass == clazz)) {
            Field[] fields = currentClass.getDeclaredFields();
            allFields.addAll(Arrays.asList(fields));
            currentClass = currentClass.getSuperclass();
        }

        for (Field field : allFields) {
            try {
                field.setAccessible(true);

                Object value1 = field.get(obj1);
                Object value2 = field.get(obj2);

                if (value1 == null && value2 == null) {
                    continue;
                }
                if (value1 == null || value2 == null) {
                    differentFields.add(field.getName());
                    continue;
                }
                if (!value1.equals(value2)) {
                    differentFields.add(field.getName());
                }
            } catch (IllegalAccessException e) {
                System.err.println("无法访问字段: " + field.getName() + ", 错误: " + e.getMessage());
            }
        }
        return differentFields;
    }

    public static List<String> getRqList(LocalDate startDate, LocalDate endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        List<String> dateList = new ArrayList<>();
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            dateList.add(date.format(formatter));
        }
        return dateList;
    }

    /**
     * 获取近12月日期集合（yyyy-MM）
     *
     * @return
     */
    public static List<String> getRqList() {
        List<String> dateList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        for (int i = 0; i < 12; i++) {
            LocalDate date = LocalDate.now().minusMonths(i);
            dateList.add(date.format(formatter));
        }

        return dateList;
    }

    /*
     *公用查询
     */
    public static String getCommSearch(List<CommSearchParams> params, String aliasName) {
        AtomicInteger index = new AtomicInteger(-1);
        if (CollectionUtil.isEmpty(params)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(" ( ");
        params.forEach(p -> {
            index.incrementAndGet();
            String strwhere = p.getKeyWord() + " " + p.getSymbol() + " " + getParamsType(p.getKeyWord(), p.getParams()) + " ";
            if (StringUtils.isEmpty(aliasName)) {
                if (StringUtils.isEmpty(p.getAliasName())) {
                    sb.append(strwhere);
                } else {
                    sb.append(p.getAliasName() + "." + strwhere);
                }
            } else {
                sb.append(aliasName + "." + strwhere);
            }

            if (index.get() != params.size() - 1) {
                sb.append(p.getUnionKey());
                sb.append(" ");
            }

        });
        sb.append(" ) ");
        return sb.toString();
    }

    /*
     *公用查询
     */
    public static String getCommSearch(List<CommSearchParams> params) {

        return getCommSearch(params, "");
    }

    /*
     *公用查询
     */
    public static String getCommSearchList(String json) throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        List<CommSearchParams> commSearchParams = mapper.readValue(json,
                mapper.getTypeFactory().constructCollectionType(List.class, CommSearchParams.class));

        return getCommSearch(commSearchParams, "");
    }

    private static String convertSymbol(String symbol) {
        return symbol.replace("<", "&lt;");
    }


    /**
     * @param keyName
     * @param params
     * @return
     */
    private static String getParamsType(String keyName, String params) {
        String retValue = "";
        switch (keyName.toLowerCase()) {
            case "cwrq":
                retValue = String.format(" to_char('%s') ", params);
                break;
            case "sfrq":
            case "jsrq":
                retValue = String.format(" to_date('%s'，'yyyy-mm-dd') ", params);
                ;
                break;
            default:
                retValue = String.format(" '%s' ", params);
                break;
        }
        return retValue;
    }

    /**
     * 获取对象中为空的字段
     *
     * @param obj
     * @return
     */
    public static String[] getnullFields(Object obj) {
        return Arrays.stream(new BeanWrapperImpl(obj).getPropertyDescriptors())
                .filter(pd -> new BeanWrapperImpl(obj).getPropertyValue(pd.getName()) == null)
                .map(PropertyDescriptor::getName)
                .toArray(String[]::new);
    }

    /**
     * 对比两个相同实体类对象的字段差异，返回指定格式的JSON字符串
     *
     * @param oldObj 原对象（修改前）
     * @param newObj 新对象（修改后）
     * @param <T>    实体类泛型
     * @return 符合格式的JSON字符串
     * @throws Exception 反射或JSON序列化异常
     */
    public <T> String compareFieldDiffToJson(T oldObj, T newObj) {
        try {

            // 1. 校验参数合法性
            if (oldObj == null && newObj == null) {
                return ""; // 两个对象都为null，返回空JSON数组
            }
            if (oldObj == null || newObj == null) {
                throw new IllegalArgumentException("原对象和新对象不能有一个为null（无法对比字段）");
            }
            if (!oldObj.getClass().equals(newObj.getClass())) {
                throw new IllegalArgumentException("两个对象不是同一个实体类，无法对比");
            }

            // 2. 初始化差异结果列表
            List<FieldDiffVO> diffVOList = new ArrayList<>();

            // 3. 通过反射获取实体类的所有字段
            Class<?> clazz = oldObj.getClass();
            Field[] fields = clazz.getDeclaredFields(); // 获取所有声明的字段（包括private）

            // 4. 遍历所有字段，对比值的差异
            for (Field field : fields) {
                // 4.1 允许访问私有字段（实体类字段通常是private）
                field.setAccessible(true);

                // 4.2 获取字段上的@FieldDesc注解（无该注解的字段忽略对比）
                FieldDesc fieldDesc = field.getAnnotation(FieldDesc.class);
                if (fieldDesc == null) {
                    continue;
                }

                // 4.3 获取两个对象该字段的值
                Object oldValue = field.get(oldObj);
                Object newValue = field.get(newObj);

                // 4.4 对比两个值是否不同（处理null值情况）
                if (isValueDifferent(oldValue, newValue)) {
                    // 4.5 封装字段说明
                    String fieldNameDesc = fieldDesc.value();
                    // 4.6 封装差异值（格式：原值修改为新值，null显示为"null"）
                    String oldValueStr = oldValue == null ? "无" : oldValue.toString();
                    String newValueStr = newValue == null ? "无" : newValue.toString();
                    String fieldName = field.getName();
                    //用户档案的字段值处理
                    if (oldObj.getClass().equals(YhKhjbxx.class)) {
                        if (fieldName.equals("xb")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = xbstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = xbstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("zjlb")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("10", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("10", newValueStr);
                            }
                        }
                        if (fieldName.equals("xydj")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("20", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("20", newValueStr);
                            }
                        }
                        if (fieldName.equals("tkhbz")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = sfstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = sfstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("fplx")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = fplxstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = fplxstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("khlb")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("24", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("24", newValueStr);
                            }
                        }
                        if (fieldName.equals("pushmode")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("25", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("25", newValueStr);
                            }
                        }
                        if (fieldName.equals("sfkp")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = sfstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = sfstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("sfms")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = sfstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = sfstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("sfqz")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = sfstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = sfstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("yhzt")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = YhztEnum.valueOf(oldValueStr).getDesc();
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = YhztEnum.valueOf(newValueStr).getDesc();
                            }
                        }
                        if (fieldName.equals("fffs")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select name from bm_fffs where code='%s'", oldValueStr), "name");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select name from bm_fffs where code='%s'", newValueStr), "name");
                            }
                        }
                        if (fieldName.equals("khlx")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("44", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("44", newValueStr);
                            }
                        }
                        if (fieldName.equals("zsjb")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("11", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("11", newValueStr);
                            }
                        }
                        if (fieldName.equals("htqd")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("39", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("39", newValueStr);
                            }
                        }
                        if (fieldName.equals("sscbpq")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select cbpqmc from bm_cbpq where cbpqbm='%s'", oldValueStr), "cbpqmc");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select cbpqmc from bm_cbpq where cbpqbm='%s'", newValueStr), "cbpqmc");
                            }
                        }
                        if (fieldName.equals("sscbb")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select cbbmc from bm_cbb where cbbbm='%s'", oldValueStr), "cbbmc");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select cbbmc from bm_cbb where cbbbm='%s'", newValueStr), "cbbmc");
                            }
                        }
                        if (field.getType().equals(Date.class)) {
                            if (!oldValueStr.equals("无")) {
                                LocalDateTime dateTime = ((Date) oldValue).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                                oldValueStr= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
                            }
                            if (!newValueStr.equals("无")) {
                                LocalDateTime dateTime = ((Date) newValue).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                                newValueStr= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
                            }
                        }
                    }
                    //水表档案的字段值处理
                    if (oldObj.getClass().equals(YhCbkxx.class)) {
                        if (fieldName.equals("sblb")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select name from bm_sblb where code='%s'", oldValueStr), "name");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select name from bm_sblb where code='%s'", newValueStr), "name");
                            }
                        }
                        if (fieldName.equals("sbsccj")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select name from bm_sbsccj where code='%s'", oldValueStr), "name");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select name from bm_sbsccj where code='%s'", newValueStr), "name");
                            }
                        }
                        if (fieldName.equals("sbxh")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select name from bm_sbxh where code='%s'", oldValueStr), "name");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select name from bm_sbxh where code='%s'", newValueStr), "name");
                            }
                        }
                        if (fieldName.equals("sbkj")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("12", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("12", newValueStr);
                            }
                        }
                        if (fieldName.equals("sblc")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("13", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("13", newValueStr);
                            }
                        }
                        if (fieldName.equals("bjwz")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("15", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("15", newValueStr);
                            }
                        }
                        if (fieldName.equals("jddj")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("14", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("14", newValueStr);
                            }
                        }
                        if (fieldName.equals("cbpl")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select name from bm_cbpl where code='%s'", oldValueStr), "name");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select name from bm_cbpl where code='%s'", newValueStr), "name");
                            }
                        }
                        if (fieldName.equals("ybdjbz")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = sfstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = sfstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("sjbm")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select name from bm_sj where code='%s'", oldValueStr), "name");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select name from bm_sj where code='%s'", newValueStr), "name");
                            }
                        }
                        if (fieldName.equals("sjbm1")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmbstr(String.format("select name from bm_sj where code='%s'", oldValueStr), "name");
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmbstr(String.format("select name from bm_sj where code='%s'", newValueStr), "name");
                            }
                        }
                        if (fieldName.equals("wsfbz")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = sfsqstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = sfsqstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("jfzt")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = jfztstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = jfztstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("ljffs")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = ljffsstr(oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = ljffsstr(newValueStr);
                            }
                        }
                        if (fieldName.equals("fmzt")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = FmztEnum.valueOf(oldValueStr).getDesc();
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = FmztEnum.valueOf(newValueStr).getDesc();
                            }
                        }
                        if (fieldName.equals("sbyt")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("32", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("32", newValueStr);
                            }
                        }
                        if (fieldName.equals("sbazfs")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("33", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("33", newValueStr);
                            }
                        }
                        if (fieldName.equals("sbzt")) {
                            if (!oldValueStr.equals("无")) {
                                oldValueStr = bmstr("34", oldValueStr);
                            }
                            if (!newValueStr.equals("无")) {
                                newValueStr = bmstr("34", newValueStr);
                            }
                        }
                        if (field.getType().equals(Date.class)) {
                            if (!oldValueStr.equals("无")) {
                                LocalDateTime dateTime = ((Date) oldValue).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                                oldValueStr= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
                            }
                            if (!newValueStr.equals("无")) {
                                LocalDateTime dateTime = ((Date) newValue).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                                newValueStr= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dateTime);
                            }
                        }
                    }
                    String diffValue = oldValueStr + "修改为" + newValueStr;
                    // 4.7 添加到差异结果列表
                    diffVOList.add(new FieldDiffVO(fieldNameDesc, diffValue));
                }
            }
            // 5. 将差异结果列表转换为指定格式的JSON字符串
            if (diffVOList.isEmpty()) {
                return "";
            }
            return JSONObject.toJSONString(diffVOList);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }

    /**
     * 辅助方法：判断两个值是否不同（处理null值）
     *
     * @param oldValue 原值
     * @param newValue 新值
     * @return true=不同，false=相同
     */
    private static boolean isValueDifferent(Object oldValue, Object newValue) {
        if (oldValue == null && newValue == null) {
            // 两个都为null，视为相同
            return false;
        }
        if (oldValue == null || newValue == null) {
            // 一个为null，一个不为null，视为不同
            return true;
        }
        // 两个都不为null，调用equals方法对比（基本类型包装类、String都重写了equals）
        return !oldValue.equals(newValue);
    }
    /**
     * 辅助方法：处理性别字段
     *
     * @param xb 性别字段值
     * @return 处理后的性别字段值
     */
    private static String xbstr(String xb) {
        switch (xb) {
            case "1":
                xb = "男";
                break;
            case "2":
                xb = "女";
                break;
            default:
                xb = "未知";
                break;
        }
        return xb;
    }

    /**
     * 辅助方法：处理编码字段
     *
     * @param zjlb
     * @return 处理后的编码字段值
     */
    private String bmstr(String pcid, String zjlb) {
        SysChildCode sysChildCode = sysChildCodeService.get(pcid, zjlb);
        return sysChildCode == null ? "未知" : sysChildCode.getCcname();
    }

    /**
     * 辅助方法：处理是否字段
     *
     * @param sf
     * @return 处理后的是否字段值
     */
    private static String sfstr(String sf) {
        switch (sf) {
            case "1":
                sf = "是";
                break;
            case "0":
                sf = "否";
                break;
            default:
                sf = "未知";
                break;
        }
        return sf;
    }

    /**
     * 辅助方法：处理是否收取字段
     *
     * @param sf
     * @return 处理后 Whether字段值
     */
    private static String sfsqstr(String sf) {
        switch (sf) {
            case "1":
                sf = "收取";
                break;
            case "0":
                sf = "不收";
                break;
            default:
                sf = "未知";
                break;
        }
        return sf;
    }

    private static String jfztstr(String jfzt) {
        switch (jfzt) {
            case "1":
                jfzt = "正常";
                break;
            case "2":
                jfzt = "停用";
                break;
            default:
                jfzt = "未知";
                break;
        }
        return jfzt;
    }

    private static String ljffsstr(String ljffs) {
        switch (ljffs) {
            case "0":
                ljffs = "按户收取";
                break;
            case "1":
                ljffs = "按用量收取";
                break;
            default:
                ljffs = "未知";
        }
        return ljffs;
    }

    /**
     * 辅助方法：处理发票类型字段
     *
     * @param fplx
     * @return 处理后的发票类型字段值
     */
    private static String fplxstr(String fplx) {
        switch (fplx) {
            case "1":
                fplx = "普票";
                break;
            case "2":
                fplx = "专票";
                break;
            default:
                fplx = "未知";
                break;
        }
        return fplx;
    }

    /**
     * 辅助方法：处理编码表字段查询
     *
     * @param sqlstr 查询sql
     * @param name   返回字段
     * @return 处理后的字段值
     */
    private String bmbstr(String sqlstr, String name) throws Exception {
//        String returnstr = "";
//        try (SqlSession sqlSession = sqlSessionFactory.openSession(true);  // true：自动提交事务
//             Connection conn = sqlSession.getConnection();
//             // SQL模板用?作为占位符
//             PreparedStatement pstmt = conn.prepareStatement(sqlstr)) {
//            ResultSet rs = pstmt.executeQuery();
//            if (rs.next()) {
//                Object value = rs.getObject(name);
//                returnstr = value != null ? value.toString() : "";
//            }
//            //conn.close();
//            //rs.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "";
//        }
//        return returnstr;
        String returnstr = DbHelper.getDbHelper().getValue(sqlstr);
        if (StringUtil.isEmpty(returnstr)) {
            returnstr = "";
        }
        return returnstr;
    }
}
