yaowanxin
2025-08-11 1b5604f8a88000e2f51d4c989fd179989468ee67
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package com.ruoyi.measuringinstrumentledger.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.measuringinstrumentledger.dto.MeasuringInstrumentLedgerDto;
import com.ruoyi.measuringinstrumentledger.mapper.MeasuringInstrumentLedgerMapper;
import com.ruoyi.measuringinstrumentledger.mapper.MeasuringInstrumentLedgerRecordMapper;
import com.ruoyi.measuringinstrumentledger.pojo.MeasuringInstrumentLedger;
import com.ruoyi.measuringinstrumentledger.pojo.MeasuringInstrumentLedgerRecord;
import com.ruoyi.measuringinstrumentledger.service.MeasuringInstrumentLedgerService;
import com.ruoyi.other.mapper.TempFileMapper;
import com.ruoyi.other.pojo.TempFile;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.sales.mapper.CommonFileMapper;
import com.ruoyi.sales.pojo.CommonFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
 
/**
 * @author :yys
 * @date : 2025/8/5 9:23
 */
@Service
@Slf4j
public class MeasuringInstrumentLedgerServiceImpl extends ServiceImpl<MeasuringInstrumentLedgerMapper, MeasuringInstrumentLedger> implements MeasuringInstrumentLedgerService {
 
    @Autowired
    private MeasuringInstrumentLedgerMapper measuringInstrumentLedgerMapper;
 
    @Autowired
    private MeasuringInstrumentLedgerRecordMapper measuringInstrumentLedgerRecordMapper;
 
    @Autowired
    private TempFileMapper tempFileMapper;
 
    @Autowired
    private CommonFileMapper commonFileMapper;
 
    @Autowired
    private SysUserMapper sysUserMapper;
 
    @Value("${file.upload-dir}")
    private String uploadDir;
 
    @Override
    public IPage<MeasuringInstrumentLedger> listPage(Page page, MeasuringInstrumentLedger measuringInstrumentLedger) {
        IPage<MeasuringInstrumentLedger> measuringInstrumentLedgerIPage = measuringInstrumentLedgerMapper.listPage(page, measuringInstrumentLedger);
        List<Integer>  types = new ArrayList<>();
        types.add(FileNameType.MEASURING.getValue());
        types.add(FileNameType.MEASURINGRecord.getValue());
        measuringInstrumentLedgerIPage.getRecords().forEach(item -> {
            LambdaQueryWrapper<MeasuringInstrumentLedgerRecord> measuringInstrumentLedgerRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            measuringInstrumentLedgerRecordLambdaQueryWrapper.eq(MeasuringInstrumentLedgerRecord::getMeasuringInstrumentLedgerId, item.getId());
            List<MeasuringInstrumentLedgerRecord> measuringInstrumentLedgerRecords = measuringInstrumentLedgerRecordMapper.selectList(measuringInstrumentLedgerRecordLambdaQueryWrapper);
            List<Long> collect = new ArrayList<>();
            if(!CollectionUtils.isEmpty(measuringInstrumentLedgerRecords)){
                collect = measuringInstrumentLedgerRecords.stream().map(MeasuringInstrumentLedgerRecord::getId).collect(Collectors.toList());
            }
            collect.add(item.getId());
            LambdaQueryWrapper<CommonFile> salesLedgerFileWrapper = new LambdaQueryWrapper<>();
            salesLedgerFileWrapper.in(CommonFile::getCommonId, collect)
                    .in(CommonFile::getType,types);
            List<CommonFile> commonFiles = commonFileMapper.selectList(salesLedgerFileWrapper);
            item.setCommonFiles(commonFiles);
 
        });
        return measuringInstrumentLedgerIPage;
    }
 
    @Override
    public boolean verifying(MeasuringInstrumentLedgerDto req) throws IOException {
        MeasuringInstrumentLedger measuringInstrumentLedger = measuringInstrumentLedgerMapper.selectById(req.getId());
        if(measuringInstrumentLedger == null) {
            return false;
        }
        SysUser sysUser = sysUserMapper.selectUserById(measuringInstrumentLedger.getUserId());
        measuringInstrumentLedger.setValid(req.getValid());
        measuringInstrumentLedger.setMostDate(req.getRecordDate());
        measuringInstrumentLedger.setNextDate(new Date(req.getRecordDate().getTime() + 1000L * 60 * 60 * 24 * req.getValid()));
        MeasuringInstrumentLedgerRecord measuringInstrumentLedgerRecord = new MeasuringInstrumentLedgerRecord();
        if(measuringInstrumentLedgerMapper.updateById(measuringInstrumentLedger) > 0) {
            measuringInstrumentLedgerRecord.setMeasuringInstrumentLedgerId(req.getId());
            measuringInstrumentLedgerRecord.setRecordDate(req.getRecordDate());
            measuringInstrumentLedgerRecord.setEntryDate(req.getEntryDate());
            measuringInstrumentLedgerRecord.setValid(req.getValid());
            measuringInstrumentLedgerRecord.setUserId(req.getUserId());
            measuringInstrumentLedgerRecord.setUserName(sysUser.getUserName());
            measuringInstrumentLedgerRecordMapper.insert(measuringInstrumentLedgerRecord);
            // 台账绑定一次
//            if(!CollectionUtils.isEmpty(req.getTempFileIds())){
//                migrateTempFilesToFormal(measuringInstrumentLedger.getId(), req.getTempFileIds(), FileNameType.MEASURING.getValue());
//            }
            // 台账记录绑定一次
            if(!CollectionUtils.isEmpty(req.getTempFileIds())){
                migrateTempFilesToFormal(measuringInstrumentLedgerRecord.getId(), req.getTempFileIds(), FileNameType.MEASURINGRecord.getValue());
            }
            return true;
        }
        return false;
    }
 
