package com.yem.wm.es.encasement.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.fileservice.FileItem;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.orm.ORM;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.web.actions.utils.FilePathUtil;

/**
 * 附件面板工具类
 *
 * @author longh
 * @description:
 * @date 2021年8月20日 下午4:33:59
 */
public class AttachmentUtil extends FileUtil
{

    public AttachmentUtil(String formId)
    {
        super(formId);
    }

    /**
     * 下载附件到指定附件面板
     *
     * @param appId
     * @param formId
     * @param pkId
     * @param attachmentKey
     * @param fileName
     * @param downloadUrl
     * @throws IOException
     */
    public DynamicObject downloadFile2Attachment(String appId, String formId, String pkId, String attachmentKey, String fileName, String downloadUrl) throws IOException
    {
        return uploadAttachment(appId, formId, pkId, attachmentKey, fileName, this.downloadFile(fileName, downloadUrl));
    }

    /**
     * 下载附件到文件服务器
     *
     * @param appId
     * @param formId
     * @param pkId
     * @param fileName
     * @param downloadUrl
     * @return
     * @throws IOException
     */
    public String downloadFile2FileItem(String appId, String formId, String pkId, String fileName, String downloadUrl) throws IOException
    {
        return uploadFileItem(appId, formId, pkId, fileName, this.downloadFile(fileName, downloadUrl));
    }

