package com.xxfc.platform.universal.service.impl;

import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.xxfc.platform.universal.constant.RedisKey;
import com.xxfc.platform.universal.constant.enumerate.FileTypeEnum;
import com.xxfc.platform.universal.service.UploadZipService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.plexus.util.IOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

@Slf4j
@Service
public class UploadZipServiceImpl implements UploadZipService {

    @Value("${universal.uploadPath}")
    private String uploadPath ;

    @Value("${universal.url}")
    private String xx_url ;
    @Value("${photo.format}")
    private  String PHOTO_FORMAT;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ObjectRestResponse uploadPictureZip(MultipartFile uFile, String prefix) throws IOException {
        if (Objects.isNull(uFile)) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"请上传压缩文件!");
        }
        String fileContentType = uFile.getContentType();
        //将压缩包保存在指定路径
        String packFilePath = uploadPath + File.separator + uFile.getName();
        if (FileTypeEnum.FILE_TYPE_ZIP.type.equals(fileContentType)||FileTypeEnum.FILE_TYPE_X_ZIP.type.equals(fileContentType)) {
            //zip解压缩处理
            packFilePath += FileTypeEnum.FILE_TYPE_ZIP.fileStufix;
        } else {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"上传的压缩包格式不正确,仅支持zip压缩文件!");
        }
        File file = new File(packFilePath);
        try {
            //保存压缩包
            FileOutputStream os = new FileOutputStream(file);
            IOUtil.copy(uFile.getInputStream(),os);
            os.close();
        } catch (IOException e) {
            log.error("zip file save to " + uploadPath + " error", e.getMessage(), e);
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"保存压缩文件到:" + uploadPath + " 失败!");
        }
        //zip压缩包解压
        return   unPackZip(file, prefix);

    }

    public ObjectRestResponse<String> unPackZip(File file, String prefix) throws IOException {
        ZipFile zipFile = new ZipFile(file, Charset.forName("GBK"));
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        long millis = System.currentTimeMillis();
        String dirPathToday = prefix+ File.separator + millis;
        String redisNoKey = RedisKey.UPLOAD_FILE_NO_PREFIX +millis;
        StringBuffer result = new StringBuffer();
        Integer index = 0;
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory() && index++ == 0) {
                File dir = new File(uploadPath+File.separator+dirPathToday);
                dir.mkdir();
            } else if (!entry.isDirectory()) {

                Long no = redisTemplate.opsForValue().increment(redisNoKey);
                if(no.equals(1l)){
                    redisTemplate.expire(redisNoKey,1, TimeUnit.DAYS);
                }
                String name = entry.getName();
                String format = name.substring(name.lastIndexOf("."));
                if (PHOTO_FORMAT.contains(format)) {
                    String realFileRelPath = dirPathToday + File.separator + no +format;
                    File targetFile = new File(uploadPath+File.separator+realFileRelPath);
            //        FileUtils.copyInputStreamToFile(zipFile.getInputStream(entry),targetFile);
                    realFileRelPath=xx_url+ SystemConfig.RENOVATE+File.separator+realFileRelPath;
                    result.append(realFileRelPath+",");
                }
            }
        }

        if (StringUtils.isNotEmpty(result.toString())) {
            result.substring(0,result.length()-1);
            return ObjectRestResponse.succ(result.substring(0, result.length()-1));
        }
       return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"压缩包中无照片或照片格式不对!");
    }
}
