package com.hzya.frame.grpU8.nxproof.attachment.service.impl;/*
* @Description
* @Author xiangerlin 
  @Date 2022-10-26 11:20
*/

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.grpU8.nxproof.attachment.dao.IAttachmentFileDao;
import com.hzya.frame.grpU8.nxproof.attachment.entity.AttachmentFileEntity;
import com.hzya.frame.grpU8.nxproof.attachment.service.IAttachmentFileService;
import com.hzya.frame.grpU8.nxproof.oerannex.entity.OerAnnexEntity;
import com.hzya.frame.grpU8.nxproof.oerannex.service.IOerAnnexService;
import com.hzya.frame.grpU8.nxproof.oerdjml.dto.FileInfoDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class AttachmentFileServiceImpl extends BaseService<AttachmentFileEntity,String> implements IAttachmentFileService {

    Logger logger = LogManager.getLogger(getClass());

    protected IAttachmentFileDao attachmentFileDao;

    @Autowired
    public void setBillLogDao(IAttachmentFileDao dao) {
        this.attachmentFileDao = dao;
        this.dao=dao;
    }
    @Autowired
    private IOerAnnexService oerAnnexService;
    /**
     * 保存附件
     * @param entity
     */
    @Override
    public void saveAttachment(AttachmentFileEntity entity) {
        entity.setaTGuid("A1:"+IdUtil.fastUUID());
        String date = DateUtil.format(new Date(), "yyyyMMdd HH:mm:ss");
        entity.setCreateDate(date);
        entity.setUpdateDate(date);
        String fileName = entity.getaTFileName();
        if (StrUtil.isNotEmpty(fileName)){
            int index = fileName.lastIndexOf(".");
            if (index > 0){
                String suffix = fileName.substring(index);
                entity.setaTExtName(suffix);
                String prefix = fileName.substring(0,index);
                entity.setaTFileName(prefix);
            }
        }
        attachmentFileDao.save("AttachmentFileEntity_insert",entity);
    }

    @Override
    public List<AttachmentFileEntity> queryFile(AttachmentFileEntity entity) throws Exception {
        List<AttachmentFileEntity> list = attachmentFileDao.query(entity);
        return list;
    }

    /**
     * 调用http接口查询单据附件
     *
     * @param billCode 单据号
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> queryFileByCode(String billCode) throws Exception {
        List<JSONObject> list = new ArrayList<>();
        if (StrUtil.isNotEmpty(billCode)){
            JSONObject params = new JSONObject();
            params.put("billNo",billCode);
            String res = HttpRequest.post("/grp/af/findFilesBB").body(params.toString()).execute().body();
            logger.info("根据单号:{},查询到到附件列表为:{}",billCode,res);
            if (StrUtil.isNotEmpty(res)){
                JSONObject resJson = JSONObject.parseObject(res);
                int pageCount = resJson.getIntValue("pageCount");
                boolean success = resJson.getBoolean("success");
                if (success){
                    String dataStr = resJson.getString("data");
                    list = JSONObject.parseArray(dataStr,JSONObject.class);
                    if (null != list && list.size() >0){
                        for (JSONObject jsonObject : list) {
                            String fileName = jsonObject.getString("fileName");
                            if (StrUtil.isNotEmpty(fileName)){
                                // 使用indexOf找到"."的位置
                                int dotIndex = fileName.lastIndexOf('.');
                                // 确保找到了"."，防止indexOf返回-1的情况
                                if (dotIndex != -1){
                                    String ext_name = fileName.substring(dotIndex);
                                    jsonObject.put("Ext",ext_name);
                                }
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 附件上传
     *
     * @param fileList
     * @param mlid
     * @param kjnd
     */
    @Override
    public void uploadAttachment(List<JSONObject> fileList, String mlid, String kjnd) {
        if (CollectionUtils.isNotEmpty(fileList) && StrUtil.isNotEmpty(mlid) && StrUtil.isNotEmpty(kjnd)){
            try {
                //附件下载
                List<FileInfoDTO> fileInfoList = fileDownload(fileList);
                //附件保存到grp库里
                if (CollectionUtils.isNotEmpty(fileInfoList)){
                    //保存前先删一下历史附件
                    OerAnnexEntity delete = new OerAnnexEntity();
                    //delete.setGsdm(Constant.CONFIGMAP.get("gsdm"));
                    delete.setKjnd(kjnd);
                    delete.setMlid(mlid);
                    //oerAnnexService.deleteAnnex(delete);
                    int no = 1;
                    for (FileInfoDTO fileInfo : fileInfoList) {
                        try {
                            AttachmentFileEntity fileEntity = new AttachmentFileEntity();
                            String fileName = URLDecoder.decode(fileInfo.getFile_name(), "UTF-8");
                            fileEntity.setaTFileName(fileName);
                            fileEntity.setaTFile(fileInfo.getData());
                            this.saveAttachment(fileEntity);
                            //保存附件关系
                            OerAnnexEntity annexEntity = new OerAnnexEntity();
                            annexEntity.setMlid(mlid);
                            annexEntity.setKjnd(kjnd);
                            annexEntity.setAnnexName(fileName);
                            annexEntity.setAnnexSize(Convert.toLong(fileInfo.getFile_size()));
                            annexEntity.setOnlyid(fileEntity.getaTGuid());
                            annexEntity.setXh(String.valueOf(no));
                            oerAnnexService.saveAnnex(annexEntity);
                            no++;
                        }catch (Exception e){
                            logger.error("保存附件到grp出错:{}",e);
                        }
                    }
                }
            }catch (Exception e){
                logger.error("保存附件到grp出错:{}",e);
            }
        }
    }

    private List<FileInfoDTO> fileDownload(List<JSONObject> fileList){
        String dir = "1";
        List<FileInfoDTO> files = new ArrayList<>();
        //1、下载附件
        for (JSONObject fileObj : fileList) {
            try {
                FileInfoDTO fileInfoDTO = new FileInfoDTO();
                String url = fileObj.getString("url");
                String fileName = URLDecoder.decode(fileObj.getString("fileName"));
                File file = HttpUtil.downloadFileFromUrl(url, dir);
                if (null != file){
                    String zipPath = dir + File.separator + fileName.split("\\.")[0] + ".zip";
                    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath), Charset.forName("GBK"));
                    writeZipFile(file, zos,fileName);
                    zos.close();
                    // 获取压缩文件的字节数组
                    File zipFile = new File(zipPath);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream((int) zipFile.length());
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(zipFile));
                    int buf_size = 1024;
                    byte[] buffer = new byte[buf_size];
                    int len = 0;
                    while (-1 != (len = bufferedInputStream.read(buffer, 0, buf_size))) {
                        byteArrayOutputStream.write(buffer, 0, len);
                    }
                    byte[] fileByte = byteArrayOutputStream.toByteArray();
                    fileInfoDTO.setData(fileByte);
                    fileInfoDTO.setFile_size(fileObj.getString("size"));
                    fileInfoDTO.setFile_name(fileName);
                    files.add(fileInfoDTO);
                }
            }catch (Exception e){
                logger.error("上传附件出错:{}",e);
            }
        }
        return files;
    }
    private void writeZipFile(File file,ZipOutputStream zos,String fileName){
        if (null != file && null !=zos){
            try {
                logger.info("=====压缩文件=====");
                zos.putNextEntry(new ZipEntry(fileName));
                FileInputStream fos = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fos);
                int len;
                byte[] buf = new byte[1024];
                while ((len = bis.read(buf, 0, 1024)) != -1) {
                    zos.write(buf, 0, len);
                }
                bis.close();
                fos.close();
                logger.info("=====压缩完成=====");
            }catch (Exception e){
                e.printStackTrace();
                logger.error("=====压缩文件出错=====");
            }
        }
    }
}
