package com.weaver.seconddev.chapanda.hrm.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.authority.annotation.WeaPermission;
import com.weaver.common.base.entity.result.WeaResult;
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.constant.DownLoadTypeEnum;
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.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.Base64;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/secondev/chapanda/hrm/info")
public class HrmInformationFilesController {

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

    @Autowired
    private FileDownloadService fileDownloadService;

    @Autowired
    HrmDownloadFilesService hrmDownloadFilesService;

    @WeaPermission(publicPermission = true)
    @PostMapping("/getinformationpath")
    public WeaResult<Object> getInformationPath(@RequestBody Map<String,Object> paramMap){
        String data = String.valueOf(paramMap.get("data"));
        log.error("data:{}",data);
        JSONArray dataArray = new JSONArray();
        if(StringUtils.isNotBlank(data)){
            String decodedData = hrmDownloadFilesService.convertBase64Data(data);
            log.error("decodedData:{}",decodedData);
            if(StringUtils.isNotBlank(decodedData)){
                try{
                    dataArray = JSONArray.parseArray(decodedData);
                }catch (Exception e){
                    log.error("{}",e);
                }
            }
        }
        log.error("dataArray:{}",dataArray.size());

        String newZipFilePath = convertZipFile(dataArray, DownLoadTypeEnum.INFORMATION.getCode());

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//        String filename = sdf.format(new Date())+".zip";
//
//        String directoryPath = Constants.templatePath+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;
//        try {
//            log.error("path:{}",zipFilePath);
//            FileOutputStream fos = new FileOutputStream(zipFilePath);
//            ZipOutputStream zos = new ZipOutputStream(fos);
//            for(int i=0;i<dataArray.size();i++){
//                JSONObject  dataObject = dataArray.getJSONObject(i);
//                String jobNum = dataObject.getString("jobnum");
//                String userName = dataObject.getString("username");
//                String fileId = dataObject.getString("fileid");
//
//                log.error("fileId:{}",fileId);
//                log.error("userName:{}",userName);
//                log.error("jobNum:{}",jobNum);
//
//                if(StringUtils.isNotBlank(fileId)){
//                    try {
//                        FileData fileData = fileDownloadService.downloadFile(Long.parseLong(fileId));
//                        FileObj fileObj = fileData.getFileObj();
//                        // 获取文件的输入流
//                        InputStream 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,jobNum,userName);
//                    } catch (IOException e) {
//                        log.error("e:" , e);
//                    }
//                }
//            }
//
//            zos.close();
//            fos.close();
//        }catch (IOException e){
//            log.error("e:{}",e);
//        }

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

        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("filepath",newZipFilePath);
        return WeaResult.success(dataMap);
    }


    /***
     * 转换为zip文件
     * @param dataArray
     * @param downloadType
     * @return
     */
    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 jobNum = dataObject.getString("jobnum");
                String userName = dataObject.getString("username");
                String fileId = dataObject.getString("fileid");

