//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package nc.bs.pub.action;

import java.math.BigDecimal;
import java.util.Hashtable;
import nc.bs.arap.actions.N_BASE_ACTION;
import nc.bs.arap.paybp.PayBillBO;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.vo.arap.pay.AggPayBillVO;
import nc.vo.arap.pub.ArapConstant;
import nc.vo.arap.pub.BillEnumCollection.ApproveStatus;
import nc.vo.fipub.exception.ExceptionHandler;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.compiler.PfParameterVO;
import nc.vo.pub.lang.UFDouble;
import nccloud.bs.arap.util.commit.ArapCommitUtil;
import nccloud.pubitf.arap.arappub.IArapBillPubUtilService;

public class N_F3_SAVE extends N_BASE_ACTION {
    private Hashtable<String, Object> m_keyHas;

    public N_F3_SAVE() {
        new Hashtable();
    }

    private boolean hasBill(String primaryKey) throws BusinessException {
        boolean hasBill = false;
        if (primaryKey != null) {
            AggPayBillVO[] bvos = null;

            try {
                PayBillBO payableBO = new PayBillBO();
                bvos = payableBO.findBillByPrimaryKey(new String[]{primaryKey});
            } catch (Exception e) {
                Logger.error(e.getMessage(), e);
            }

            if (bvos != null && bvos.length != 0 && bvos[0] != null) {
                hasBill = true;
            }
        }

        return hasBill;
    }

    public Object runComClass(PfParameterVO paraVo) throws BusinessException {
        try {
            if (paraVo.m_preValueVos == null) {
                return null;
            } else {
                Object obj = null;
                super.m_tmpVo = paraVo;
                if (paraVo.isCloudEntry) {
                    String actionCode = ArapConstant.SAVE;
                    ((IArapBillPubUtilService)NCLocator.getInstance().lookup(IArapBillPubUtilService.class)).interceptorVaildator(paraVo.m_preValueVos, actionCode);
                }

                this.setParameter("context", paraVo.m_preValueVos);
                this.beforeCheck();
                String primaryKey = paraVo.m_preValueVos[0].getParentVO().getPrimaryKey();
                 paraVo = this.def10Change(paraVo);
                if (this.hasBill(primaryKey)) {
                    obj = this.runClass("nc.bs.arap.actions.PaybillEditSaveBatchBSAction", "updateVOs", "&context:nc.vo.pub.AggregatedValueObject[]", paraVo, this.m_keyHas);
                } else {
                    paraVo = this.approveStatusChange(paraVo);
                    obj = this.runClass("nc.bs.arap.actions.PaybillSaveBatchBSAction", "insertVOs", "&context:nc.vo.pub.AggregatedValueObject[]", paraVo, this.m_keyHas);
                }

                this.afterCheck();
                obj = (new ArapCommitUtil()).autoCommit(obj);
                return obj;
            }
        } catch (Exception exception) {
            throw ExceptionHandler.handleException(this.getClass(), exception);
        }
    }

    protected void setParameter(String key, Object val) {
        if (this.m_keyHas == null) {
            this.m_keyHas = new Hashtable();
        }

        if (val != null) {
            this.m_keyHas.put(key, val);
        }

    }

    public String getCodeRemark() {
        return " arap action script not allowed to modify ,all rights reserved!";
    }

    private PfParameterVO approveStatusChange(PfParameterVO paraVo) {
        for(AggregatedValueObject vo : paraVo.m_preValueVos) {
            vo.getParentVO().setAttributeValue("approvestatus", ApproveStatus.NOSTATE.VALUE);
        }

        return paraVo;
    }

    private PfParameterVO def10Change(PfParameterVO paraVo) {
        for(AggregatedValueObject vo : paraVo.m_preValueVos) {
            UFDouble money_de = UFDouble.ZERO_DBL;
            for(CircularlyAccessibleValueObject childVO : vo.getChildrenVO()) {
                money_de =money_de.add((UFDouble) childVO.getAttributeValue("money_de"))  ;
            }
            vo.getParentVO().setAttributeValue("def10",toChineseAmount(money_de.toBigDecimal()));
        }

        return paraVo;
    }
    // 数字大写汉字映射表
    private static final String[] CHINESE_CHARS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    // 数位映射表
    private static final String[] DIGIT_UNITS = {"", "拾", "佰", "仟"};
    // 数映射表
    private static final String[] LARGE_NUMBERS = {"", "万", "亿", "万亿", "亿亿"};
    // 金额单位
    private static final String[] AMOUNT_UNITS = {"元", "角", "分"};
    // 特殊情况处理
    private static final String ZERO_YUAN = "零元整";

