package nckd.jimin.jyyy.fi.webapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import fi.er.webService.BankSynReturnModel;
import kd.bos.config.client.util.StringUtils;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.DB;
import kd.bos.ext.fi.plugin.ArApConvert.util.EmptyUtils;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.login.utils.DateUtils;
import kd.bos.openapi.common.custom.annotation.ApiController;
import kd.bos.openapi.common.custom.annotation.ApiMapping;
import kd.bos.openapi.common.custom.annotation.ApiParam;
import kd.bos.openapi.common.custom.annotation.ApiPostMapping;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.data.rsa.helper.CodeRuleHelper;
import kd.fi.cas.helper.CasBotpHelper;
import nckd.jimin.jyyy.fi.common.NstcApiReturnModel;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 交易明细API插件类
 * 用于处理交易明细相关的操作，如保存交易明细信息。
 *
 * @author turborao
 * @date 2025/05/24
 */
@ApiController(value = "nstc", desc = "对接九恒星交易明细")
@ApiMapping("/nstc")
public class TransDetailApiPlugin implements Serializable {

    private static final Log log = LogFactory.getLog(TransDetailApiPlugin.class);

    /**
     * 保存交易明细
     *
     * @param operation 操作类型
     * @param jsondata  交易明细数据
     * @return 处理结果
     */
    @ApiPostMapping(value = "/transdetail", desc = "操作九恒星交易明细")
    public CustomApiResult<JSONObject> oprationTransDetail(
            @ApiParam(value = "操作类型") String operation,
            @ApiParam(value = "交易明细数据", required = true) String jsondata
    ) {
        log.info("九恒星-收到保存交易明细请求:\r\n操作类型:{}\r\n交易明细数据:{}",
                operation,
                jsondata
        );

        NstcApiReturnModel returnModel = new NstcApiReturnModel();

        // 解析JSON数据
        JSONObject jsonObject = JSON.parseObject(jsondata);
        // 交易流水号ID  关键字
        String number = jsonObject.getString("number");
        String code = "";
        String msg = "";

        //JSONArray jsonArray =JSONArray.parseArray(jsondata);
        if(jsondata.startsWith("[")){
            log.error("九恒星-保存交易明细失败。操作类型:{}，交易明细数据:{}，错误信息:{}", operation, jsondata, "只允许接收1条数据，请重新传输！");
            returnModel.setNumber(number);
            returnModel.setCode("500");
            returnModel.setMessage("九恒星-操作交易明细失败: 只允许接收1条数据，请重新传输！");

            JSONArray dataArray = new JSONArray();
            dataArray.add(JSONObject.parseObject(returnModel.toString()));

            return returnResult("200","S","九恒星-接口调用成功，具体信息查看responseData参数", dataArray);
        }

        //如果未传operation参数，则默认为sava保存
        if(StringUtils.isEmpty(operation)){
            operation = "save";
        }

        try {
            // 根据操作类型处理不同的逻辑
            switch (operation) {
                case "save":
                    // 添加交易明细逻辑
                    String errMsg = saveTransDetail(jsondata);

                    if (!EmptyUtils.isEmpty(errMsg)) {
                        log.error("九恒星-交易明细添加失败。操作类型:{}，交易明细数据:{}，错误信息:{}", operation, jsondata, "交易明细添加失败" + errMsg);

                        code = "500";
                        msg = "交易明细添加失败，" + errMsg;
                    } else {
                        log.info("九恒星-交易明细添加成功。操作类型:{}，交易明细数据:{}", operation, jsondata);

                        code = "200";
                        msg = "交易明细添加成功";
                    }
                    break;
                case "delete":
                    // 更新交易明细逻辑
                    String errMsg1 = deleteTransDetail(jsondata);
                    if (!EmptyUtils.isEmpty(errMsg1)) {
                        log.error("九恒星-交易明细更新失败。操作类型:{}，交易明细数据:{}，错误信息:{}", operation, jsondata, errMsg1);

                        code = "500";
                        msg = "交易明细删除失败，" + errMsg1;
                    } else {
                        log.info("九恒星-交易明细更新成功。操作类型:{}，交易明细数据:{}", operation, jsondata);

                        code = "200";
                        msg = "交易明细删除成功";
                    }
                    break;
                default:
                    log.error("九恒星-不支持的操作类型。操作类型:{}，交易明细数据:{}", operation, jsondata);
                    break;
            }

            returnModel.setNumber(number);
            returnModel.setCode(code);
            returnModel.setMessage(msg);

            JSONArray dataArray = new JSONArray();
            dataArray.add(JSONObject.parseObject(JSON.toJSONString(returnModel)));

            return returnResult("200", "S", "九恒星-接口调用成功，同步结果请查看responseData参数", dataArray);
        } catch (Exception e) {
            log.error("九恒星-保存交易明细失败。操作类型:{}，交易明细数据:{}，错误信息:{}", operation, jsondata, e.getMessage());

            returnModel.setNumber(number);
            returnModel.setCode("500");
            returnModel.setMessage("操作交易明细失败: " + e.getMessage());

            JSONArray dataArray = new JSONArray();
            dataArray.add(JSONObject.parseObject(JSON.toJSONString(returnModel)));

            return returnResult("500","E","九恒星-接口调用异常，同步结果请查看responseData参数", dataArray);
        }
    }

