zss
2025-03-07 12291480d592402398c3ba76e8de6006da5c2612
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package com.ruoyi.personnel.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.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.DepartmentLims;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.numgen.NumberGenerator;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.personnel.dto.PersonTrainingDetailedDto;
import com.ruoyi.personnel.enumeration.AttachmentType;
import com.ruoyi.personnel.excel.PersonTrainingDetailedUpload;
import com.ruoyi.personnel.mapper.*;
import com.ruoyi.personnel.pojo.*;
import com.ruoyi.personnel.service.PersonTrainingDetailedService;
import com.ruoyi.system.mapper.DepartmentLimsMapper;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.service.DepartmentLimsService;
import lombok.AllArgsConstructor;
import org.apache.commons.math3.analysis.function.Power;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 培训计划详情 服务实现类
 * </p>
 *
 * @author 芯导软件(江苏)有限公司
 * @since 2024-10-11 01:46:27
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PersonTrainingDetailedServiceImpl extends ServiceImpl<PersonTrainingDetailedMapper, PersonTrainingDetailed> implements PersonTrainingDetailedService {
 
    @Resource
    private DepartmentLimsService departmentLimsService;
 
    @Resource
    private UserMapper userMapper;
 
    @Resource
    private PersonTrainingRecordMapper personTrainingRecordMapper;
 
    @Resource
    private PersonTrainingMapper personTrainingMapper;
 
//    private PowerMapper powerMapper;
 
    @Resource
    private PersonTrainingFileMapper personTrainingFileMapper;
 
    @Resource
    private NumberGenerator<PersonTrainingDetailed> numberGenerator;
 
    @Resource
    private DepartmentLimsMapper departmentLimsMapper;
 
    @Value("${file.path}")
    private String imgUrl;
 
    @Value("${excelUrl}")
    private String excelUrl;
 
    @Value("${wordUrl}")
    private String wordUrl;
 
    /**
     *
     * @param file
     * @param id 年度计划明细表id
     */
    @Override
    public Map<String,Object> fileUpload(MultipartFile file, Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        String fileName = file.getOriginalFilename();
 
        try {
            UUID uuid = UUID.randomUUID();
            String uuidString = uuid.toString();
            int i = fileName.indexOf(".");
            String suffix = fileName.substring(i); //文件后缀
            String url = uuidString + suffix;
            String OriginalFileName = fileName.substring(0,i); // 文件原名称
            // 存放路径
            String path = "";
            // 根据不同的后缀存放在不同的路径下
            if(suffix.toLowerCase().contains("xls")) {
                path = excelUrl;
            } else if (suffix.toLowerCase().contains("doc") || suffix.toLowerCase().contains("pdf")) {
                path = wordUrl;
            }else {
                path = imgUrl;
            }
            File uploadDir  = new File(path);
            if(!uploadDir.exists()){
                uploadDir.mkdir();
            }
            File destFile = new File(uploadDir , url);
            file.transferTo(destFile);
            // 将文件路径存储到数据库
            PersonTrainingFile personTrainingFile = new PersonTrainingFile();
            personTrainingFile.setDetailId(id);
            personTrainingFile.setFileName(OriginalFileName + suffix);
            personTrainingFile.setFileUrl("/"+url);
            personTrainingFile.setCreateUser(SecurityUtils.getUserId().intValue());
            personTrainingFile.setCreateTime(LocalDateTime.now());
            personTrainingFileMapper.insert(personTrainingFile);
 
 
            map.put("fileName",OriginalFileName + suffix);
            map.put("url","/"+url);
        } catch (IOException e) {
            throw new ErrorException("上传失败");
        }
        return map;
    }
 
    @Override
    public List<DepartmentLims> selectDepartLims() {
        List<DepartmentLims> departmentLims = departmentLimsMapper.selectList(null);
        return departmentLims;
 
 
    }
 
    @Override
    public void importExcel(List<PersonTrainingDetailedUpload> list, Integer planId) {
        List<PersonTrainingDetailed> personTrainingDetailedList = new ArrayList<>();
        list.forEach(i -> {
            PersonTrainingDetailed personTrainingDetailed = new PersonTrainingDetailed();
            BeanUtils.copyProperties(i, personTrainingDetailed);
            personTrainingDetailed.setClassHour(Double.parseDouble( i.getClassHour()));
            // 匹配举办部门
            DepartmentLims departmentLims = departmentLimsService.getOne(Wrappers.<DepartmentLims>lambdaQuery()
                    .eq(DepartmentLims::getName, i.getHoldingDepartment()));
            if (ObjectUtils.isEmpty(departmentLims)) {
                throw new ErrorException("未匹配到举办部门:" + i.getHoldingDepartment());
            }
            personTrainingDetailed.setHoldingDepartment(departmentLims.getId());
 
//            // 匹配讲师
//            String[] names = i.getTrainingLecturerName().split("、|,|,|\\s+");
//            ArrayList<Integer> ids = new ArrayList<>();
//            for(String name : names) {
//                if(StringUtils.isNotEmpty(name)) {
//                    User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
//                            .eq(User::getName, name));
//                    if(Objects.isNull(user)) {
//                        throw new ErrorException("未找到该讲师:" + name);
//                    }
//                    ids.add(user.getId());
//                }
//            }
//            String collect = ids.stream().map(item -> item.toString()).collect(Collectors.joining(","));
            personTrainingDetailed.setTrainingLecturerId(i.getTrainingLecturerName());
            personTrainingDetailed.setPlanId(planId);
            personTrainingDetailed.setState(3);
 
            String year = new SimpleDateFormat("yy", Locale.CHINESE).format(new Date());
            String month = new SimpleDateFormat("MM", Locale.CHINESE).format(new Date());
            String processNumber = numberGenerator.generateNumberWithPrefix(4, "KC" + month + "-" + year + month, PersonTrainingDetailed::getCourseCode);
            personTrainingDetailed.setCourseCode(processNumber);
            personTrainingDetailedList.add(personTrainingDetailed);
        });
        // 批量新增
        if (CollectionUtils.isNotEmpty(personTrainingDetailedList)) {
            baseMapper.insertBatchSomeColumn(personTrainingDetailedList);
        }
    }
 
    @Override
    public void deleteAnnualPlanDetailTable(String ids) {
        String[] split = ids.split(",");
        if (split.length > 0) {
            for (String s : split) {
                baseMapper.deleteById(s);
            }
        }
    }
 
    @Override
    public IPage<PersonTrainingDetailedDto> queryTheAnnualPlanDetailsTable(Page page, String trainingLecturerName, String courseCode, String trainingDate,
                                                                           Integer id, Integer userId,Integer departId,Integer state) {
        // 判断当前人是否有权限查看年度计划主表
        Integer userId1 = SecurityUtils.getUserId().intValue();
        User user = userMapper.selectById(userId1);
        String name1 =  user.getName();
        Integer currentUserId = user.getId();
        //todo 权限待完成
//        List<Power> powers = powerMapper.selectList(new LambdaQueryWrapper<Power>()
//                .eq(Power::getRoleId, user.getRoleId())
//                .eq(Power::getMenuMethod,"personTrainingSelect"));
//        if(CollectionUtils.isEmpty(powers)) {
//            if(Objects.isNull(departId) || departId == 1) {
//                // 没有权限 就默认查看自己部门最新的年度计划  18 通信产品实验室  19 电力产品实验室
//                if(user.getDepartLimsId().contains("18")) {
//                    List<PersonTraining> personTrainings = personTrainingMapper.selectList(new LambdaQueryWrapper<PersonTraining>()
//                            .eq(PersonTraining::getDepartId, 18)
//                            .orderByDesc(PersonTraining::getId));
//                    if(CollectionUtils.isNotEmpty(personTrainings)) {
//                        id = personTrainings.get(0).getId();
//                    }
//                }else if(user.getDepartLimsId().contains("19")) {
//                    List<PersonTraining> personTrainings = personTrainingMapper.selectList(new LambdaQueryWrapper<PersonTraining>()
//                            .eq(PersonTraining::getDepartId, 19)
//                            .orderByDesc(PersonTraining::getId));
//                    if(CollectionUtils.isNotEmpty(personTrainings)) {
//                        id = personTrainings.get(0).getId();
//                    }
//                }
//            }else {
//                List<PersonTraining> personTrainings = personTrainingMapper.selectList(new LambdaQueryWrapper<PersonTraining>()
//                        .eq(PersonTraining::getDepartId, departId)
//                        .orderByDesc(PersonTraining::getId));
//                if(CollectionUtils.isNotEmpty(personTrainings)) {
//                    id = personTrainings.get(0).getId();
//                }
//            }
//        }
        if(Objects.nonNull(state)) {
            if(state == -1) {
                state = null;
            }
        }
        IPage<PersonTrainingDetailedDto> list = baseMapper.queryTheAnnualPlanDetailsTable(page, trainingLecturerName, courseCode, trainingDate, id, userId, userId1,state);
        // 报名人数
        List<PersonTrainingDetailedDto> records = list.getRecords();
        for(PersonTrainingDetailedDto a : records) {
            // 报名的人数
            List<PersonTrainingRecord> personTrainingRecords = personTrainingRecordMapper.selectList(new LambdaQueryWrapper<PersonTrainingRecord>()
                    .eq(PersonTrainingRecord::getCourseId, a.getId()));
            a.setEnrollment(CollectionUtils.isNotEmpty(personTrainingRecords) ? personTrainingRecords.size() : 0);
            List<Integer> collect = personTrainingRecords.stream().map(PersonTrainingRecord::getUserId).collect(Collectors.toList());
            if(collect.contains(SecurityUtils.getUserId().intValue())) {
                a.setWhetherClaim(true);
            }else {
                a.setWhetherClaim(false);
            }
            //前端权限需要 是否可以操作按钮
//            if(a.getTrainingLecturerId().contains(name1) || CollectionUtils.isNotEmpty(powers) ||
//                    (Objects.nonNull(a.getAssessmentUserId()) && a.getAssessmentUserId().equals(currentUserId)) || Arrays.asList(16,36,35).contains(currentUserId)) {
//                a.setIsDisabled(1); // 1不禁用
//            }else{
//                a.setIsDisabled(0);
//            }
        }
        return list;
    }
 
    @Override
    public List<PersonTrainingFile> getFileData(Integer detailedId) {
        List<PersonTrainingFile> personTrainingFiles = personTrainingFileMapper.selectList(new LambdaQueryWrapper<PersonTrainingFile>()
                .eq(PersonTrainingFile::getDetailId, detailedId)
                .eq(PersonTrainingFile::getEnumAttachmentType, AttachmentType.getTypeValue(2)));
        if(CollectionUtils.isNotEmpty(personTrainingFiles)) {
            for(PersonTrainingFile a : personTrainingFiles) {
                // 设置mime
                int i = a.getFileUrl().indexOf(".");
                String contentType = getContentType(a.getFileUrl().substring(i + 1));
                a.setMime(contentType);
            }
        }
        return personTrainingFiles;
    }
 
    @Override
    public void deleteFile(Integer id) {
        personTrainingFileMapper.deleteById(id);
    }
 
    @Override
    public void fileDownLoad(Integer id, HttpServletResponse response) {
        // 根据id查询下载的文件
        PersonTrainingFile personTrainingFile = personTrainingFileMapper.selectById(id);
        if(Objects.nonNull(personTrainingFile)) {
            // 拿到文件路径
            String fileUrl = personTrainingFile.getFileUrl();
            int i = fileUrl.indexOf(".");
            String suffix = fileUrl.substring(i); // 文件后缀
            String url = "";
            if(suffix.toLowerCase().contains("xls")) {
                 url = excelUrl + File.separator + fileUrl;
            } else if (suffix.toLowerCase().contains("doc") || suffix.toLowerCase().contains("pdf")) {
                url = wordUrl + File.separator + fileUrl;
            }else {
                url = imgUrl + File.separator + fileUrl;
            }
            File file = new File(url);
            if(!file.exists()) {
                throw new ErrorException("文件不存在或损坏");
            }
            // 获取文件输入流
            try(FileInputStream fileInputStream = new FileInputStream(file); ServletOutputStream outputStream = response.getOutputStream()) {
                String contentType = getContentType(fileUrl.substring(i + 1));
                // 设置响应头
                response.setContentType(contentType);
                int i1 = personTrainingFile.getFileName().indexOf(".");
                String fileName = URLEncoder.encode(personTrainingFile.getFileName().substring(0, i1), "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + suffix);
                byte[] bytes = new byte[1024];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(bytes)) != -1 ){
                    outputStream.write(bytes,0,bytesRead);
                }
                outputStream.flush();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    // 根据文件扩展名获取 MIME 类型
    private String getContentType(String fileExtension) {
        switch (fileExtension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "pdf":
                return "application/pdf";
            case "doc":
                return "application/msword";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "xls":
                return "application/vnd.ms-excel";
            case "xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            case "ppt":
            case "pptx":
                return "application/vnd.ms-powerpoint";
            default:
                return "application/octet-stream"; // 默认二进制流
        }
    }
 
 
 
}