package com.tofly.gpsboot.custom.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.oauth.util.SecurityUtils;

import com.tofly.gpsboot.config.car.CarFilePathBean;
import com.tofly.gpsboot.config.car.PdfUtil;
import com.tofly.gpsboot.custom.service.CustomDeptCarService;
import com.tofly.gpsboot.service.car.DeptCarService;
import com.tofly.pojo.car.DeptCar;

import lombok.AllArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@AllArgsConstructor
public class CustomDeptCarServiceImpl implements CustomDeptCarService {
    private CarFilePathBean carFilePathBean;
    private DeptCarService deptCarService;

    private String fileToPdf(String filename, MultipartFile f) {
        String name = f.getOriginalFilename().substring(0, f.getOriginalFilename().lastIndexOf("."));
        String wordFile = "c:/temp/" + f.getOriginalFilename();
        String pdfFile = "c:/temp/" + name + ".pdf";
        File file1 = new File(pdfFile);
        if (file1.exists()) {
            file1.delete();
        }
        ActiveXComponent app = null;

        if (filename.toLowerCase().endsWith(".doc")
                || filename.toLowerCase().endsWith(".docx")) {
            File file = new File(wordFile);
            try {
                FileUtils.copyInputStreamToFile(f.getInputStream(), file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*Document document = new Document();
            document.loadFromFile("c:/temp/" + f.getOriginalFilename());
            document.saveToFile("c:/temp/" + name + ".pdf", FileFormat.PDF);*/
            try {
                //打开Word
                app = new ActiveXComponent("Word.Application");
                //获取Word中所有打开的文档
                Dispatch documents = app.getProperty("Documents").toDispatch();
                //打开文档
                Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
                Dispatch.call(document, "SaveAs", pdfFile, 17);
                //关闭文档
                Dispatch.call(document, "Close", false);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭软件
                app.invoke("Quit", 0);
                file.delete();
            }
        } else if (filename.toLowerCase().endsWith(".bmp")
                || filename.toLowerCase().endsWith(".jpg")
                || filename.toLowerCase().endsWith(".jpeg")
                || filename.toLowerCase().endsWith(".gif")
                || filename.toLowerCase().endsWith(".png")) {
            File file = new File("c:/temp/images/" + f.getOriginalFilename());
            try {
                FileUtils.copyInputStreamToFile(f.getInputStream(), file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            file1 = PdfUtil.imagesToPdf2(file1, "c:/temp/images");
            file.delete();
        }
        FileInputStream input = null;
        MultipartFile m = null;
        try {
            input = new FileInputStream(file1);
            m = new MockMultipartFile(file1.getName(), file1.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), input);
            String filename1 = carFilePathBean.getDeptcar() + IdWorker.getIdStr() + ".pdf";
            boolean b1 = FtpUtil.uploadFile2Ftp(m, filename1);
            filename = filename + "," + filename1;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (input != null) {
                    input.close();
                    //file.delete();
                    file1.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filename;
    }

    private DeptCar file(DeptCar deptCar, HttpServletRequest servletRequest) {
        MultiValueMap<String, MultipartFile> multipartFileMap = ((MultipartHttpServletRequest) servletRequest).getMultiFileMap();
        if (!multipartFileMap.isEmpty()) {
            multipartFileMap.forEach((k, v) -> {
                //web端所有文件
                if (k.contains("file")) {
                    v.forEach(f -> {
                        String filename = carFilePathBean.getDeptcar() + IdWorker.getIdStr() + f.getOriginalFilename().substring(f.getOriginalFilename().lastIndexOf("."));
                        boolean b = FtpUtil.uploadFile2Ftp(f, filename);

                        if (filename.toLowerCase().endsWith(".bmp")
                                || filename.toLowerCase().endsWith(".jpg")
                                || filename.toLowerCase().endsWith(".jpeg")
                                || filename.toLowerCase().endsWith(".gif")
                                || filename.toLowerCase().endsWith(".png")) {
                            filename = fileToPdf(filename, f);
                            deptCar.setFileType("0");
                        } else if (filename.toLowerCase().endsWith(".amr")) {
                            deptCar.setFileType("1");
                        } else if (filename.toLowerCase().endsWith(".doc")
                                || filename.toLowerCase().endsWith(".docx")) {
                            filename = fileToPdf(filename, f);
                            deptCar.setFileType("2");
                        } else {
                            deptCar.setFileType("2");
                        }
                        deptCar.setFilePath(filename);
                        deptCar.setFileName(f.getOriginalFilename());
                    });
                }
            });
        }
        return deptCar;
    }

    @Override
    @Transactional
    public boolean save(DeptCar deptCar, HttpServletRequest request) {
        if (((MultipartHttpServletRequest) request).getMultiFileMap().size() > 0) {
            file(deptCar, request);
        }
        if (StringUtil.isNotEmpty(deptCar.getFilePath())) {
            deptCar.setState("1");
        } else {
            deptCar.setState("0");
        }
        deptCar.setCreatTime(new Date());
        deptCar.setCreatUser(SecurityUtils.getUserId());
        deptCarService.save(deptCar);
        return true;
    }

    @Override
    @Transactional
    public boolean updateById(DeptCar deptCar, HttpServletRequest request) {
        String path = deptCarService.getById(deptCar.getId()).getFilePath();
        if (((MultipartHttpServletRequest) request).getMultiFileMap().size() > 0) {
            if (StringUtil.isNotEmpty(path)) {
                if (path.contains(",")) {
                    String[] paths = path.split(",");
                    for (String p : paths) {
                        FtpUtil.deleteFile(p);
                    }
                } else {
                    FtpUtil.deleteFile(path);
                }
            }
            file(deptCar, request);
        }
        deptCar.setUpdateTime(new Date());
        deptCarService.updateById(deptCar);
        return true;
    }

    @Override
    @Transactional
    public boolean removeById(List<String> ids) {
        List<DeptCar> list1 = deptCarService.list(Wrappers.<DeptCar>lambdaQuery()
                .in(DeptCar::getId, ids));
        list1.forEach(k -> {
            if (StringUtil.isNotEmpty(k.getFilePath())) {
                if (k.getFilePath().contains(",")) {
                    String[] paths = k.getFilePath().split(",");
                    for(String p : paths){
                        FtpUtil.deleteFile(p);
                    }
                } else {
                    FtpUtil.deleteFile(k.getFilePath());
                }
            }
        });
        deptCarService.remove(Wrappers.<DeptCar>lambdaQuery()
                .in(DeptCar::getId, ids));
        return true;
    }
}