    /**
     * 上传附件至附件面板
     *
     * @param appId         应用标识
     * @param formId        单据标识
     * @param pkId          单据内码
     * @param attachmentKey 附件面板标识
     * @param fileName      文件名
     * @param filePath      文件物理地址
     * @return
     * @throws IOException
     */
    public static DynamicObject uploadAttachment(String appId, String formId, String pkId, String attachmentKey, String fileName, String filePath) throws IOException
    {
        Date today = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMM");
        String NewDateStr = df.format(today);
        String attachmentPath = "/" + RequestContext.get().getTenantId() + "/" + RequestContext.get().getAccountId()
                + "/" + NewDateStr + "/" + appId + "/" + formId + "/" + pkId + "/attachments/";
        DynamicObject newAtt = BusinessDataServiceHelper.newDynamicObject("bos_attachment");
        File file = new File(filePath);
        if (file.isFile()) {
            @SuppressWarnings("resource")
            int size = new FileInputStream(file).available();
            FileService fs = FileServiceFactory.getAttachmentFileService();
            String path = attachmentPath + fileName;
            FileItem fi = new FileItem(fileName, path, new FileInputStream(file.getPath()));
            fi.setCreateNewFileWhenExists(true);
            String url = fs.upload(fi);
            Long id = ORM.create().genLongId("bos_attachment");
            if (url != null && !"".equals(url)) {
                newAtt.set("id", id);
                newAtt.set("fnumber", id + "upload_" + formId);
                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 != null ? fileName.substring(fileName.lastIndexOf(46) + 1) : "");
                newAtt.set("FATTACHMENTSIZE", size);
                newAtt.set("FCREATEMEN", RequestContext.get().getCurrUserId());
                newAtt.set("fattachmentpanel", attachmentKey);
                newAtt.set("fdescription", "");
                SaveServiceHelper.save(new DynamicObject[]{newAtt});
            } else {
                new Exception("附件【" + fileName + "】上传失败！");
            }
        }
        return newAtt;
    }

    /**
     * 上传附件至文件服务器
     *
     * @param appId
     * @param formId   单据标识
     * @param pkId     单据内码
     * @param fileName 文件名
     * @param filePath 文件物理地址
     * @return
     * @throws IOException
     */
    public static String uploadFileItem(String appId, String formId, String pkId, String fileName, String filePath) throws IOException
    {
        Date today = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMM");
        String NewDateStr = df.format(today);
        String attachmentPath = "/" + RequestContext.get().getTenantId() + "/" + RequestContext.get().getAccountId()
                + "/" + NewDateStr + "/" + appId + "/" + formId + "/" + pkId + "/attachments/";
        String url = "";
        File file = new File(filePath);
        if (file.isFile()) {
            FileService fs = FileServiceFactory.getAttachmentFileService();
            String path = attachmentPath + fileName;
            FileItem fi = new FileItem(fileName, path, new FileInputStream(file.getPath()));
            fi.setCreateNewFileWhenExists(true);
            url = fs.upload(fi);
            if (url == null || "".equals(url)) {
                new Exception("附件【" + fileName + "】上传失败！");
            }
        }
        return url;
    }

    /**
     * add by zhangh 20230727
     * 源单中的附件面板上传到目标单的附件面板上
     *
     * @param purInBill 源单
     * @param to        目标单
     */
    public static void uploadAttachment(DynamicObject purInBill, DynamicObject to)
    {
        List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachmentsByExport(purInBill.getDataEntityType().getName(),
                purInBill.getLong("id"));
        try {
            for (Map<String, Object> map : attachments) {
                map.put("lastModified", null);
                map.put("url", getPathfromDownloadUrl(URLDecoder.decode(String.valueOf(map.get("url")), "UTF-8")));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        AttachmentServiceHelper.upload(to.getDataEntityType().getName(), to.getLong("id"), "attachmentpanel",
                attachments);
        to.set("tpv_attachmentcon", purInBill.getString("tpv_attachmentcon_tag"));
    }

    /**
     * add by zhangh 20230727
     * 获取文件服务器相对路径
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String getPathfromDownloadUrl(String url) throws IOException
    {
        String path = StringUtils.substringAfter(url, "path=");
        path = URLDecoder.decode(path, "UTF-8");
        return FilePathUtil.dealPath(path, "attach");
    }

    /**
     * add by zhangh 20230727
     * 源单中的附件面板上传到目标单的附件面板上
     *
     * @param purInBill 源单
     * @param to        目标单
     */
    public static void uploadAttachmentPanel(DynamicObject purInBill, DynamicObject to)
    {
        List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachmentsByExport(purInBill.getDataEntityType().getName(),
                purInBill.getLong("id"));
        for (Map<String, Object> map : attachments) {
            DynamicObject newAtt = BusinessDataServiceHelper.newDynamicObject("bos_attachment");
            Date date = new Date();
            Long id = ORM.create().genLongId("bos_attachment");
            newAtt.set("id", id);
            newAtt.set("fnumber", "upload_" + id);
            newAtt.set("FBillType", to.getDataEntityType().getName());
            newAtt.set("FInterID", to.getString("id"));

            newAtt.set("FModifyTime", date);
            newAtt.set("fcreatetime", date);
            newAtt.set("FaliasFileName", map.get("name"));
            newAtt.set("FAttachmentName", map.get("name"));
            newAtt.set("FFileId", map.get("url"));
            newAtt.set("FExtName", "pdf");
            newAtt.set("FATTACHMENTSIZE", map.get("size"));
            newAtt.set("FCREATEMEN", RequestContext.get().getCurrUserId());
            newAtt.set("fattachmentpanel", "attachmentpanel");
            newAtt.set("fdescription", "");
            SaveServiceHelper.save(new DynamicObject[]{newAtt});
        }
    }

    public static DynamicObject uploadAttachmentPanel(String formId, Object pkId, String attachmentKey, String fileName, String url, Long cretor)
    {
        int size = 0;
        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("fcreatemen", "1822390359892689920");//1821094233772156928 本地环境,1822390359892689920//47环境
            newAtt.set("FExtName", fileName.substring(fileName.lastIndexOf(46) + 1));
            newAtt.set("FATTACHMENTSIZE", size);
            //newAtt.set("FCREATEMEN", RequestContext.get().getCurrUserId());
            newAtt.set("fattachmentpanel", attachmentKey);
            newAtt.set("fdescription", "");
            SaveServiceHelper.save(new DynamicObject[]{newAtt});
            return newAtt;
        }
        return null;
    }

    public static DynamicObject uploadAttachmentPanel(String formId, Object pkId, String attachmentKey, String fileName, String url)
    {
        int size = 0;
        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", size);
            newAtt.set("FCREATEMEN", RequestContext.get().getCurrUserId());
            newAtt.set("fattachmentpanel", attachmentKey);
            newAtt.set("fdescription", "");
            SaveServiceHelper.save(new DynamicObject[]{newAtt});
            return newAtt;
        }
        return null;
    }

}