    @Override
    public void export(HttpServletResponse response) {
        List<MeasuringInstrumentLedger> list = measuringInstrumentLedgerMapper.listPage(new MeasuringInstrumentLedger());
        ExcelUtil<MeasuringInstrumentLedger> util = new ExcelUtil<MeasuringInstrumentLedger>(MeasuringInstrumentLedger.class);
        util.exportExcel(response, list , "客户档案数据");
    }
 
    @Override
    public boolean add(MeasuringInstrumentLedger measuringInstrumentLedger) throws IOException {
        SysUser sysUser = sysUserMapper.selectUserById(measuringInstrumentLedger.getUserId());
        if (sysUser == null) {
            return false;
        }
        measuringInstrumentLedger.setUserName(sysUser.getUserName());
        measuringInstrumentLedgerMapper.insert(measuringInstrumentLedger);
        if(!CollectionUtils.isEmpty(measuringInstrumentLedger.getTempFileIds())){
            migrateTempFilesToFormal(measuringInstrumentLedger.getId(), measuringInstrumentLedger.getTempFileIds(), FileNameType.MEASURING.getValue());
        }
        return true;
    }
 
 
    /**
     * 将临时文件迁移到正式目录
     *
     * @param businessId  业务ID(销售台账ID)
     * @param tempFileIds 临时文件ID列表
     * @throws IOException 文件操作异常
     */
    private void migrateTempFilesToFormal(Long businessId, List<String> tempFileIds,Integer fileType) throws IOException {
        if (CollectionUtils.isEmpty(tempFileIds)) {
            return;
        }
 
        // 构建正式目录路径(按业务类型和日期分组)
        String formalDir = uploadDir + LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
 
        Path formalDirPath = Paths.get(formalDir);
 
        // 确保正式目录存在(递归创建)
        if (!Files.exists(formalDirPath)) {
            Files.createDirectories(formalDirPath);
        }
 
        for (String tempFileId : tempFileIds) {
            // 查询临时文件记录
            TempFile tempFile = tempFileMapper.selectById(tempFileId);
            if (tempFile == null) {
                log.warn("临时文件不存在,跳过处理: {}", tempFileId);
                continue;
            }
 
            // 构建正式文件名(包含业务ID和时间戳,避免冲突)
            String originalFilename = tempFile.getOriginalName();
            String fileExtension = FilenameUtils.getExtension(originalFilename);
            String formalFilename = businessId + "_" +
                    System.currentTimeMillis() + "_" +
                    UUID.randomUUID().toString().substring(0, 8) +
                    (StringUtils.hasText(fileExtension) ? "." + fileExtension : "");
 
            Path formalFilePath = formalDirPath.resolve(formalFilename);
 
            try {
                // 执行文件迁移(使用原子操作确保安全性)
                Files.move(
                        Paths.get(tempFile.getTempPath()),
                        formalFilePath,
                        StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.ATOMIC_MOVE
                );
                log.info("文件迁移成功: {} -> {}", tempFile.getTempPath(), formalFilePath);
 
                // 更新文件记录(关联到业务ID)
                CommonFile fileRecord = new CommonFile();
                fileRecord.setCommonId(businessId);
                fileRecord.setName(originalFilename);
                fileRecord.setUrl(formalFilePath.toString());
                fileRecord.setCreateTime(LocalDateTime.now());
                fileRecord.setType(fileType);
                commonFileMapper.insert(fileRecord);
 
                // 删除临时文件记录
                tempFileMapper.deleteById(tempFile);
 
                log.info("文件迁移成功: {} -> {}", tempFile.getTempPath(), formalFilePath);
            } catch (IOException e) {
                log.error("文件迁移失败: {}", tempFile.getTempPath(), e);
                // 可选择回滚事务或记录失败文件
                throw new IOException("文件迁移异常", e);
            }
        }
    }
}