package nckd.jimin.jyyy.fi.plugin.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.exception.KDBizException;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.print.NotePrintService;
import kd.bos.util.ExceptionUtils;
import kd.bos.web.actions.utils.FilePathUtil;
import kd.fi.cas.util.EmptyUtil;
import kd.tmc.bei.common.helper.ReceiptPrintHelper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 批量查询电子回单帮助类
 * @author wanghaiwu_kd
 * @date 2025/09/04
 */
public class FeiBillFileViewMultHelper {
    private static final Log logger = LogFactory.getLog(FeiBillFileViewMultHelper.class);

    /**
     * 获取电子回单ID
     * 通过付款单ID获取交易明细ID，再通过交易明细ID获取电子回单ID
     * @param payBillId
     * @return
     */
    public static String getElecreceiptByFile(String payBillId) throws IOException {
        Long billId = Long.parseLong(payBillId);
        QFilter qFilter = new QFilter("sourcebillid", QCP.equals, billId);
        qFilter.and(new QFilter("detailseqid", QCP.not_equals, " "));

        //查询报销单的下游付款单
        DynamicObject[] billDyns = BusinessDataServiceHelper.load("cas_paybill","id,detailseqid", qFilter.toArray());
        if(EmptyUtil.isEmpty(billDyns)) {
            return null;
        }

        List<String> transdetailIds = Arrays.stream(billDyns)
                .map(dyn -> dyn.getString("detailseqid"))
                .collect(Collectors.toList());
        if(transdetailIds.size() == 0) {
            return null;
        }

        qFilter = new QFilter("billno", QCP.in, transdetailIds);

        //查询付款单的下游交易明细
        DynamicObject[] transdetailDyns = BusinessDataServiceHelper.load("bei_transdetail","id,receiptno", qFilter.toArray());
        if(EmptyUtil.isEmpty(transdetailDyns)) {
            return null;
        }

        List<byte[]> resList = new ArrayList<>(10);

        for(DynamicObject transdetail : transdetailDyns){
            String elecreceiptNo = transdetail.getString("receiptno");
            QFilter qf2 = new QFilter("receiptno", QCP.equals, elecreceiptNo);
            DynamicObject elecreceiptDyn = BusinessDataServiceHelper.loadSingle("bei_elecreceipt", new QFilter[]{qf2});

            if(EmptyUtil.isEmpty(elecreceiptDyn)) {
                continue;
            }

            Long elecreceiptId = elecreceiptDyn.getLong("id");

            //创建一条基础资料数据-附件字段
            //获取单据信息，并查询单据中的附件字段
            QFilter qf = new QFilter("id", QCP.equals, elecreceiptId);
            DynamicObject file = BusinessDataServiceHelper.loadSingle("bei_elecreceipt", "attachmentpanel", new QFilter[]{qf});

            if(file == null){
                continue;
            }

            //获取单据中附件面板信息
            List<Map<String, Object>> atts = AttachmentServiceHelper.getAttachments("bei_elecreceipt", file.getPkValue().toString(), "attachmentpanel");
            //遍历文件
            for (Map<String, Object>  attachmentMap: atts) {
                if(attachmentMap.get("type") != null
                        && ("pdf".equals(attachmentMap.get("type").toString()) || "jpg".equals(attachmentMap.get("type").toString()))) {

                    if(attachmentMap == null) {
                        continue;
                    }

                    Object relativeUrl = attachmentMap.get("relativeUrl");
                    if (relativeUrl == null) {
                        continue;
                    }

                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    String path = FilePathUtil.dealPath(relativeUrl.toString(), "attach");
                    InputStream inputStream = FileServiceFactory.getAttachmentFileService().getInputStream(path);

                    if("jpg".equals(attachmentMap.get("type").toString())){
                        ReceiptPrintHelper.imageConvertPdf(path, resList, inputStream);
                        continue;
                    }

                    byte[] bytesAtt = getBytes(inputStream,outputStream);
                    resList.add(bytesAtt);
                }
            }
        }

        if(resList.size() == 0){
            return null;
        }

        String pdfUrl = null;

        try {
            pdfUrl = finlyOpenForm(resList);
        } catch (Exception var27) {
            logger.error("mergeMultiPdf Fail：", ExceptionUtils.getExceptionStackTraceMessage(var27));
        }

        return pdfUrl;
    }


    public static Map<String, Object>  getAttachmentFile(Long billId) {

        //创建一条基础资料数据-附件字段
        //获取单据信息，并查询单据中的附件字段
        QFilter qf = new QFilter("id", QCP.equals, billId);
        DynamicObject file =BusinessDataServiceHelper.loadSingle("bei_elecreceipt", "attachmentpanel",new QFilter[]{qf});
        //获取单据中附件面板信息
        List<Map<String, Object>> atts = AttachmentServiceHelper.getAttachments("bei_elecreceipt", file.getPkValue().toString(), "attachmentpanel");
        //遍历文件   电子回单只有一条
        for (Map<String, Object>  att: atts) {
            if(att.get("type") != null && "pdf".equals(att.get("type").toString())) {
                return att;
            }
        }
        return null;
    }


    private static byte[] getBytes(InputStream inputStream, ByteArrayOutputStream outputStream) throws IOException {
        int b;
        while ((b= inputStream.read())!=-1){
            outputStream.write(b);
        }
        byte[] bytes1 = outputStream.toByteArray();
        return bytes1;
    }

    private static String finlyOpenForm(List<byte[]> resList) {
        if (!resList.isEmpty()) {
            byte[] mergeMultiPdf;
            if (resList.size() > 1) {
                try {
                    mergeMultiPdf = ReceiptPrintHelper.mergeMultiPdf(resList);
                } catch (Exception var5) {
                    throw new KDBizException(ExceptionUtils.getExceptionStackTraceMessage(var5));
                }
            } else {
                mergeMultiPdf = (byte[])resList.get(0);
            }

            NotePrintService notePrintService = new NotePrintService();
            LocaleString localeString = new LocaleString("receipt");
            return notePrintService.createPdfUrl(localeString, mergeMultiPdf);
        } else {
            return null;
        }
    }

    public static void openForm(IFormView view, String pdfUrl) {
        IFormView mainView = view.getMainView();
        if (mainView == null) {
            view.openUrl(pdfUrl);
        } else {
            FormShowParameter formShowParameter = new FormShowParameter();
            formShowParameter.setFormId("bos_printpreview");
            formShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
            formShowParameter.setCustomParam("src", pdfUrl);
            formShowParameter.setCaption(ResManager.loadKDString("联查回单", "ElecReceiptQueryPlugin_1", "bos-ext-tmc", new Object[0]));
            view.getParentView().showForm(formShowParameter);
            view.sendFormAction(view.getParentView());
        }

    }
}
