package com.seeyon.apps.src_hxinvoice.node;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.common.plugin.vo.ConfigVo;
import com.seeyon.apps.common.workflow.constants.WorkFlowType;
import com.seeyon.apps.common.workflow.node.ACommonSuperNode;
import com.seeyon.apps.ext.workflow.vo.FormDataVo;
import com.seeyon.apps.ext.workflow.vo.SuperNodeContext;
import com.seeyon.apps.src_hxinvoice.constants.HxinvoiceConstants;
import com.seeyon.apps.src_hxinvoice.dao.IHxinvoiceDao;
import com.seeyon.apps.src_hxinvoice.dao.impl.HxinvoiceDaoImpl;
import com.seeyon.apps.src_hxinvoice.util.FileUtil;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.SystemEnvironment;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

public class FileDataValidateNode extends ACommonSuperNode {

    private static Log log = Log.get(FileDataValidateNode.class);

    // 定义常量：保留小数位数（金额计算建议6位，最终展示2位）
    final int CALC_SCALE = 6;
    final int SHOW_SCALE = 2;

    protected ICstConfigApi cstConfigApi = (ICstConfigApi) AppContext.getBean("cstConfigApi");

    @Override
    public String getPluginId() {
        return HxinvoiceConstants.getPluginId();
    }

    @Override
    public String getFormParse() {
        return "json";
    }

    @Override
    public WorkFlowType[] getTypes() {
        return new WorkFlowType[0];
    }

    @Override
    public SuperNodeContext proceed(String request, FormDataVo formDataVo, FormDataMasterBean formDataMasterBean) throws Exception {
        SuperNodeContext context = new SuperNodeContext();

        ConfigVo configVo = cstConfigApi.getConfig(getPluginId());
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);    // 保留2位
        nf.setRoundingMode(RoundingMode.HALF_UP); // 四舍五入
        nf.setGroupingUsed(false);
        context.setRequest(request);
        context.setNeedSave(true);

