package nc.bs.uapbd.util;

import nc.bs.dao.BaseDAO;
import nc.bs.logging.Logger;
import nc.itf.arap.goldentax.SysParaInitQuery;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.cmp.util.StringUtils;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.pub.SqlBuilder;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 工具类
 *
 * @author mzr
 * @date 2025/7/3
 */
public class MyHelper {
    private static final BaseDAO dao = new BaseDAO();

    /**
     * 根据主键查询编码
     */
    public static String transferField(String tableName, String selectField, String pkField, String pk) throws BusinessException {
        if (StringUtils.isEmpty(pk)) {
            return null;
        }
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.append(" select " + selectField);
        sqlBuilder.append(" from " + tableName);
        sqlBuilder.append(" where ");
        sqlBuilder.append(pkField, pk);
        Object o = dao.executeQuery(sqlBuilder.toString(), new ColumnProcessor());
        if (o == null) {
            throw new BusinessException("未查询到编码信息，sql【" + sqlBuilder + "】");
        }
        return o.toString();
    }

    /**
     * 检查当前组织是否为电力电子
     */
    public static boolean checkIfDldzOrg(String code) throws BusinessException {
        String targetCode = SysParaInitQuery.getParaString("GLOBLE00000000000000", "DLDZORG");
        if (targetCode == null || nc.vo.am.common.util.StringUtils.isEmpty(targetCode)) {
            throw new BusinessException("未配置组织参数,请前往 [业务参数设置-全局] 配置DLDZORG参数");
        }
        String[] orgItem = targetCode.split(";");
        for (String orgCode : orgItem) {
            if (!orgCode.isEmpty() && orgCode.equals(code)) {
                Logger.debug("当前处理组织校验为电力电子:" + code);
                return true;
            }
        }
        return false;
    }

    /**
     * 转换特殊字段  如 1/1 转换为小数 1.0
     */

    private String transferSpecialField(String field) {
        if (field == null || field.trim().isEmpty()) {
            return null;
        }
        String[] split = field.split("/");
        if (split.length == 2) {
            String numStr = split[0].trim();
            String denStr = split[1].trim();
            if (denStr.equals("0")) {
                return "0.00"; // 分母不能为零
            }
            try {
                BigDecimal numerator = new BigDecimal(numStr);
                BigDecimal denominator = new BigDecimal(denStr);
                return numerator.divide(denominator, 2, RoundingMode.HALF_UP).toString();
            } catch (NumberFormatException e) {
                return field; // 非法数字，返回原字段
            }
        }
        return field;
    }
}
