package com.weaver.seconddev.chapanda.hrm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.eteams.file.client.file.FileData;
import com.weaver.eteams.file.client.file.FileObj;
import com.weaver.file.ud.api.FileDownloadService;
import com.weaver.seconddev.chapanda.hrm.constant.Constants;
import com.weaver.seconddev.chapanda.hrm.service.HrmDownloadFilesService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/***
 * author:shil
 */

@Service
public class HrmDownloadFilesServiceImpl implements HrmDownloadFilesService {

    private final static Logger log = LoggerFactory.getLogger(HrmDownloadFilesServiceImpl.class);

    @Autowired
    HrmDownloadFilesService hrmDownloadFilesService;

    @Autowired
    private FileDownloadService fileDownloadService;

    /***
     * 将InputStream转换为byte[]
     * @param inputStream
     * @return
     */
    public byte[] convertInputStreamToBytes(InputStream inputStream) {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        try{
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteStream.write(buffer, 0, bytesRead);
            }
            log.error("byteStream:{}",byteStream.toByteArray().length);
        }catch (IOException e) {
            log.error("e:{}",e.getMessage());
        }
        return byteStream.toByteArray();
    }

    /***
     *
     * @param base64Data
     * @return
     */
    @Override
    public String convertBase64Data(String base64Data) {
        String decodedData = "";
        try{
            Base64.Decoder decoder = Base64.getDecoder();
            // 解码Base64字符串
            byte[] bytesDecoded = decoder.decode(base64Data);
            // 将字节数组转换回字符串
            decodedData = new String(bytesDecoded, StandardCharsets.UTF_8);
        }catch (Exception e){
            log.error("e:{}",e);
        }
       return decodedData;
    }


    public String convertZipFile(JSONArray dataArray,String downloadType) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String filename = sdf.format(new Date())+".zip";

        String directoryPath = Constants.templatePath+ File.separator+downloadType+File.separator+sdf.format(new Date());
        // 将字符串路径转换为Path对象
        Path path = Paths.get(directoryPath);
        // 检查目录是否存在
        if (Files.notExists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                log.error("e:{}",e);
            }
        }

        String zipFilePath = directoryPath+File.separator+filename;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            log.error("path:{}",zipFilePath);
            fos = new FileOutputStream(zipFilePath);
            zos = new ZipOutputStream(fos);
            for(int i=0;i<dataArray.size();i++){
                JSONObject dataObject = dataArray.getJSONObject(i);
                String fileId = dataObject.getString("fileid");
                log.error("fileId:{}",fileId);
                if(StringUtils.isNotBlank(fileId)){
                    InputStream inputStream = null;
                    try {
                        FileData fileData = fileDownloadService.downloadFile(Long.parseLong(fileId));
                        FileObj fileObj = fileData.getFileObj();
                        // 获取文件的输入流
                        inputStream = fileData.getInputStream();
                        log.error("inputStream:{}",inputStream.available());
                        String fileName = fileObj.getName();
                        log.error("fileName:{}",fileName);
                        byte[] filedata = hrmDownloadFilesService.convertInputStreamToBytes(inputStream);

                        addFileToZip(zos, filedata, fileName);

                        inputStream.close();
                    } catch (IOException e) {
                        log.error("e:" , e);
                    }finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    }
                }
            }
            zos.close();
            fos.close();
        }catch (IOException e){
            log.error("e:{}",e);
        }finally {
            try {
                if (zos != null) {
                    zos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("e:{}",e);
            }
        }

        String newZipFilePath = "";
        File zipFile = new File(zipFilePath);
        if(zipFile.exists()){
            newZipFilePath = zipFile.getPath();
        }
        return newZipFilePath;
    }

    // 将文件添加到zip输出流
    private void addFileToZip(ZipOutputStream zos, byte[] fileData, String entryName) throws IOException {
//        ZipEntry entry = new ZipEntry(fileName+"_"+jobNum+"/"+entryName);
        ZipEntry entry = new ZipEntry(entryName);
        zos.putNextEntry(entry);
        zos.write(fileData);
        zos.closeEntry();
    }

    public static void main(String[] args) {
        String data = "L25mcy9kYXRhL3dlYXRlbXBmaWxlcy9kb3dubG9hZHRlbXAvcmVzaWduLzIwMjUwODI2MTczNjU3L+emu+iBjOivgeaYji0yMDI1MDgyNjE3MzY1Ny56aXA=";
        HrmDownloadFilesServiceImpl HrmDownloadFilesServiceImpl = new HrmDownloadFilesServiceImpl();
        String decodedData = HrmDownloadFilesServiceImpl.convertBase64Data(data);
        System.out.println(decodedData);
    }

}
