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

import com.artfess.base.context.BaseContext;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.FileUtil;
import com.artfess.base.util.HttpUtil;
import com.artfess.file.util.CheckFileFormatUtil;
import com.artfess.file.util.MinioUtil;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.specialproject.model.BizEngineeringAccessories;
import com.artfess.yhxt.specialproject.model.BizEngineeringAccessories;
import com.artfess.yhxt.specialproject.model.BizEngineeringAccessories;
import com.artfess.yhxt.specialproject.dao.BizEngineeringAccessoriesDao;
import com.artfess.yhxt.specialproject.manager.BizEngineeringAccessoriesManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.jsonwebtoken.lang.Assert;
import net.lingala.zip4j.core.ZipFile;
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.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 工程附件表 服务实现类
 *
 * @author wangping
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-08-12
 */
@Service
public class BizEngineeringAccessoriesManagerImpl extends BaseManagerImpl<BizEngineeringAccessoriesDao, BizEngineeringAccessories> implements BizEngineeringAccessoriesManager {
    @Resource
    private BaseContext baseContext;

    @Override
    public PageList<BizEngineeringAccessories> queryBizEngineeringAccessories(QueryFilter<BizEngineeringAccessories> queryFilter) {
        IPage<BizEngineeringAccessories> result = baseMapper.queryBizEngineeringAccessories(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public BizEngineeringAccessories getBizEngineeringAccessoriesById(String id) {
        BizEngineeringAccessories bizEngineeringAccessories = baseMapper.selectById(id);
        return bizEngineeringAccessories;
    }

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

        try {

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

            String url = MinioUtil.uploadRelative(file, "/engineering", name, "yhxt");
            //验证图片类型
            String ext = CheckFileFormatUtil.getFileType((FileInputStream) file.getInputStream());
            accessory.setAttachmentType(ext);
            accessory.setAttachmentSuffix(ext);
            accessory.setAttachmentPath(url);
            accessory.setIsDele("0");
            this.create(accessory);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

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

        try {

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

            engineeringAccessories.setAttachmentName(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);
            engineeringAccessories.setAttachmentSuffix(ext);
            engineeringAccessories.setAttachmentType(ext);
            engineeringAccessories.setValidFlag(1);
            engineeringAccessories.setIsDele("0");
            engineeringAccessories.setAttachmentPath(url);
            engineeringAccessories.setOwnerId(baseContext.getCurrentUserId());
            this.create(engineeringAccessories);
            return engineeringAccessories;
        } 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<BizEngineeringAccessories> list = this.listByIds(idList);
            if (list.size()==1){
                BizEngineeringAccessories accessories = list.get(0);
                String url = accessories.getAttachmentPath();
                String substring = url.substring(url.lastIndexOf("/"));
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(path + "/" + accessories.getAttachmentName());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                MinioUtil.downFile(customBucket, bizPath + substring, out, false);
                HttpUtil.downLoadFile(response, filePath+"/"+ accessories.getAttachmentName(),  accessories.getAttachmentName());
                FileUtil.deleteFile(filePath+"/"+ accessories.getAttachmentName());
                return;
            }


            list.forEach(s -> {
                String url = s.getAttachmentPath();
                String substring = url.substring(url.lastIndexOf("/"));
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(path + "/" + s.getAttachmentName());
                } 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 minIoAllDownFile(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) {
        BizEngineeringAccessories engineeringAccessories = this.get(id);
        String url = engineeringAccessories.getAttachmentPath();
        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);
    }

    @Override
    public void removeEngineeringAccessories(String sourceId) {
        if (sourceId !=null) {

            UpdateWrapper<BizEngineeringAccessories> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("SOURCE_ID_", sourceId);
            updateWrapper.set("is_dele_","1");
            this.update(null,updateWrapper);
        }
    }

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

    /**
     * 压缩文件
     *
     * @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();
        }
    }
}