    private String deleteTransDetail(String jsonData) {
        // 解析JSON数据
        JSONObject jsonObject = JSON.parseObject(jsonData);

        StringBuilder errMsg = new StringBuilder();
        // 交易流水号ID  关键字
        String number = jsonObject.getString("number");
        // 电子回单号ID  关键字
        //String receiptNo = jsonObject.getString("receiptNo");

        // 是否有重复信息接收单
        DynamicObject billByn = BusinessDataServiceHelper.loadSingle(
                BeiTransdetailConstantInfo.ENTITYID,
                new QFilter[]{new QFilter(BeiTransdetailConstantInfo.BILLNO, QCP.equals, number)}
        );
        if(!EmptyUtils.isEmpty(billByn)) {
            DeleteServiceHelper.delete(BeiTransdetailConstantInfo.ENTITYID,new QFilter[]{new QFilter("id", QCP.equals, billByn.getPkValue())});
        }else {
            errMsg = new StringBuilder("交易流水号: " + number + "不存在;");
        }

        // 是否有重复信息接收单
        DynamicObject billeleByn = BusinessDataServiceHelper.loadSingle(
                BeiElecreceiptConstantInfo.ENTITYID,
                new QFilter[]{new QFilter(BeiElecreceiptConstantInfo.BILLNO, QCP.equals, number)}
        );
        if(!EmptyUtils.isEmpty(billeleByn)) {
            DeleteServiceHelper.delete(BeiElecreceiptConstantInfo.ENTITYID,new QFilter[]{new QFilter("id", QCP.equals, billeleByn.getPkValue())});
        }else {
            errMsg = new StringBuilder("电子回单号: " + number + "不存在;");
        }

        return errMsg.toString();

    }

