package com.seeyon.apps.src_saomaoyi.invoice;

import com.seeyon.apps.src_saomaoyi.config.SaoMiaoYiPluginConfigProvider;
import com.seeyon.apps.src_saomaoyi.constants.SaoMiaoYiConstants;
import com.seeyon.apps.src_saomaoyi.utils.*;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.organization.bo.V3xOrgAccount;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.services.FileUploadExporter;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.bean.FormExport;
import com.seeyon.v3x.services.form.bean.ValueExport;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class InvoiceImgSaveServiceImpl implements InvoiceImgSaveService {

    private FormFactory formFactory;

    private SaoMiaoYiPluginConfigProvider configProvider = (SaoMiaoYiPluginConfigProvider) AppContext.getBean("saoMiaoYiPluginConfigProvider");

    public FormFactory getFormFactory() {
        if (formFactory == null) {
            formFactory = (FormFactory) AppContext.getBean("formFactory");
        }
        return formFactory;
    }
    public void setFormFactory(FormFactory formFactory) {
        this.formFactory = formFactory;
    }

    @Override
    public void saveInvoiceImg(InputStream is) throws Exception {
        String code = insertRecord();
        String formCode = configProvider.getBizConfigByKey(SaoMiaoYiConstants.formCode);
        FormDataOperator formDataOperator = new FormDataOperator();
        List<FormWhereCondition> condiitonVo = new ArrayList<>();
        List<FormUpdateField> updateFields = new ArrayList<>();
        condiitonVo.add(FormWhereCondition.build().display("编号").value(code));

        List<FormColumn> formColumns = formDataOperator.queryFormDataCondition(formCode, null, condiitonVo);
        if (formColumns == null || formColumns.size() == 0) {
            throw new RuntimeException("查询错误");
        }
        String formId = formColumns.get(0).getId();
        String refId = bindFileRef(formId,is);
        updateFields.add(FormUpdateField.build().value(refId).display("文件"));
        List<FormWhereCondition> whereClause = new ArrayList<>();
        whereClause.add(FormWhereCondition.build().display("ID").value(Long.parseLong(formId)));
        formDataOperator.updateMasterForm(formCode, updateFields, whereClause);
    }

    private String bindFileRef(String formId, InputStream is) throws Exception {
        String refId = Math.abs(UUID.randomUUID().getLeastSignificantBits()) + "";
        String localFilePath = System.getProperty("java.io.tmpdir") + File.separator + "seeyontempfile";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String tempFileName = UUID.randomUUID() + ".pdf";
        File tempFileParent = new File(localFilePath);

        if (!tempFileParent.exists()) {
            tempFileParent.mkdirs();
        }

        File tempFile = new File(tempFileParent, tempFileName);

        // ----------- 关键修复：用字节流复制 InputStream 到 PDF -----------
        try (InputStream input = is;
             OutputStream output = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[8192];
            int len;
            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
        } catch (Exception e) {
            throw new RuntimeException("保存临时 PDF 文件失败", e);
        }

        // 限制 100MB
        if (tempFile.length() > 102400000) {
            tempFile.delete();
            return null;
        }

        // 调用 Seeyon 附件服务上传
        FileUploadExporter fileUpload = new FileUploadExporter();
        String uploadResult = fileUpload.processUpload(new String[]{tempFile.getAbsolutePath()});

        Map<String, String> map = new HashMap<>();
        map.put("type", "0");
        map.put("fileUrl", uploadResult);
        map.put("mimeType", "application/pdf");
        map.put("size", String.valueOf(tempFile.length()));
        map.put("subReference", refId);
        map.put("category", "66");
        map.put("createdate", sdf.format(new Date()));
        map.put("filename", tempFileName);
        map.put("reference", formId);

        // 删除本地临时文件
        tempFile.delete();

        Attachment attachment = new Attachment(map);
        OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
        AttachmentManager attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");

        String loginName = configProvider.getBizConfigByKey(SaoMiaoYiConstants.formDataLoginName);
        String updateAccountName = configProvider.getBizConfigByKey(SaoMiaoYiConstants.updateAccountName);

        V3xOrgMember member = orgManager.getMemberByLoginName(loginName);
        V3xOrgAccount account = orgManager.getAccountByName(updateAccountName);

        attachmentManager.create(Collections.singletonList(attachment), member.getId(), account.getId());

        return refId;
    }


    public String insertRecord() throws Exception {
        String code = UUID.randomUUID().toString().replace("-", "");
        String loginName = configProvider.getBizConfigByKey(SaoMiaoYiConstants.formDataLoginName);
        String formCode = configProvider.getBizConfigByKey(SaoMiaoYiConstants.formCode);
        Map<String,Object> map = new HashMap<String,Object>();
        Long currentUserId = AppContext.currentUserId();
        if(currentUserId != null) {
           map.put("操作人",currentUserId);
        }
        map.put("编号", code);
        FormExport formExport = new FormExport();
        FormExportUtil formExportUtil = new FormExportUtil();
        List<ValueExport> valueExport = formExportUtil.setFormValue(map);
        formExport.setValues(valueExport);
        getFormFactory().importBusinessFormData(loginName, formCode,
                formExport, new String[] {});
        return code;
    }
}
