FileController.java 12.9 KB
package vion.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.regex.ReUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.http.client.HttpDownloader;
import org.dromara.hutool.http.client.Request;
import org.dromara.hutool.http.meta.Method;
import org.dromara.hutool.json.JSONArray;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vion.dto.FileInfoDTO;
import vion.model.Contract;
import vion.model.FileInfo;
import vion.model.Pic;
import vion.service.IContractService;
import vion.service.IFileService;

import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class FileController {

    private final IFileService fileService;
    private final IContractService contractService;
    private final Converter converter;

    @Value("${fileUrl:}")
    private String fileUrl;

    @GetMapping("/files")
    public Page<FileInfo> getFiles(FileInfoDTO data) {
        return fileService.lambdaQuery(converter.convert(data, new FileInfo()))
                .eq(ObjUtil.isNotNull(data.getStoreId()), FileInfo::getStoreId, data.getStoreId())
                .eq(ObjUtil.isNotNull(data.getSourceId()), FileInfo::getSourceId, data.getSourceId())
                .eq(ObjUtil.isNotNull(data.getContractId()), FileInfo::getContractId, data.getContractId())
                .eq(ObjUtil.isNotNull(data.getSourceType()), FileInfo::getSourceType, data.getSourceType())
                .in(CollUtil.isNotEmpty(data.getSourceTypeList()), FileInfo::getSourceType, data.getSourceTypeList())
                .orderByDesc(FileInfo::getCreateTime)
                .page(Page.of(data.getPageNum(), data.getPageSize()));
    }

    @DeleteMapping("/file/{id}")
    public String remove(@PathVariable(name = "id") Integer id) {
        FileInfo file = fileService.getById(id);
        FileUtil.del(file.getUrl());
        fileService.removeById(id);
        return "文件删除成功";
    }

    @PostMapping("/file/formFileUpload")
    public String uploadFile(FileInfo fileInfo, @RequestParam(name = "file") MultipartFile infile) throws IOException {
        String orgName = infile.getOriginalFilename();
        String mainName = FileNameUtil.mainName(orgName);
        String fileExt = FileNameUtil.extName(orgName);
        String filename = StrUtil.format("{}_{}.{}", mainName, DateUtil.format(new Date(), "yyyyMMdd_HHmmssSSS"), fileExt);
        String path = getPath(fileInfo, filename);
        File file = FileUtil.touch(path);
        infile.transferTo(file);
        FileInfo tempFileInfo = new FileInfo();
        tempFileInfo.setStoreId(fileInfo.getStoreId());
        tempFileInfo.setSourceId(fileInfo.getSourceId());
        tempFileInfo.setSourceType(fileInfo.getSourceType());
        tempFileInfo.setName(filename);
        tempFileInfo.setUrl(path);
        tempFileInfo.setType(FileNameUtil.extName(file));
        tempFileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
        tempFileInfo.setUploader(fileInfo.getUploader());

        if (fileService.save(tempFileInfo)) {
            return path;
        } else {
            return "文件保存失败";
        }
    }

    private String getPath(FileInfo fileInfo, String filename) {
        String path;
        if ("storeLog".equals(fileInfo.getFlag())) {
            path = fileUrl + FileUtil.FILE_SEPARATOR + "form" + FileUtil.FILE_SEPARATOR + "storeLog" + FileUtil.FILE_SEPARATOR + fileInfo.getStoreId() + FileUtil.FILE_SEPARATOR + fileInfo.getSourceId() + FileUtil.FILE_SEPARATOR + filename;
        } else {
            path = fileUrl + FileUtil.FILE_SEPARATOR + "form" + FileUtil.FILE_SEPARATOR + fileInfo.getStoreId() + FileUtil.FILE_SEPARATOR + fileInfo.getSourceId() + FileUtil.FILE_SEPARATOR + filename;

        }
        return path;
    }

    @PostMapping("/file/uploadFile")
    public String uploadFile1(FileInfo fileInfo, @RequestParam(name = "files") MultipartFile[] files) throws IOException {
        for (MultipartFile infile : files) {
            String orgName = infile.getOriginalFilename();
            String mainName = FileNameUtil.mainName(orgName);
            String fileExt = FileNameUtil.extName(orgName);
            String filename = StrUtil.format("{}_{}.{}", mainName, DateUtil.format(new Date(), "yyyyMMdd_HHmmssSSS"), fileExt);
            String path = fileUrl + FileUtil.FILE_SEPARATOR + fileInfo.getStoreId() + FileUtil.FILE_SEPARATOR + fileInfo.getSourceId() + FileUtil.FILE_SEPARATOR + filename;
            File file = FileUtil.touch(path);
            infile.transferTo(file);

            FileInfo tempFileInfo = new FileInfo();
            tempFileInfo.setStoreId(fileInfo.getStoreId());
            tempFileInfo.setSourceId(fileInfo.getSourceId());
            tempFileInfo.setSourceType(fileInfo.getSourceType());
            tempFileInfo.setName(filename);
            tempFileInfo.setUrl(path);
            tempFileInfo.setType(FileNameUtil.extName(file));
            tempFileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
            tempFileInfo.setUploader(fileInfo.getUploader());

            fileService.save(tempFileInfo);
        }
        return "文件保存成功";
    }

    @GetMapping("/contractFile")
    public String export() {
        String url = "jdbc:sqlserver://47.92.144.255:1433;databaseName=UFDATA_001_2020;encrypt=false";
        String username = "vion-reader";
        String password = "vion-reader";
        List<Pic> res = new ArrayList<>();

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            String sql = """
                    select a.hetongluru_name as contract_no,b.hetongluru_char13 as pic_url from tcu_hetongluru a, tcu_hetongluru_attr b 
                    where a.hetongluru_id = b.hetongluru_id and b.hetongluru_char13 != '';
                    """;
            try (Statement statement = connection.createStatement()) {
                ResultSet resultSet = statement.executeQuery(sql);
                while (resultSet.next()) {
                    Pic pic = new Pic();
                    String contractNo = resultSet.getString("contract_no");
                    pic.setContractNo(contractNo);
                    String picUrl = resultSet.getString("pic_url");
                    if (StrUtil.isBlank(picUrl)) {
                        continue;
                    }
                    // 获取字符串picUrl后三十六个字符
                    String code = picUrl.substring(picUrl.length() - 36);

                    pic.setCode(code);
                    res.add(pic);
                }
            }
        } catch (SQLException e) {
        }

        Map<String, Contract> no2ConMap = contractService.list().stream().collect(Collectors.toMap(Contract::getContractNo, Function.identity()));

        // CSRP20111098   CSRM23065215
        for (Pic pic : res) {
            String contractNo = pic.getContractNo();
            String code = pic.getCode();
            if (!no2ConMap.containsKey(contractNo)) {
                log.info("合同文件导入-合同不存在:{}", contractNo);
                continue;
            }
            Contract contract = no2ConMap.get(contractNo);
            List<FileInfo> list = fileService.lambdaQuery()
                    .eq(FileInfo::getContractId, contract.getId())
                    .eq(FileInfo::getSourceType, 5)
                    .eq(FileInfo::getSourceId, contract.getId()).list();
            if (CollUtil.isNotEmpty(list)) {
                log.info("合同文件导入-合同文件已存在:{}", contractNo);
                continue;
            }

            String body = Request.of("http://47.92.144.255:8072/pub/processattach.php?Action=viewfiles&PageSrc=")
                    .header("Cookie", "PHPSESSID=v0t8clpoqcn1686fhneul31rf4; LoginSystemCookie=1; LoginNameCookie=0191; OrgCodeCookie=%28default%29%40001; ID_LIST_OL_10_0_0_MessageItem__Subject=250; TL_EXPANDED=*REL_CRMCONTRACT4*XSFPSQD.hetonglur2017*hetongluru.XMMC4*hetongpingshen.Opportunity4")
                    .method(Method.POST)
                    .form(Map.of("cellID", code))
                    .send()
                    .bodyStr();
            if (body.contains("text/javascript")) {
                log.info("合同文件导入-调CRM接口出错:{}", contractNo);
                break;
            }
            if (StrUtil.isBlank(body)) {
                log.info("合同文件导入-body为空:{},code:{}", contractNo, code);
                continue;
            }
            if (!StrUtil.contains(body, "href")) {
                log.info("合同文件导入-无文件:{},code:{}", contractNo, code);
                continue;
            }

            JSONObject json = JSONUtil.parseObj(body);
            Object o = json.get("files");
            if (o instanceof JSONObject) {
                JSONObject files = json.getJSONObject("files");
                for (Map.Entry<String, Object> entry : files) {
                    if (ObjUtil.isEmpty(entry.getValue())) {
                        continue;
                    }
                    String href = entry.getValue().toString();
                    String suf = ReUtil.get("href='(.*?)'", href, 1);
                    String finalUrl = "http://47.92.144.255:8072" + suf;
                    String name = ReUtil.get(">(.*?)<", href, 1);

                    String path = fileUrl + FileUtil.FILE_SEPARATOR + "contract" + FileUtil.FILE_SEPARATOR + contract.getId() + FileUtil.FILE_SEPARATOR + name;
                    log.info("合同:{},文件存入路径:{}", contractNo, path);
                    File file = HttpDownloader.downloadFile(finalUrl, FileUtil.file(path));
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setStoreId(-1L);
                    fileInfo.setSourceId(contract.getId());
                    fileInfo.setSourceType(5);
                    fileInfo.setContractId(contract.getId());
                    fileInfo.setName(name);
                    fileInfo.setUrl(path);
                    fileInfo.setType(FileNameUtil.extName(file));
                    fileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
                    fileInfo.setUploader("CRM");
                    fileService.save(fileInfo);
                }
            } else if (o instanceof JSONArray) {
                JSONArray files = json.getJSONArray("files");
                for (Object obj : files) {
                    if (ObjUtil.isEmpty(obj)) {
                        continue;
                    }
                    String href = obj.toString();
                    String suf = ReUtil.get("href='(.*?)'", href, 1);
                    String finalUrl = "http://47.92.144.255:8072" + suf;
                    String name = ReUtil.get(">(.*?)<", href, 1);

                    String path = fileUrl + FileUtil.FILE_SEPARATOR + "contract" + FileUtil.FILE_SEPARATOR + contract.getId() + FileUtil.FILE_SEPARATOR + name;
                    log.info("合同:{},文件存入路径:{}", contractNo, path);
                    File file = HttpDownloader.downloadFile(finalUrl, FileUtil.file(path));
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setStoreId(-1L);
                    fileInfo.setSourceId(contract.getId());
                    fileInfo.setSourceType(5);
                    fileInfo.setContractId(contract.getId());
                    fileInfo.setName(name);
                    fileInfo.setUrl(path);
                    fileInfo.setType(FileNameUtil.extName(file));
                    fileInfo.setSha256(SecureUtil.sha256(file).toUpperCase());
                    fileInfo.setUploader("CRM");
                    fileService.save(fileInfo);
                }
            } else {
                log.info("合同文件导入-json转化出错:{},code:{}", contractNo, code);
            }


        }
        return "success";
    }

    @DeleteMapping("/speFile")
    public String delSpeFile() {
        List<FileInfo> list = fileService.lambdaQuery().eq(FileInfo::getSourceType, 5).eq(FileInfo::getUploader, "CRM").list();
        for (FileInfo file : list) {
            FileUtil.del(file.getUrl());
            fileService.removeById(file.getId());
        }
        return "success";
    }
}