        System.out.println("进行附件处理");
        FileUtil fileUtil = new FileUtil();
        IHxinvoiceDao hxinvoiceDao = new HxinvoiceDaoImpl();
//        参数转JSON
        JSONObject jsonObject = JSONObject.parseObject(request);
//        获取参数名称
        String DDZXXName = jsonObject.getString("DDZXX");
        System.out.println("获取参数附件ID"+DDZXXName);
//        根据参数名称获取附件控件对象
//        设置附件下载路径
        String path = SystemEnvironment.getApplicationFolder()+"/hxinvoiceFile/"+DDZXXName+"/";
        System.out.println("文件下载路径"+path);
//        Thread.sleep(3000);
//        将附件下载到服务器
        List<String> filePaths = fileUtil.fieldFileDownload(Long.parseLong(DDZXXName),path);
//        创建DDZXX对象
        JSONArray DDZXXS = new JSONArray();

//      税率判断 & 金额计算逻辑
        String taxRes = "";
//      初始化所有金额为 BigDecimal.ZERO，避免空指针
        BigDecimal zje = BigDecimal.ZERO;
        BigDecimal sj = BigDecimal.ZERO;
        BigDecimal bhsje = BigDecimal.ZERO;
        for(String filePath : filePaths){
            JSONArray jsonArray = fileUtil.getFileContent(filePath);
            context.setResponse(jsonArray.toString());
            log.info("处理文件：{}，文件内容长度：{}", filePath, jsonArray.size());
//          System.out.println("获取附件内容"+jsonArray);
            for(int i = 0 ; i < jsonArray.size();i++){
                JSONObject fileJson = jsonArray.getJSONObject(i);
                JSONArray SPS = fileJson.getJSONArray("SPS");
                log.info("当前批次开票文件行数：{}", SPS.size());
                for (int n = 0 ; n < SPS.size() ; n++){
                    JSONObject SP = SPS.getJSONObject(n);
                    String SL = SP.getString("SL");
//                  获取当前金额
                    String JE = SP.getString("JE");
                    // 1. 解析金额 JE（处理千分位、异常兜底）
                    BigDecimal jeBig;
                    try {
                        NumberFormat format = NumberFormat.getInstance(Locale.US);
                        Number number = format.parse(JE);
                        jeBig = new BigDecimal(number.toString()).setScale(2, RoundingMode.HALF_UP);
                    } catch (ParseException e) {
                        String errorMsg = "第" + (i+1) + "批次第" + (n+1) + "行金额解析失败：" + JE;
                        log.error(errorMsg, e);
                        context.back("金额填写异常，行号：" + (n+1) + "，请检查金额字段是否为数字格式");
                        return context;
                    }
                    // 2. 累加总金额 zje
                    zje = zje.add(jeBig);
                    // 3. 解析税率 SL 并计算不含税金额 bhsje = JE/(1+SL)
                    BigDecimal slBig;
                    try {
                        slBig = new BigDecimal(SL);
                    } catch (NumberFormatException e) {
                        String errorMsg = "第" + (i+1) + "批次第" + (n+1) + "行税率解析失败：" + SL;
                        log.error(errorMsg, e);
                        context.back("税率填写异常，行号：" + (n+1) + "，请检查税率字段是否为数字格式");
                        return context;
                    }
                    // 计算 1+税率，避免分母为0
                    BigDecimal denominator = BigDecimal.ONE.add(slBig);
                    if (denominator.compareTo(BigDecimal.ZERO) == 0) {
                        String errorMsg = "第" + (i+1) + "批次第" + (n+1) + "行税率异常（1+税率=0）：" + SL;
                        log.error(errorMsg);
                        context.back("税率异常，行号：" + (n+1) + "，税率不能为-1");
                        return context ;
                    }

                    // 计算不含税金额：JE/(1+SL)，指定精度和四舍五入
                    BigDecimal currentBhsje = jeBig.divide(denominator, CALC_SCALE, RoundingMode.HALF_UP);
                    bhsje = bhsje.add(currentBhsje);

                    // 4. 计算税金：JE - 不含税金额 （等价于 不含税金额*税率，更精准）
                    BigDecimal currentSj = jeBig.subtract(currentBhsje);
                    sj = sj.add(currentSj);

//                    bhsje = bhsje + (Double.parseDouble(JE)/(1+Double.parseDouble(SL)));
//                    sj = sj+(Double.parseDouble(JE)*Double.parseDouble(SL));
                }
            }
        }
        // 最终结果保留2位小数（符合财务展示规范）
        BigDecimal finalZje = zje.setScale(SHOW_SCALE, RoundingMode.HALF_UP);
        BigDecimal finalBhsje = bhsje.setScale(SHOW_SCALE, RoundingMode.HALF_UP);
        BigDecimal finalSj = sj.setScale(SHOW_SCALE, RoundingMode.HALF_UP);

//        if(taxRes.length()==0){
// 填充结果到表单
        formDataVo.getNewFieldDataMap().put("总金额合计", nf.format(finalZje));
        formDataVo.getNewFieldDataMap().put("税金合计", nf.format(finalSj));
        formDataVo.getNewFieldDataMap().put("不含税金额合计", nf.format(finalBhsje));
        context.success("成功", false);
//        }else{
//            taxRes = taxRes.substring(0,taxRes.length()-1)+"请重新填写";
//            context.back("开票清单校验失败："+ taxRes);
//            context.setErrMsg(taxRes);
//        }
//        总金额=金额累计和
//        税金 = （金额*税率）累计和
//                不含税金额 = 总金额 - 税金
//        System.out.println("总金额"+nf.format(zje));
//        System.out.println("税金"+nf.format(sj));
//        System.out.println("不含税金额"+nf.format(zje-sj));
        return context;
    }

    @Override
    public String getNodeId() {
        return "FileDataValidateNode";
    }

    @Override
    public String getNodeName() {
        return "批量数电发票开票附件校验超级节点";
    }
}
