package com.persagy.adm.server.backstage.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSONObject;
import com.persagy.adm.server.algorithm.constant.AdmModelFileStatusEnum;
import com.persagy.adm.server.algorithm.entity.AdmModelFile;
import com.persagy.adm.server.backstage.domain.AdmAnalysisModel;
import com.persagy.dmp.file.utils.FileStorageHelper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipInputStream;

/**
 * 解压模型文件
 * @author : lijie
 * Update By 2022/1/21 15:36
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AdmUnzipFileServiceImpl extends AdmAnalysisServiceBase {

    @Override
    protected void analysisInternal(AdmAnalysisModel model) {
        // 遍历模型文件
        for (AdmModelFile admModelFile : model.getAdmModelFiles()) {
            if (StrUtil.isBlank(admModelFile.getDataFileId())){
                continue;
            }
            // 2.1 从文件服务下载jsonz文件
            JSONObject dataObj = unzipDataModelFile(FileStorageHelper.downloadStream(admModelFile.getDataFileId()));
            if (ObjectUtil.isNull(dataObj)){
                admModelFile.setRemoved(Boolean.TRUE);
                continue;
            }
            model.setCurrentAdmModelObj(dataObj);
            model.setCurrentModelFile(admModelFile);
            model.setCurrentFloor(model.getFloorMap().get(admModelFile.getFloorId()));
            getNext().analysis(model);
            admModelFile.setStatus(AdmModelFileStatusEnum.NORMAL_COMPLETED.getValue());
        }
    }

    /**
     * 解压数据文件流
     * @param inputStream :数据文件流
     * @return : java.util.Map<java.lang.String,com.alibaba.fastjson.JSONObject>
     * @author : lijie
     * Update By 2022/1/17 11:59
     */
    private JSONObject unzipDataModelFile(InputStream inputStream) {
        Map<String, byte[]> byteMap = unzipDataModelFileToByteArray(inputStream);
        Set<String> keySet = byteMap.keySet();
        Map<String, JSONObject> resultMap = MapUtil.newHashMap(keySet.size());
        for (String key : keySet) {
            byte[] bytes = byteMap.get(key);
            if (null==bytes || bytes.length<=0){
                continue;
            }
            return JSONObject.parseObject(StrUtil.str(bytes, StandardCharsets.UTF_8));
        }
        return null;
    }
    /**
     * 解压文件到字节流
     * @param inputStream : 数据文件流
     * @return : java.util.Map<java.lang.String,java.io.ByteArrayInputStream>
     * @author : lijie
     * Update By 2022/1/17 12:02
     */
    @SneakyThrows
    private Map<String, byte[]> unzipDataModelFileToByteArray(InputStream inputStream){
        if (null==inputStream){
            return new HashMap<>(0);
        }
        Map<String, byte[]> resultMap = MapUtil.newHashMap();
        ZipInputStream zipInputStream = new ZipInputStream(inputStream, Charset.forName("GBK"));
        ZipUtil.read(zipInputStream, zipEntry -> {
            if (zipEntry.isDirectory()){
                return;
            }
            resultMap.put(zipEntry.getName(), IoUtil.readBytes(zipInputStream,false));
        });
        return resultMap;
    }

}
