package com.yem.wm.utils;


/**
 * @author lipan
 * @date 2023/11/20 18:37
 * @className PrintHelper
 * @description
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import kd.bos.bill.OperationStatus;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.exception.KDBizException;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.print.api.PrintTask;
import kd.bos.print.api.PrintWork;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.print.core.service.PrtAttach.AttachDetail;
import kd.bos.print.service.BosPrintServiceHelper;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.attachment.AttachmentFieldServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserConfigServiceHelper;
import kd.bos.url.UrlService;
import kd.bos.util.FileNameUtils;
import org.apache.commons.io.IOUtils;

/**
 * 二开打印
 *
 * @author longh
 * @description
 * @date 2023年10月16日
 */
public class PrintHelper {

    public static void print(IFormView view) {
        IDataModel model = view.getModel();
        DynamicObject dataEntity = model.getDataEntity();
        Object pkId = dataEntity.getPkValue();
        if (YEM.isEmpty(pkId)) {
            view.showTipNotification("请先保存单据。");
            return;
        }
        String entityId = view.getEntityId();
        FormShowParameter formShowParameter = view.getFormShowParameter();
        String formId = formShowParameter.getFormId();
        String tplId = "";
        String printLang = "";
        String setting = UserConfigServiceHelper.getSetting(YEM.getCurrentUserId(), formId + "_printsetting");
        if (setting != null) {
            JSONObject fromJsonString = SerializationUtils.fromJsonString(setting, JSONObject.class);
            if (fromJsonString != null) {
                tplId = fromJsonString.getString("templateid");
                printLang = fromJsonString.getString("printlang");
            }
        }
        if (YEM.isEmpty(tplId)) {
            view.showTipNotification("没有设置打印模板，请在“打印”->“设置”中进行设置。");
        } else {
            ArrayList<Object> pkIds = new ArrayList<>();
            pkIds.add(pkId);
            // 打印任务
            ArrayList<PrintTask> taskList = new ArrayList<>();
            PrintTask printTask = new PrintTask();
            printTask.setTplId(tplId);// 打印模板的id
            printTask.setPkIds(pkIds);
            printTask.setPrintType("billForm");// 打印对象的类型，是单据（billForm),报表（report)，还是动态表单(dynamic)
            printTask.setFormId(entityId);
            taskList.add(printTask);
            // 打印作业
            PrintWork printWork = new PrintWork();
            printWork.setPrintLang(YEM.isEmpty(printLang) ? "zh_CN" : printLang);
            printWork.setExpType("pdf");
            printWork.setTaskList(taskList);
            // 生成打印模板生成的pdf文件
            PrtAttach doPrint = BosPrintServiceHelper.doPrint(printWork);
//            PrtAttach doPrint = BosPrintServiceHelper.execPrint(printWork);
            List<AttachDetail> attachDetails = doPrint.getAttachDetail();
            for (AttachDetail attachDetail : attachDetails) {
                String filePath = attachDetail.getFilePath();
                String fileName = "";
                String attachmentKey = "yem_approval";
                AttachmentUtil.uploadAttachmentPanel(entityId, pkId, attachmentKey, fileName, filePath);
                view.invokeOperation("refresh");
                break;
            }
        }
    }

    public static void printdata(DynamicObject dataEntity, String attachmentKey) {
        Object pkId = dataEntity.getPkValue();
        if (YEM.isEmpty(pkId)) {
            throw new KDBizException("请先保存单据。");
        }
        String entityId = dataEntity.getDataEntityType().getName();
        String formId = dataEntity.getDataEntityType().getName();
        String yem_billtype = dataEntity.getString("yem_billtype.number");
        if (yem_billtype.equals("yem_es_salesorder_ZJ")) {
            formId = "yem_es_salesorder_zj";
        } else if (yem_billtype.equals("yem_es_salesorder_PJ")) {
            formId = "yem_es_salesorder_pj";
        } else if (yem_billtype.equals("yem_es_salesorder_nmzj")) {
            formId = "yem_es_salesorder_nmzj";
        } else if (yem_billtype.equals("yem_es_salesorder_nmpj")) {
            formId = "yem_es_salesorder_nmpj";
        } else if (yem_billtype.equals("yem_es_xsalesorder_zj")) {
            formId = "yem_es_xsalesorder_zj";
        }
        if (yem_billtype.equals("yem_es_xsalesorder_pj")) {
            formId = "yem_es_xsalesorder_pj";
        }
        if (yem_billtype.equals("yem_es_xsalesorder_nmzj")) {
            formId = "yem_es_xsalesorder_nmzj";
        }
        if (yem_billtype.equals("yem_es_xsalesorder_nmpj")) {
            formId = "yem_es_xsalesorder_nmpj";
        }
        String tplId = "";
        String printLang = "";
        String setting = UserConfigServiceHelper.getSetting(YEM.getCurrentUserId(), formId + "_printsetting");
        if (setting != null) {
            JSONObject fromJsonString = SerializationUtils.fromJsonString(setting, JSONObject.class);
            if (fromJsonString != null) {
                tplId = fromJsonString.getString("templateid");
                printLang = fromJsonString.getString("printlang");
            }
        }
        if (YEM.isEmpty(tplId)) {
            throw new KDBizException("没有设置打印模板，请在“打印”->“设置”中进行设置。");
        } else {
            ArrayList<Object> pkIds = new ArrayList<>();
            pkIds.add(pkId);
            // 打印任务
            ArrayList<PrintTask> taskList = new ArrayList<>();
            PrintTask printTask = new PrintTask();
            printTask.setTplId(tplId);// 打印模板的id
            printTask.setPkIds(pkIds);
            printTask.setPrintType("billForm");// 打印对象的类型，是单据（billForm),报表（report)，还是动态表单(dynamic)
            printTask.setFormId(entityId);
            taskList.add(printTask);
            // 打印作业
            PrintWork printWork = new PrintWork();
            printWork.setPrintLang(YEM.isEmpty(printLang) ? "zh_CN" : printLang);
            printWork.setExpType("pdf");
            printWork.setTaskList(taskList);
            // 生成打印模板生成的pdf文件
            PrtAttach doPrint = BosPrintServiceHelper.doPrint(printWork);
//            PrtAttach doPrint = BosPrintServiceHelper.execPrint(printWork);
            //调用打印服务接口
            List<AttachDetail> attachDetails = doPrint.getAttachDetail();
            for (AttachDetail attachDetail : attachDetails) {
                String filePath = attachDetail.getFilePath();
                String fileName = attachDetail.getFileName();
//                String attachmentKey = "yem_approval";
                Boolean isattachmentpanel = isattachmentpanel(dataEntity, fileName, attachmentKey);
                if (isattachmentpanel) {
                    String url = "";
                    if (filePath.contains("configKey=redis.serversForCache&id=tempfile")) {
                        //持久化附件到服务器
                        String attachmentFullUrl = UrlService.getAttachmentFullUrl(filePath);
                        url = uploadTempfile(attachmentFullUrl, fileName);
                    } else {
                        url = filePath;
                    }
                    uploadAttachmentPanel(entityId, pkId, attachmentKey, fileName, url);
                } else {
                    throw new KDBizException("当前单据已上传PDF套打，禁止再次生成！\n如需再次上传请删除原附件后重试！");
                }
                break;
            }
        }
    }

