package com.engine.shuzhi.service.impl;

import com.engine.core.impl.Service;
import com.engine.shuzhi.exception.CustomizeRunTimeException;
import com.engine.shuzhi.service.SzBatchExportService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author:dxfeng
 * @createTime: 2023/06/02
 * @version: 1.0
 */
public class SzBatchExportServiceImpl extends Service implements SzBatchExportService {
    @Override
    public Map<String, Object> downloadResourceFile(List<Long> idList) {
        Map<String, Object> returnMap = new HashMap<>(2);
        if (CollectionUtils.isEmpty(idList)) {
            throw new CustomizeRunTimeException("未选择需要下载的人员信息");
        }
        // 身份证复印件+日期
        String zipFilename = "身份证复印件" + LocalDate.now() + ".zip";

        String outPutPath = GCONST.getRootPath() + "filesystem" + File.separator + "downloadBatchTemp";
        File outPut = new File(outPutPath);
        if (!outPut.exists() && !outPut.isDirectory()) {
            outPut.mkdir();
        }
        outPutPath += File.separator + zipFilename;


        try {
            RecordSet rs = new RecordSet();
            // TODO 调整附件字段
            String sql = "select a.lastname ,a.workcode ,b.field13 as fileId from HrmResource a inner join cus_fielddata b on a.id =b.id and b.scopeid =1 and a.id = ? ";
            ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(Paths.get(outPutPath)));
            byte[] buffer = new byte[1024];
            for (Long userId : idList) {
                String fileId = "";
                String lastname = "";
                String workcode = "";
                rs.executeQuery(sql, userId);
                if (rs.next()) {
                    fileId = rs.getString("fileId");
                    lastname = rs.getString("lastname");
                    workcode = rs.getString("workcode");
                }
                if (StringUtils.isNotBlank(fileId)) {
                    for (String file : fileId.split(",")) {
                        ImageFileManager manager = new ImageFileManager();
                        manager.getImageFileInfoById(Util.getIntValue(file));
                        manager.getImageFileType();
                        InputStream inputStream = manager.getInputStream();
                        // 姓名+工号（身份证）
                        zipOutputStream.putNextEntry(new ZipEntry(lastname + workcode + getFileSuffix(manager.getImageFileName())));
                        int length;
                        while ((length = inputStream.read(buffer)) > 0) {
                            zipOutputStream.write(buffer, 0, length);
                        }
                        inputStream.close();
                        zipOutputStream.closeEntry();
                    }

                }

            }
            zipOutputStream.close();
            returnMap.put("zipFilename", zipFilename);
            returnMap.put("outPutPath", outPutPath);
        } catch (IOException e) {
            new BaseBean().writeLog(e);
            throw new CustomizeRunTimeException(e);
        }
        return returnMap;
    }

    @Override
    public Map<String, Object> downloadContractFile(List<Long> idList) {
        Map<String, Object> returnMap = new HashMap<>(2);
        if (CollectionUtils.isEmpty(idList)) {
            throw new CustomizeRunTimeException("未选择需要下载的人员信息");
        }

        // 合同附件+日期
        String zipFilename = "合同附件" + LocalDate.now() + ".zip";

        String outPutPath = GCONST.getRootPath() + "filesystem" + File.separator + "downloadBatchTemp";
        File outPut = new File(outPutPath);
        if (!outPut.exists() && !outPut.isDirectory()) {
            outPut.mkdir();
        }
        outPutPath += File.separator + zipFilename;

        try {
            RecordSet rs = new RecordSet();
            String sql = "select a.lastname ,a.workcode ,b.fj as fileId,b.htksrq from HrmResource a inner join uf_ygqdhtbd b on a.id =b.xm where b.id = ?";
            ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(Paths.get(outPutPath)));
            byte[] buffer = new byte[1024];
            for (Long id : idList) {
                String docId = "";
                String lastname = "";
                String workcode = "";
                String htksrq = "";
                rs.executeQuery(sql, id);
                if (rs.next()) {
                    docId = rs.getString("fileId");
                    lastname = rs.getString("lastname");
                    workcode = rs.getString("workcode");
                    htksrq = rs.getString("htksrq");
                }
                if (StringUtils.isNotBlank(docId)) {
                    for (String doc : docId.split(",")) {
                        rs.executeQuery("select imagefileid  from DocImageFile where docid = ?", doc);
                        String file = "";
                        if (rs.next()) {
                            file = rs.getString("imagefileid");
                        }
                        if (StringUtils.isBlank(file)) {
                            continue;
                        }
                        ImageFileManager manager = new ImageFileManager();
                        manager.getImageFileInfoById(Util.getIntValue(file));
                        manager.getImageFileType();
                        InputStream inputStream = manager.getInputStream();
                        // 姓名+工号+开始日期（合同）
                        zipOutputStream.putNextEntry(new ZipEntry(lastname + workcode + htksrq + getFileSuffix(manager.getImageFileName())));
                        int length;
                        while ((length = inputStream.read(buffer)) > 0) {
                            zipOutputStream.write(buffer, 0, length);
                        }
                        inputStream.close();
                        zipOutputStream.closeEntry();
                    }

                }

            }
            zipOutputStream.close();
            returnMap.put("zipFilename", zipFilename);
            returnMap.put("outPutPath", outPutPath);
        } catch (IOException e) {
            new BaseBean().writeLog(e);
            throw new CustomizeRunTimeException(e);
        }
        return returnMap;
    }


    /**
     * 获取文件名后缀
     *
     * @param sourceName
     * @return
     */
    private String getFileSuffix(String sourceName) {
        if (StringUtils.isBlank(sourceName) || !sourceName.contains(".")) {
            return "";
        }
        return sourceName.substring(sourceName.lastIndexOf('.'));
    }
}
