package com.kingdee.eas.custom.sendmessage.utils;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.eas.base.attachment.AttachmentFactory;
import com.kingdee.eas.base.attachment.AttachmentInfo;
import com.kingdee.eas.base.attachment.AttachmentManagerFacadeFactory;
import com.kingdee.eas.base.attachment.IAttachmentManagerFacade;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.rpts.ctrlreport.osf.OSFExecutor;
import com.kingdee.shr.certificationservice.HRCertificationBillInfo;
import com.kingdee.util.StringUtils;

import javax.servlet.ServletOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

/**
 * 获取附件并保存到磁盘
 */
public class SaveFileForDisk {
//    private static String HOME_URL = "https://shr-test.gooeto.com:6888/";
    private static Properties propt = new Properties();
   
    
    
    private static void setUrlPath() throws BOSException {
    	String syncOAConfigPath = System.getProperty("EAS_HOME") + "/server/properties/gyt/sendMessage.properties";
        try {
            propt.load(Files.newBufferedReader(Paths.get(syncOAConfigPath), StandardCharsets.UTF_8));
            //propt.load(new FileInputStream(syncOAConfigPath));
        } catch (IOException e) {
            e.printStackTrace();
            String errorMsg = "获取配置文件报错，请检查配置：" + syncOAConfigPath + "   " + e.getMessage();
            throw new BOSException(errorMsg);
        }
    }
    
    /**
     * 获取pdf对应的信息
     * elecProofInfo 为证明单据
     * @param ctx
     * @param elecProofInfo
     * @return
     * @throws BOSException
     * @throws EASBizException
     * @throws IOException
     */
    public static Map<String,String>  getPDFInfo(Context ctx, HRCertificationBillInfo elecProofInfo ) throws BOSException, EASBizException, IOException {
    	setUrlPath();
    	Map<String,String> resultMap = new HashMap();
        //获取证明号
        String signNo = StringUtils.cnulls(elecProofInfo.getSignNO());
        //签署完成后，调用osf服务，预览证明
        String billId = StringUtils.cnulls(elecProofInfo.getId());
        //调用osf服务
        HashMap param = new HashMap<String,String>();
        param.put("contractNo", signNo);
        param.put("billId",  billId);
        param.put("isDefault", "1");
        Map<String, Object> result = (Map<String, Object>) OSFExecutor.executeOSF(ctx, param, "empPreViewECertificationV2Service");
        boolean  isSucc = (Boolean)result.get("isSuccess");
        String returnUrl = StringUtils.cnulls( result.get("returnUrl") );
        //如果成功则把证件放入磁盘;
        if(isSucc) {
            String folderName =  createFolderName();
            String fileName =  getPDFToDisk(ctx, returnUrl, folderName);
            //发送消息
            String urlPath  = propt.getProperty("shrPath")+"?sole="+folderName+"&fname="+fileName;
            //文件夹名
            resultMap.put("dirName",folderName);
            //文件名
            resultMap.put("fileName",fileName);
            //url路径
            resultMap.put("urlPath",urlPath);
        }
        return resultMap;
    }

    public static  String  getPDFToDisk(Context ctx, String attachId, String dirName) throws IOException {

        String home = System.getProperty("EAS_HOME"); // 获取 EAS 根目录
        String fileDir = home+"/server/deploy/easweb.ear/shr_web.war/tmp/electronicAttachment/"+ dirName;
        fileDir = fileDir.replace("\\", "/"); //
        ServletOutputStream outputStream = null;
        OutputStream fileOutputStream = null; // 创建文件输出流
        try {
//            AttachmentInfo ai = AttachmentFactory.getLocalInstance(ctx).getAttachmentInfo(new ObjectUuidPK(attachId));
//            String fileName = ai.getName();
//            String simpleName = ai.getSimpleName();
        	String fileName = createFolderName()+".pdf";
        	IAttachmentManagerFacade iAttachmentManagerFacade = AttachmentManagerFacadeFactory.getLocalInstance(ctx);
            byte[] content = iAttachmentManagerFacade.downLoad(attachId);

            // 确保输出目录存在
            File directory = new File(fileDir);
            if (!directory.exists()) {
                directory.mkdirs(); // 创建目录
            }
            
            // 指定文件的完整路径
            File file = new File(directory, fileName);
            fileOutputStream = new FileOutputStream(file); // 创建文件输出流
            fileOutputStream.write(content); // 将内容写入文件
            fileOutputStream.flush();
            return fileName;

        } catch (EASBizException | BOSException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close(); // 关闭文件输出流
                }
                if (outputStream != null) {
                    outputStream.close(); // 关闭 Servlet 输出流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    public static String createFolderName () {
        //使用uuid生成一个8位数的随机字符串作为文件夹名
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
    }

}
