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.xxfc.platform.universal.constant.enumerate.FileTypeEnum;
import com.xxfc.platform.universal.service.FileUploadService;
import com.xxfc.platform.universal.utils.UnPackeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;


@Service
@Slf4j
public class FileUploadServiceImpl  implements FileUploadService {

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

    private static final String APK_SUFFIX=".apk";
    private static final String APK_NAME="xxfc.apk";

    @Override
    public ObjectRestResponse handlerUpload(MultipartFile zipFile,String password,String prefix)throws Exception {
        if (null == zipFile) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"请上传压缩文件!");
        }
        boolean isZipPack = true;
        String fileContentType = zipFile.getContentType();
        //将压缩包保存在指定路径
        String packFilePath = uploadPath + File.separator + zipFile.getName();
        if (FileTypeEnum.FILE_TYPE_ZIP.type.equals(fileContentType)) {
            //zip解压缩处理
            packFilePath += FileTypeEnum.FILE_TYPE_ZIP.fileStufix;
        } else if (FileTypeEnum.FILE_TYPE_RAR.type.equals(fileContentType)) {
            //rar解压缩处理
            packFilePath += FileTypeEnum.FILE_TYPE_RAR.fileStufix;
            isZipPack = false;
        } else {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"上传的压缩包格式不正确,仅支持rar和zip压缩文件!");
        }
        File file = new File(packFilePath);
        try {
            zipFile.transferTo(file);
        } catch (IOException e) {
            log.error("zip file save to " + uploadPath + " error", e.getMessage(), e);
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"保存压缩文件到:" + uploadPath + " 失败!");
        }
        if (isZipPack) {
            //zip压缩包
            UnPackeUtil.unPackZip(file, password, uploadPath);
        } else {
            //rar压缩包
            UnPackeUtil.unPackRar(file, uploadPath);
        }

        String path=readZipFile(packFilePath);
        if (StringUtils.isNotBlank(path)){
            String filename = path;
            path=xx_url+"/"+prefix+"/"+path;
               log.info("文件名：{}",path);
                if (filename.contains(APK_SUFFIX)){
                    Runtime runtime = Runtime.getRuntime();
                    log.info("执行删除xxfc.apk");
                    //删除包
                    runtime.exec("rm -rf  "+uploadPath+"/"+APK_NAME);
                    log.info("执行复制上传包为xxfc.apk");
                    //复制包
                    runtime.exec("cp -f  "+uploadPath+"/"+filename+"  "+uploadPath+"/"+APK_NAME);
            }
            return ObjectRestResponse.succ(path);
        }else {
            return ObjectRestResponse.createDefaultFail();
        }

    }

    public static String readZipFile(String file) throws Exception {
        ZipFile zf = new ZipFile(file);
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry ze;
        String path=null;
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                path= ze.getName();
            }
        }
        zin.closeEntry();
        return path;
    }



}