    /**
     * 保存交易明细信息
     *
     * @param jsonData  JSON数据
     */
    public String saveTransDetail( String jsonData) {
        // 解析JSON数据
        JSONObject jsonObject = JSON.parseObject(jsonData);

        StringBuilder errMsg =  new StringBuilder();
        // 交易流水号ID  关键字
        String number = jsonObject.getString("number");


        // 是否有重复信息接收单
        DynamicObject billByn = BusinessDataServiceHelper.loadSingle(
                BeiTransdetailConstantInfo.ENTITYID,
                new QFilter[]{new QFilter(BeiTransdetailConstantInfo.BILLNO, QCP.equals, number)}
        );
        boolean isNew = EmptyUtils.isEmpty(billByn);
        DynamicObject transDetail = null;
        if(!isNew){
            transDetail = billByn;
        }else {
            // 创建动态对象，用于存储交易明细数据
            transDetail = BusinessDataServiceHelper.newDynamicObject(BeiTransdetailConstantInfo.ENTITYID);
            //生成随机单据id
            long Id = DB.genLongId("t_bei_transdetail");
            transDetail.set("id", Id);
            transDetail.set(BeiTransdetailConstantInfo.BILLNO, number); // 编号
        }

        // 设置字段值，将JSON中的数据映射到动态对象中
        /**
         * 资金组织判断
         */
        //String company  = jsonObject.getString("company");
        JSONObject companyObj =  jsonObject.getJSONObject("company");
        if (EmptyUtils.isNotEmpty(companyObj)) {
            String company = companyObj.getString("id");
            DynamicObject companyByn = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter[]{new QFilter("number", QCP.equals, company)});
            if (EmptyUtils.isEmpty(companyByn)) {
                errMsg.append("资金组织不存在;");
            } else {
                transDetail.set(BeiTransdetailConstantInfo.COMPANY, companyByn); // 资金组织Number
            }
        }else{
            errMsg.append("组织不能为空;");
        }
        /**
         * 银行账号Number
         */
        String bankAccount = jsonObject.getString("bankAccountNumber");
        DynamicObject bankAccountByn = BusinessDataServiceHelper.loadSingle("bd_accountbanks",new QFilter[]{new QFilter("number", QCP.equals, bankAccount)});
        if (EmptyUtils.isEmpty(bankAccountByn)){
            errMsg.append("银行账号不存在;");
        }else {
            transDetail.set(BeiTransdetailConstantInfo.ACCOUNTBANK, bankAccountByn); // 银行账号Number
            transDetail.set(BeiTransdetailConstantInfo.BANK, bankAccountByn.getDynamicObject("bank"));  // 开户银行
        }
        /**
         * 币种ID
         */
        //String currency = jsonObject.getString("currency");
        JSONObject currencyObj =  jsonObject.getJSONObject("currency");
        if (EmptyUtils.isNotEmpty(currencyObj)) {
            String currency = currencyObj.getString("id");
            DynamicObject currencyByn = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter[]{new QFilter("number", QCP.equals, currency)});
            if (EmptyUtils.isEmpty(currencyByn)) {
                errMsg.append("币种不存在;");
            } else {
                transDetail.set(BeiTransdetailConstantInfo.CURRENCY, currencyByn); // 币种Number
            }
        }
        String bizTimeStr =  jsonObject.getString("bizTime");
        Date bizTime = DateUtils.parseDateTime(bizTimeStr, "yyyy-MM-dd HH:mm:ss");
        transDetail.set(BeiTransdetailConstantInfo.BIZTIME, bizTime); // 原始交易时间

        String bizdateString =  jsonObject.getString("bizDate");
        Date bizdate = DateUtils.parseDateTime(bizdateString, "yyyy-MM-dd");
        transDetail.set(BeiTransdetailConstantInfo.BIZDATE, bizdate); // 业务日期

        transDetail.set(BeiTransdetailConstantInfo.DESCRIPTION, jsonObject.getString("description")); // 描述
        transDetail.set(BeiTransdetailConstantInfo.BUSINESSBILLNUM, jsonObject.getString("name"));    //票据号

        transDetail.set(BeiTransdetailConstantInfo.CREDITAMOUNT, jsonObject.getBigDecimal("creditAmount")); // 收款金额
        transDetail.set(BeiTransdetailConstantInfo.DEBITAMOUNT, jsonObject.getBigDecimal("debitAmount")); // 付款金额
        transDetail.set(BeiTransdetailConstantInfo.TRANSBALANCE, jsonObject.getBigDecimal("transBalance")); // 余额

        transDetail.set(BeiTransdetailConstantInfo.OPPUNIT, jsonObject.getString("oppUnit")); // 对方户名
        transDetail.set(BeiTransdetailConstantInfo.OPPBANK, jsonObject.getString("oppBank")); // 对方开户银行
        transDetail.set(BeiTransdetailConstantInfo.OPPBANKNUMBER, jsonObject.getString("oppBankNumber")); // 对方银行账号

        /**
         * 交易流水号ID
         */
        transDetail.set(BeiTransdetailConstantInfo.DETAILID, jsonObject.getString("tranPackageID")); // 交易流水号ID
        transDetail.set(BeiTransdetailConstantInfo.BANKDETAILNO, jsonObject.getString("tranPackageID")); // 银行流水号

        transDetail.set(BeiTransdetailConstantInfo.BILLSTATUS, "C");
        String receiptNo = jsonObject.getString("receiptNo");
        transDetail.set(BeiTransdetailConstantInfo.RECEIPTNO, receiptNo); // 电子回单编号

        /**
         * 入账状态
         * 待入账=0,已入账=1,无需入账=2
         */
        //String isReced = jsonObject.getString("isReced");
        JSONObject isRecedObj =  jsonObject.getJSONObject("isReced");
        if (EmptyUtils.isNotEmpty(isRecedObj)) {
            String isReced = isRecedObj.getString("value");
            switch (isReced) {
                case "0":
                    transDetail.set(BeiTransdetailConstantInfo.RECEREDTYPE, "0");
                    break;
                case "1":
                    transDetail.set(BeiTransdetailConstantInfo.RECEREDTYPE, "3");
                    break;
                default:
                    errMsg.append("入账状态不存在;");
                    break;
            }
        }

        /**
         * 业务类型
         * 普通	1
         * 上划	2
         * 下拨	3
         * 内部代付	4
         * 内部转账	5
         * 内部扣款	6
         * 贷款收回	7
         * 贷款结息	8
         * 活转定	9
         * 定转活	10
         * 供应链融资还款	11
         * 联动支付	12
         * 内部收款	13
         * 贷款发放	14
         * 存款结息	15
         * 定期收益	16
         */

        JSONObject bizTypeObj =  jsonObject.getJSONObject("bizType");
        if (EmptyUtils.isNotEmpty(bizTypeObj)) {
            String bizType = bizTypeObj.getString("value");
            switch (bizType) {
                case "1":
                    transDetail.set(BeiTransdetailConstantInfo.BIZTYPE, "1");
                    break;
                case "2":
                    transDetail.set(BeiTransdetailConstantInfo.BIZTYPE, "2");
                    transDetail.set(BeiTransdetailConstantInfo.ISTRANSUP, true); // 是否上划
                    break;
                case "3":
                    transDetail.set(BeiTransdetailConstantInfo.BIZTYPE, "3");
                    transDetail.set(BeiTransdetailConstantInfo.ISTRANSDOWN, true); // 是否下拨
                    break;
                default:
                    errMsg.append("业务类型不存在;");
                    break;
            }
        }
        if(EmptyUtils.isNotEmpty(errMsg)){
            return errMsg.toString();
        }

        String electricAddress = jsonObject.getString("electricAddress");
        // 判断是否有电子回单，如果有则处理电子回单单据对象，并保存
        if (EmptyUtils.isNotEmpty(electricAddress)) {
            DynamicObject elecreceipt = BusinessDataServiceHelper.loadSingle(BeiElecreceiptConstantInfo.ENTITYID, new QFilter[]{new QFilter("receiptno", QCP.equals, receiptNo)});
            /**
             * 保存电子回单
             */
            String errStr = saveElecreceipt(transDetail, elecreceipt,electricAddress);
            if (EmptyUtils.isNotEmpty(errStr)) {
                errMsg.append(errStr);
                return errMsg.toString();
            }else{
                transDetail.set(BeiTransdetailConstantInfo.ISMATCHERECEIPT, true); // 是否匹配电子回单

            }
        }

        //  银行主键 不能重复 不能为空
        transDetail.set(BeiTransdetailConstantInfo.UNIQUESEQ, receiptNo);

        //需要与付款单建立关联关系
        String casBillID = jsonObject.getString("sourceBillId");
        DynamicObject paybillDyn = null;
        if(StringUtils.isNotEmpty(casBillID)){
            if(casBillID.contains("@")){
                casBillID = casBillID.split("@")[0];
            }

            Long billid  = Long.parseLong(casBillID);
            //获取 付款单号
            QFilter qFilter = new QFilter("id", QCP.equals, billid);
            paybillDyn = BusinessDataServiceHelper.loadSingle("cas_paybill", new QFilter[]{qFilter});
            if (paybillDyn != null) {

                transDetail.set(BeiTransdetailConstantInfo.SOURCEBILLID, paybillDyn.getPkValue());
                transDetail.set(BeiTransdetailConstantInfo.SOURCEBILLTYPE, "cas_paybill");
            }
        }

        SaveServiceHelper.save(new DynamicObject[]{transDetail});
        if (EmptyUtils.isNotEmpty(paybillDyn)) {
            //在付款单保存交易流水号
            paybillDyn.set("detailseqid", number);
            paybillDyn.set("nckd_detailtimes", bizdate);
            paybillDyn.set("nckd_receiptno", receiptNo);
            SaveServiceHelper.save(new DynamicObject[]{paybillDyn});

            //保存与付款单的关联关系   不用保存   通过联查处理了
            ///CasBotpHelper.saveRelation(paybillDyn, transDetail);

            Long billID = paybillDyn.getLong("sourcebillid");
            String billtype = paybillDyn.getString("sourcebilltype");
            if (billID > 0 && EmptyUtils.isNotEmpty(billtype)){
                List<Long> billIds = new ArrayList<>();
                billIds.add(billID);
                /**
                 * 付款单上游单据生成凭证
                 */
                OperationServiceHelper.executeOperate("nckd_rebackpayinfo", billtype, billIds.toArray(), OperateOption.create());
            }
        }

        return errMsg.toString();
    }

    /**
     * 保存电子回单信息
     *
     * @param transDetail 交易明细对象，包含交易的详细信息
     * @param elecreceipt 电子回单对象，如果已存在则不为空
     * @param electricAddress 电子回单的地址，用于从FTP服务器下载文件
     * @return 返回错误信息，如果没有错误则返回空字符串
     */
    private String saveElecreceipt( DynamicObject transDetail,DynamicObject elecreceipt,String electricAddress) {
        StringBuilder errMsg = new StringBuilder();

        DynamicObject elecreceiptDyn = null;
        String receiptNo = transDetail.getString(BeiTransdetailConstantInfo.RECEIPTNO);
        if(!EmptyUtils.isEmpty(elecreceipt)){
            elecreceiptDyn = elecreceipt;
            return "";
        }else {
            // 创建动态对象，用于存储交易明细数据
            elecreceiptDyn = BusinessDataServiceHelper.newDynamicObject(BeiElecreceiptConstantInfo.ENTITYID);
            long Id = DB.genLongId("t_bei_elecreceipt");
            elecreceiptDyn.set("id", Id);

            String billNo = CodeRuleHelper.generateNumber(BeiElecreceiptConstantInfo.ENTITYID, elecreceiptDyn, null, null);
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.DETAILID, transDetail.get(BeiTransdetailConstantInfo.DETAILID));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.BILLNO, billNo);
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.COMPANY, transDetail.get(BeiTransdetailConstantInfo.COMPANY));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.ACCOUNTBANK, transDetail.get(BeiTransdetailConstantInfo.ACCOUNTBANK));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.CURRENCY, transDetail.get(BeiTransdetailConstantInfo.CURRENCY));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.BIZDATE, transDetail.get(BeiTransdetailConstantInfo.BIZDATE));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.BIZTYPE, transDetail.get(BeiTransdetailConstantInfo.BIZTYPE));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.DETAILDATETIME, transDetail.get(BeiTransdetailConstantInfo.BIZTIME));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.DESCRIPTION, transDetail.get(BeiTransdetailConstantInfo.DESCRIPTION));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.DEBITAMOUNT, transDetail.get(BeiTransdetailConstantInfo.DEBITAMOUNT));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.CREDITAMOUNT, transDetail.get(BeiTransdetailConstantInfo.CREDITAMOUNT));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.RECEIPTNO, transDetail.get(BeiTransdetailConstantInfo.RECEIPTNO));
            if(transDetail.getBigDecimal(BeiTransdetailConstantInfo.DEBITAMOUNT).compareTo(BigDecimal.ZERO)>0){
                elecreceiptDyn.set(BeiElecreceiptConstantInfo.AMOUNT, transDetail.get(BeiTransdetailConstantInfo.DEBITAMOUNT));
                elecreceiptDyn.set(BeiElecreceiptConstantInfo.CREDITDEBITFLAG, "1");
            }else{
                elecreceiptDyn.set(BeiElecreceiptConstantInfo.AMOUNT, transDetail.get(BeiTransdetailConstantInfo.CREDITAMOUNT));
                elecreceiptDyn.set(BeiElecreceiptConstantInfo.CREDITDEBITFLAG, "2"); // 借贷标记
            }
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.OPPUNIT, transDetail.get(BeiTransdetailConstantInfo.OPPUNIT));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.OPPBANK, transDetail.get(BeiTransdetailConstantInfo.OPPBANK));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.OPPBANKNUMBER, transDetail.get(BeiTransdetailConstantInfo.OPPBANKNUMBER));
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.BILLSTATUS, transDetail.get(BeiTransdetailConstantInfo.BILLSTATUS));

            DynamicObjectCollection entrys = elecreceiptDyn.getDynamicObjectCollection(BeiElecreceiptConstantInfo.MATCHDETAILENTRY);
            DynamicObject entry = entrys.addNew();
            entry.set("e_transdetailid",transDetail.getPkValue());

            ///处理交易明细的分录
            DynamicObjectCollection entrys1 = transDetail.getDynamicObjectCollection(BeiTransdetailConstantInfo.MATCHRECEIPTENTRY);
            if(entrys1.size()<=0) {
                DynamicObject entry1 = entrys1.addNew();
                entry1.set("e_receiptid", Id);
                entry1.set("e_receiptno", receiptNo);
            }

        }

        /**
         * 地址格式：address="ftp:\\\\172.16.3.232\\Files\\12Qwee.pdf";
         * 格式 ：ftp://172.16.68.44:21/Files/CMB//791904936510302_20250422-20250422_365B261684797_C04474R0007ZOYZ.jpg
         */
        if(EmptyUtils.isEmpty(elecreceipt) && EmptyUtils.isNotEmpty(electricAddress)){
            String address = electricAddress;
            address = address.replace("//", "/");
            address = address.replace("\\", "/");
            String filename = extractFilename(address);
            //elecreceiptDyn.set(BeiElecreceiptConstantInfo.UPLOADFILENAME,filename);//文件名称

            address = address.split("Files")[1];
            address = "/Files"+address;
            address = address.replace("//", "/");
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.FILEPATH,address);//电子回单路径

            /**
             * 从FTP上将文件上传到苍穹中，处理文件上传
             */
            String fileurl =  oprationFilename(address);
            Map<String, Object> reMap = AttachmentFileUtil.saveUrlFile2Attchment(receiptNo, BeiElecreceiptConstantInfo.ENTITYID, elecreceiptDyn.getPkValue(), fileurl, filename, "0", "attachmentpanel");
            if(reMap.get("isSuccess").toString().equals("false")){
                errMsg.append(reMap.get("msg").toString());
                return errMsg.toString();
            }else{
                String pathParam = reMap.get("pathParam").toString();
                if(StringUtils.isNotEmpty(pathParam)){
                    elecreceiptDyn.set(BeiElecreceiptConstantInfo.FILEPATH, pathParam);
                }
                //String url = reMap.get("url").toString();
                String url = reMap.get("downUrl").toString();
                if(StringUtils.isNotEmpty(url)){
                    elecreceiptDyn.set(BeiElecreceiptConstantInfo.UPLOADFILENAME, url);
                }
            }
            elecreceiptDyn.set(BeiElecreceiptConstantInfo.FILEFLAG, "1"); // 是否已上传
        }

        SaveServiceHelper.save(new DynamicObject[]{elecreceiptDyn});

        return errMsg.toString();
    }

    public static String oprationFilename(String path) {
        // Remove the leading slash if present
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        // Extract the substring after the last slash
        return path;
    }

    public static String extractFilename(String address) {
        // Find the last slash in the URL
        int lastSlashIndex = address.lastIndexOf('/');
        if (lastSlashIndex == -1) {
            return null; // No slash found, invalid URL
        }
        // Extract the substring after the last slash
        return address.substring(lastSlashIndex + 1);
    }
    public static String extractBillID(String billid) {
        // Find the last slash in the URL
        int lastSlashIndex = billid.lastIndexOf('-');
        if (lastSlashIndex == -1) {
            return billid; // No slash found, invalid URL
        }
        // Extract the substring after the last slash
        return billid.substring(lastSlashIndex + 1);
    }

    /**
     * 自定义返回data对象
     * @param code  编码
     * @param message  错误信息
     * @return   CustomApiResult  返回
     */
    public CustomApiResult<JSONObject> returnResult(String code, String status, String message, JSONArray dataArrary){
        JSONObject reslutData = new JSONObject();

        JSONArray responseData = new JSONArray();
        JSONObject dataJSON = new JSONObject();
        dataJSON.put("data", dataArrary);

        responseData.add(dataJSON);

        reslutData.put("code", code);
        reslutData.put("status", status);
        reslutData.put("message", message);
        reslutData.put("responseData", responseData);

        return CustomApiResult.success(reslutData);
    }
}