    public static String toChineseAmount(BigDecimal number) {
        boolean isNegative = number.compareTo(BigDecimal.ZERO) < 0;
        if (isNegative) {
            number = number.abs(); // 转为正数
        }

        // 将数字分为整数部分和小数部分
        String numStr = number.stripTrailingZeros().toPlainString();
        String[] parts = numStr.split("\\.");
        String integerPart = parts[0];
        String decimalPart = parts.length > 1 ? parts[1] : "";

        // 处理整数部分
        StringBuilder chineseInteger = new StringBuilder();
        if ("0".equals(integerPart)) {
            chineseInteger.append(CHINESE_CHARS[0]);
        } else {
            char[] intChars = integerPart.toCharArray();
            int len = intChars.length;
            int zeroCount = 0; // 记录连续的零的个数

            for (int i = 0; i < len; i++) {
                int digit = intChars[i] - '0';
                int digitPosition = len - i - 1;
                int section = digitPosition / 4;
                int positionInSection = digitPosition % 4;

                if (digit != 0) {
                    // 如果前面有连续的零，添加一个零
                    if (zeroCount > 0) {
                        chineseInteger.append(CHINESE_CHARS[0]);
                        zeroCount = 0;
                    }

                    chineseInteger.append(CHINESE_CHARS[digit]);
                    if (positionInSection > 0) {
                        chineseInteger.append(DIGIT_UNITS[positionInSection]);
                    }

                    // 每四位添加一个大数单位
                    if (positionInSection == 0) {
                        chineseInteger.append(LARGE_NUMBERS[section]);
                    }
                } else {
                    zeroCount++;

                    // 每四位的末尾，即使是零也要添加大数单位
                    if (positionInSection == 0 && zeroCount < 4) {
                        chineseInteger.append(LARGE_NUMBERS[section]);
                    }
                }

                // 每四位的末尾重置零计数
                if (positionInSection == 0) {
                    zeroCount = 0;
                }
            }
            // 移除多余的零和重复的单位
            cleanUpChineseNumber(chineseInteger);
        }

        // 处理小数部分
        StringBuilder chineseDecimal = new StringBuilder();
        int jiao = 0;
        int fen = 0;
        if (!decimalPart.isEmpty()) {
            if (decimalPart.length() >= 1) {
                jiao = Integer.parseInt(decimalPart.substring(0, 1));
            }
            if (decimalPart.length() >= 2) {
                fen = Integer.parseInt(decimalPart.substring(1, 2));
            }
            if (jiao != 0) {
                chineseDecimal.append(CHINESE_CHARS[jiao]).append(AMOUNT_UNITS[1]);
            }
            // 如果分不为0，才输出分部分
            if (fen != 0) {
                chineseDecimal.append(CHINESE_CHARS[fen]).append(AMOUNT_UNITS[2]);
            }
        }

        // 整合整数部分和小数部分
        if (chineseInteger.length() == 0) {
            chineseInteger.append(CHINESE_CHARS[0]);
        }
        chineseInteger.append(AMOUNT_UNITS[0]);
        if (jiao == 0 && fen == 0) {
            chineseInteger.append("整");
        } else {
            if (fen == 0 && jiao != 0) {
                chineseInteger.append(chineseDecimal).append("整");
            } else {
                chineseInteger.append(chineseDecimal);
            }
        }

        // 特殊情况处理：零元整
        if (chineseInteger.toString().equals("零元")) {
            return ZERO_YUAN;
        }

        // 添加负号（如果需要）
        if (isNegative) {
            return "负" + chineseInteger.toString();
        }

        return chineseInteger.toString();
    }

    private static void cleanUpChineseNumber(StringBuilder sb) {
        // 移除连续的零，只保留一个零
        while (sb.indexOf("零零") != -1) {
            sb.replace(sb.indexOf("零零"), sb.indexOf("零零") + 2, "零");
        }
        // 移除末尾的零
        if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '零') {
            sb.deleteCharAt(sb.length() - 1);
        }
        // 移除单位前面的零
        for (String unit : DIGIT_UNITS) {
            if (!unit.isEmpty()) {
                while (sb.indexOf("零" + unit) != -1) {
                    sb.replace(sb.indexOf("零" + unit), sb.indexOf("零" + unit) + 2, unit);
                }
            }
        }
        // 移除大数单位前面的零
        for (String largeNum : LARGE_NUMBERS) {
            if (!largeNum.isEmpty()) {
                while (sb.indexOf("零" + largeNum) != -1) {
                    sb.replace(sb.indexOf("零" + largeNum), sb.indexOf("零" + largeNum) + 2, largeNum);
                }
            }
        }
        // 移除连续的大数单位
        for (String largeNum : LARGE_NUMBERS) {
            if (!largeNum.isEmpty()) {
                while (sb.indexOf(largeNum + largeNum) != -1) {
                    sb.replace(sb.indexOf(largeNum + largeNum), sb.indexOf(largeNum + largeNum) + largeNum.length() * 2, largeNum);
                }
            }
        }
    }


}