                log.error("fileId:{}",fileId);
                log.error("userName:{}",userName);
                log.error("jobNum:{}",jobNum);

                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,jobNum,userName);

                        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;
    }

    /***
     * 电子签名模板预览接口
     * @return
     * @throws IOException
     */
    @WeaPermission(publicPermission = true)
    @GetMapping("/downloadZip")
    public ResponseEntity downloadZip(HttpServletRequest request) throws IOException{
        String data = request.getParameter("data");
        String type = request.getParameter("type");
        log.error("data2:{}",data);
        log.error("typ2e:{}",type);
        String filename = "";
        try{
            DownLoadTypeEnum[] values = DownLoadTypeEnum.values();
            for (DownLoadTypeEnum item : values) {
                log.error("item.getCode():{}",item.getCode());
                if(item.getCode().equals(type)){
                    filename = DownLoadTypeEnum.INCOME.getFileName();
                }
            }
            if(StringUtils.isNotBlank(filename)){
                filename = URLEncoder.encode(filename, "UTF-8");  // 使用UTF-8编码
            }
        }catch (Exception e){
            log.error("e:{}",e);
        }
        String zipFilePath = "";
        if(StringUtils.isNotBlank(data)){
            zipFilePath = hrmDownloadFilesService.convertBase64Data(data);
        }
        if(StringUtils.isNotBlank(filename)){
            log.error("zipFilePath:{}",zipFilePath);
            if(StringUtils.isNotBlank(zipFilePath) && zipFilePath.contains(Constants.templatePath) && new File(zipFilePath).exists()){
                // 文件转成字节数组
                File file = ResourceUtils.getFile(zipFilePath);
                byte[] fileBytes = Files.readAllBytes(file.toPath());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String filename2 = filename+"-"+sdf.format(new Date())+".zip";
                return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + new String(filename2.getBytes(), "UTF-8") + "\"")
                        .body(fileBytes);
            }else{
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new String("文件下载失败".getBytes(), "utf-8"));
            }
        }else{
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new String("文件下载失败".getBytes(), "utf-8"));
        }
    }

    // 将文件添加到zip输出流
    private void addFileToZip(ZipOutputStream zos, byte[] fileData, String entryName,String jobNum,String fileName) throws IOException {
        ZipEntry entry = new ZipEntry(fileName+"_"+jobNum+"/"+entryName);
        zos.putNextEntry(entry);
        zos.write(fileData);
        zos.closeEntry();
    }
    /**
     * 测试接口
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @WeaPermission(publicPermission = true)
    @GetMapping("/test")
    public WeaResult<Object> test(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> recordMap = new HashMap<String,Object>();
        recordMap.put("test","test");
        return WeaResult.success(recordMap);
    }


    public static void main(String[] args) {
        String originalString = "/nfs/data/weatempfiles/downloadtemp/1111/1111.zip";

        //
//        String originalString = "[{\"fielid\":\"1169600692452909062\",\"jobnum\":\"10000000000\",\"username\":\"王文猛\"},{\"fielid\":\"1169600688166330369\",\"jobnum\":\"10000000000\",\"username\":\"王文猛\"},{\"fielid\":\"1167396240209780739\",\"jobnum\":\"1000002229\",\"username\":\"崔晓龙\"},{\"fielid\":\"1167650515133440001\",\"jobnum\":\"1000002805\",\"username\":\"刘琪琪\"},{\"fielid\":\"1167395969819779075\",\"jobnum\":\"1000003958\",\"username\":\"刘颖慧\"},{\"fielid\":\"1169538849218813953\",\"jobnum\":\"1000003958\",\"username\":\"刘颖慧\"},{\"fielid\":\"1169601053305659394\",\"jobnum\":\"1000003958\",\"username\":\"刘颖慧\"},{\"fielid\":\"1169543698203336705\",\"jobnum\":\"1000003958\",\"username\":\"刘颖慧\"},{\"fielid\":\"1169501139481452545\",\"jobnum\":\"1000004336\",\"username\":\"蒋欢\"},{\"fielid\":\"1167403559018602499\",\"jobnum\":\"1000004410\",\"username\":\"刘贤松\"},{\"fielid\":\"1167394818600771585\",\"jobnum\":\"1000004846\",\"username\":\"刘刚菊\"},{\"fielid\":\"1167389900896772097\",\"jobnum\":\"1000006146\",\"username\":\"周娟\"},{\"fielid\":\"1169540279359037441\",\"jobnum\":\"1000006146\",\"username\":\"周娟\"},{\"fielid\":\"1167718573191520257\",\"jobnum\":\"1000006146\",\"username\":\"周娟\"}]";
        // 将字符串转换为字节数组
        byte[] bytesToEncode = originalString.getBytes();

        // 创建Base64编码器
        Base64.Encoder encoder = Base64.getEncoder();

        // 编码字节数组
        String encodedString = encoder.encodeToString(bytesToEncode);

        System.out.println("Encoded String: " + encodedString);

        Base64.Decoder decoder = Base64.getDecoder();

        // 解码Base64字符串
        byte[] bytesDecoded = decoder.decode(encodedString);

        // 将字节数组转换回字符串
        String decodedString = new String(bytesDecoded);

        System.out.println("Decoded String: " + decodedString);

    }

}
