package com.artfess.yhxt.basedata.manager.impl;

import cn.hutool.core.io.IoUtil;
import com.artfess.base.model.CommonResult;
import com.artfess.base.util.FileUtil;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.util.ZipUtil;
import com.artfess.file.util.CheckFileFormatUtil;
import com.artfess.file.util.MinioUtil;
import com.artfess.uc.exception.BaseException;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.basedata.dao.AccessoryDao;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.jsonwebtoken.lang.Assert;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 附件表 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author wangping
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-08-03
 */
@Service
public class AccessoryManagerImpl extends BaseManagerImpl<AccessoryDao, Accessory> implements AccessoryManager {

    @Override
    public String minioDrawingUpload(MultipartFile file, String sourceId) {
        Accessory accessory = new Accessory();
        accessory.setSourceId(sourceId);
        if (file.isEmpty() || file.getSize() == 0) {
            throw new RuntimeException("文件为空");
        }

        try {

            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            accessory.setName(fileName);
            String name = DigestUtils.md5Hex(UUID.randomUUID().toString()) + fileName.substring(fileName.lastIndexOf("."));

            String url = MinioUtil.upload(file, "drawing", name, "yhxt");
            //验证图片类型
            String ext = CheckFileFormatUtil.getFileType((FileInputStream) file.getInputStream());
            System.out.println(ext);
            accessory.setType(ext);
            accessory.setSuffix(ext);
            accessory.setUrl(url);
            accessory.setIsDele("0");
            this.create(accessory);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Accessory minIoUpload(MultipartFile file, String bizPath, String fileName, String customBucket, String sourceId) {
        Accessory accessory = new Accessory();
        accessory.setSourceId(sourceId);
        if (file.isEmpty() || file.getSize() == 0) {
            throw new RuntimeException("文件为空");
        }

        try {

            if (StringUtils.isBlank(fileName)) {
                fileName = file.getOriginalFilename();
            }

            accessory.setName(fileName);
            String name = DigestUtils.md5Hex(UUID.randomUUID().toString()) + fileName.substring(fileName.lastIndexOf("."));

            String url = MinioUtil.upload(file, bizPath, name, customBucket);
            //验证图片类型
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            System.out.println(ext);
            accessory.setType(ext);
            accessory.setSuffix(ext);
            accessory.setUrl(url);
            accessory.setIsDele("0");
            this.create(accessory);
            return accessory;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public void minIoDownFile(String ids, String bizPath, String filePath, String customBucket, HttpServletResponse response) throws Exception {
        if (StringUtils.isNotBlank(ids)) {

//            String file = "download/contract";
            File path = new File(filePath);
            if (!path.exists()) {
                path.mkdirs();
            }
            List<String> idList = Arrays.asList(ids.split(","));
            List<Accessory> accessories = this.listByIds(idList);
            if (accessories.size() == 1) {
                Accessory accessory = accessories.get(0);
                String url = accessory.getUrl();
                String substring = url.substring(url.lastIndexOf("/"));
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(path + "/" + accessory.getName());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                MinioUtil.downFile(customBucket, bizPath + substring, out, false);
                HttpUtil.downLoadFile(response, filePath + "/" + accessory.getName(), accessory.getName());
                FileUtil.deleteFile(filePath + "/" + accessory.getName());
                return;
            }


            accessories.forEach(s -> {
                String url = s.getUrl();
                String substring = url.substring(url.lastIndexOf("/"));
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(path + "/" + s.getName());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                System.out.println("contract" + substring);
                MinioUtil.downFile(customBucket, bizPath + substring, out, false);

            });
            this.zip(filePath, true);
            String zipPath = filePath + ".zip";
            HttpUtil.downLoadFile(response, zipPath, zipPath.substring(zipPath.lastIndexOf("/") + 1));
            // 删除导出的文件
            FileUtil.deleteFile(zipPath);
        }


    }

    @Override
    public void minIoDownFile(String ids, String bizPath, HttpServletResponse response) throws Exception {
        this.minIoDownFile(ids, bizPath,"download/"+bizPath,"yhxt",response);
    }

    @Override
    public void minIoRemoveFile(String id, String bizPath, String customBucket) {
        Accessory accessory = this.get(id);
        String url = accessory.getUrl();
        String substring = null;
        if (StringUtils.isBlank(bizPath)) {
            substring = url.substring(url.lastIndexOf("/") + 1);
        } else {
            substring = bizPath + url.substring(url.lastIndexOf("/"));
        }
        MinioUtil.removeObject(customBucket, substring, true);
        this.remove(id);
    }

    /**
     * 压缩文件
     *
     * @param path     压缩文件\文件夹路径
     * @param isDelete 压缩后是否删除原文件\文件夹
     */
    public void zip(String path, Boolean isDelete) {
        ZipFile zipFile = null;
        try {
            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            File file = new File(path);
            Assert.isTrue(file.exists(), "文件不存在");
            ArrayList<String> list = new ArrayList<>();
            if (file.isDirectory()) {
                zipFile = new ZipFile(new File(path + ".zip"));
                zipFile.setFileNameCharset("GBK");
                zipFile.addFolder(path, parameters);
            } else {
                zipFile = new ZipFile(new File(path.split(".")[0] + ".zip"));
                zipFile.setFileNameCharset("GBK");
                zipFile.addFile(file, parameters);
            }
            if (isDelete)
                FileUtil.deleteDir(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public Accessory minioUpload(MultipartFile file,String bizPath ,HttpServletResponse response) throws Exception {
        Accessory accessory = new Accessory();
        String fileName = null;
        if (file.isEmpty() || file.getSize() == 0) {
            throw new BaseException("文件为空");
        }
        if (StringUtils.isBlank(fileName)) {
            fileName = file.getOriginalFilename();
        }
        accessory.setName(fileName);
        String name = DigestUtils.md5Hex(UUID.randomUUID().toString()) + fileName.substring(fileName.lastIndexOf("."));
        //如果为空放到默认文件夹
        if (StringUtils.isEmpty(bizPath)){
            bizPath="default";
        }
        String url = MinioUtil.upload(file, bizPath, name, "yhxt");
        //验证图片类型
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(ext);
        accessory.setType(ext);
        accessory.setSuffix(ext);
        accessory.setUrl(url);
        accessory.setIsDele("0");
        return accessory;
    }

    @Override
    public List<Accessory> getAccessoryBySourceId(String sourceId) {
        QueryWrapper<Accessory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SOURCE_ID_",sourceId);
        queryWrapper.eq("IS_DELE_","0");
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public void delAccessoryBySourceId(String sourceId) {
//        UpdateWrapper<Accessory> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.eq("SOURCE_ID_", sourceId);
//        updateWrapper.set("is_dele_", "1");
//        this.update(null, updateWrapper);
        QueryWrapper<Accessory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SOURCE_ID_", sourceId);
        this.remove(queryWrapper);
    }
}