    private static void previewUrl(IFormView view, String previewUrl) {
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setStatus(OperationStatus.EDIT);
        showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
        showParameter.setFormId("bos_printpreview");
        showParameter.setCustomParam("src", previewUrl);
        view.showForm(showParameter);
    }

    public static DynamicObject uploadAttachmentPanel(String formId, Object pkId, String attachmentKey, String fileName, String url) {
        int size = 10;
        try {
            size = FileServiceFactory.getAttachmentFileService().getInputStream(url).available();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (YEM.isNotEmpty(url)) {
            if (YEM.isEmpty(fileName)) {
                fileName = url.substring(url.lastIndexOf("/") + 1);
            }
            Date today = new Date();
            DynamicObject newAtt = BusinessDataServiceHelper.newDynamicObject("bos_attachment");
            Long id = ORM.create().genLongId("bos_attachment");
            newAtt.set("id", id);
            newAtt.set("fnumber", "upload_" + id);
            newAtt.set("FBillType", formId);
            newAtt.set("FInterID", pkId);
            newAtt.set("FModifyTime", today);
            newAtt.set("fcreatetime", today);
            newAtt.set("FaliasFileName", fileName);
            newAtt.set("FAttachmentName", fileName);
            newAtt.set("FFileId", url);
            newAtt.set("FExtName", fileName.substring(fileName.lastIndexOf(46) + 1));
            newAtt.set("FATTACHMENTSIZE", 100);
            newAtt.set("FCREATEMEN", RequestContext.get().getCurrUserId());
            newAtt.set("fattachmentpanel", attachmentKey);
            newAtt.set("fdescription", "");
            SaveServiceHelper.save(new DynamicObject[]{newAtt});
            return newAtt;
        }
        return null;
    }


    /**
     * 上传临时文件到服务器中
     *
     * @param url
     * @param name
     * @return
     */
    private static String uploadTempfile(String url, String name) {
        TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
        InputStream in = cache.getInputStream(url);
        FileService service = FileServiceFactory.getAttachmentFileService();
        FileService fs = FileServiceFactory.getAttachmentFileService();
        RequestContext requestContext = RequestContext.get();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 生成文件路径-上传附件时远程服务器需要存储文件的位置
        String pathParam = FileNameUtils.getAttachmentFileName(requestContext.getTenantId(),
                requestContext.getAccountId(), uuid, name);
        FileItem fileItem = new FileItem(name, pathParam, in);
        // cache.remove(url);
        // 上传附件到文件服务器
        String downUrl = service.upload(fileItem);
        return downUrl;
    }


    public static Boolean isattachmentpanel(DynamicObject dataEntity, String fileName, String attachmentKey) {
        List<Map<String, Object>> attachmentpanel =
                AttachmentServiceHelper.getAttachments(dataEntity.getDynamicObjectType().getName(), dataEntity.getPkValue(), attachmentKey);
        if ("attachmentpanel".equals(attachmentKey)) {

            if (attachmentpanel.size() > 0) {
                for (int i = 0; i < attachmentpanel.size(); i++) {
                    Map<String, Object> stringObjectMap = attachmentpanel.get(i);
                    String name = (String) stringObjectMap.get("name");
                    if (name.equals(fileName)) {
                        return false;
                    }
                }
            } else {
                return true;
            }
            return true;
        } else {
            if (attachmentpanel.size() > 0) {
//            for (int i = 0; i < attachmentpanel.size(); i++) {
//                Map<String, Object> stringObjectMap = attachmentpanel.get(i);
//                String name = (String) stringObjectMap.get("name");
//                if (name.equals(fileName)) {
                return false;
//                }
//            }
            } else {
                return true;
            }
        }
    }

}
