lxp
2025-03-13 b7c4edd36912d26aa2e8e6fa5605c370bb2e478a
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
package com.ruoyi.personnel.service.impl;
 
import cn.hutool.core.util.NumberUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.utils.DateImageUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.framework.util.HackLoopTableRenderPolicy;
import com.ruoyi.personnel.dto.PersonSupervisePlanDto;
import com.ruoyi.personnel.excel.PersonSupervisePlanDetailsListener;
import com.ruoyi.personnel.excel.PersonSupervisePlanDetailsUpload;
import com.ruoyi.personnel.mapper.PersonSupervisePlanDetailsMapper;
import com.ruoyi.personnel.mapper.PersonSupervisePlanMapper;
import com.ruoyi.personnel.mapper.PersonSupervisionRecordMapper;
import com.ruoyi.personnel.pojo.PersonSupervisePlan;
import com.ruoyi.personnel.pojo.PersonSupervisePlanDetails;
import com.ruoyi.personnel.pojo.PersonSupervisionRecord;
import com.ruoyi.personnel.service.PersonSupervisePlanDetailsService;
import com.ruoyi.personnel.service.PersonSupervisePlanService;
import com.ruoyi.system.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
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.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * <p>
 * 监督计划 - 父 服务实现类
 * </p>
 *
 * @author 芯导软件(江苏)有限公司
 * @since 2024-10-09 04:14:45
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class PersonSupervisePlanServiceImpl extends ServiceImpl<PersonSupervisePlanMapper, PersonSupervisePlan> implements PersonSupervisePlanService {
 
    @Resource
    private PersonSupervisePlanDetailsService personSupervisePlanDetailsService;
 
    @Resource
    private PersonSupervisePlanDetailsMapper personSupervisePlanDetailsMapper;
 
    @Resource
    private PersonSupervisionRecordMapper personSupervisionRecordMapper;
 
    @Value("${file.path}")
    private String imgUrl;
 
    @Autowired
    private UserMapper userMapper;
 
    public IPage<PersonSupervisePlanDto> yearPlanDtoIPage(Page page, String organizationPerson, Integer departId) {
        IPage<PersonSupervisePlanDto> personSupervisePlanDtoIPage = baseMapper.pageByPerson(page, organizationPerson, departId);
        List<PersonSupervisePlanDto> records = personSupervisePlanDtoIPage.getRecords();
        for(PersonSupervisePlanDto a : records) {
            a.setCurrentId(SecurityUtils.getUserId().intValue());
        }
        return personSupervisePlanDtoIPage;
    }
 
    @Override
    public void yearPlanDetailImport(MultipartFile file ,String suffix) {
        // 年度计划父级新增数据
        PersonSupervisePlan personSupervisePlan = new PersonSupervisePlan();
        String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        personSupervisePlan.setFileName(fileName);
        personSupervisePlan.setOrganizationPersonId(SecurityUtils.getUserId().intValue());
        personSupervisePlan.setOrganizationDate(LocalDateTime.now());
        baseMapper.insert(personSupervisePlan);
        List<List<String>> tableData = new ArrayList<>();
        String name = "";
        // 年度计划详情 新增
        try {
            if(suffix.toLowerCase().contains("xls")) {
                PersonSupervisePlanDetailsListener personSupervisePlanDetailsListener = new PersonSupervisePlanDetailsListener(personSupervisePlanDetailsService);
                personSupervisePlanDetailsListener.setPlanId(personSupervisePlan.getId());
                EasyExcel.read(file.getInputStream(), PersonSupervisePlanDetailsUpload.class, personSupervisePlanDetailsListener).sheet().doRead();
            }else if(suffix.toLowerCase().equals("doc"))  {
                try(InputStream inputStream = file.getInputStream();
                    HWPFDocument doc = new HWPFDocument(inputStream)) {
                    // 获取文档的 Range
                    Range range = doc.getRange();
                    // 遍历所有表格
                    TableIterator tableIterator = new TableIterator(range);
                    while (tableIterator.hasNext()) {
                        Table table = tableIterator.next();
                        // 遍历表格的每一行
                        for (int rowIdx = 0; rowIdx < table.numRows(); rowIdx++) {
                            TableRow row = table.getRow(rowIdx);
                            List<String> rowData = new ArrayList<>();
 
                            // 遍历行中的每个单元格
                            for (int cellIdx = 0; cellIdx < row.numCells(); cellIdx++) {
                                TableCell cell = row.getCell(cellIdx);
                                String text = cell.text().trim();
                                rowData.add(text);
                            }
                            tableData.add(rowData);
                        }
                    }
                    for (List<String> list : tableData) {
                        // 进行添加
                        addPersonSupervisePlanDetails(list,personSupervisePlan.getId());
                        if(StringUtils.isEmpty(name) && NumberUtil.isInteger(list.get(0))) {
                            String supervisePerson = list.get(4); // 被监督人员
                            name = supervisePerson;
                        }
                    }
                    // 根据添加数据被监督人 来判断该文件是哪个部门的
                    String departLimsId = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getName, name)).get(0).getDepartLimsId();
                    if(StringUtils.isNotEmpty(departLimsId) && departLimsId.contains("18")) {
                        baseMapper.update(null,new LambdaUpdateWrapper<PersonSupervisePlan>()
                                .set(PersonSupervisePlan::getDepartId,18)
                                .set(PersonSupervisePlan::getOrganizationPersonId,12) // 通信的是刘晨 (编制人)
                                .eq(PersonSupervisePlan::getId,personSupervisePlan.getId()));
                    } else if (StringUtils.isNotEmpty(departLimsId) && departLimsId.contains("19")) {
                        baseMapper.update(null,new LambdaUpdateWrapper<PersonSupervisePlan>()
                                .set(PersonSupervisePlan::getDepartId,19)
                                .set(PersonSupervisePlan::getOrganizationPersonId,41) // 电力的是吴明华 (编制人)
                                .eq(PersonSupervisePlan::getId,personSupervisePlan.getId()));
                    }
 
                log.info("读取文件: {}",tableData);
                }catch (Exception e) {
                    throw new ErrorException("导入失败"+ e);
                }
            }else if(suffix.toLowerCase().equals("docx")) {
                try(InputStream fileInputStream = file.getInputStream();XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream)) {
 
                    // 遍历所有表格
                    for(XWPFTable table : xwpfDocument.getTables()) {
                        // 遍历每一行
                        for(XWPFTableRow row : table.getRows()) {
                            List<String> list = new ArrayList<>();
                            // 遍历每一个单元格
                            for(XWPFTableCell cell : row.getTableCells()) {
                                String text = cell.getText();
                                list.add(text);
                            }
                            log.info("读取每一行的内容: {}",list);
                            // 进行添加
                            addPersonSupervisePlanDetails(list,personSupervisePlan.getId());
                           if(StringUtils.isEmpty(name) && NumberUtil.isInteger(list.get(0))) {
                               String supervisePerson = list.get(4); // 被监督人员
                               name = supervisePerson;
                           }
                        }
                    }
                    // 根据添加数据被监督人 来判断该文件是哪个部门的
                    String departLimsId = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getName, name)).get(0).getDepartLimsId();
                    if(StringUtils.isNotEmpty(departLimsId) && departLimsId.contains("18")) {
                        baseMapper.update(null,new LambdaUpdateWrapper<PersonSupervisePlan>()
                                .set(PersonSupervisePlan::getDepartId,18)
                                .eq(PersonSupervisePlan::getId,personSupervisePlan.getId()));
                    } else if (StringUtils.isNotEmpty(departLimsId) && departLimsId.contains("19")) {
                        baseMapper.update(null,new LambdaUpdateWrapper<PersonSupervisePlan>()
                                .set(PersonSupervisePlan::getDepartId,18)
                                .eq(PersonSupervisePlan::getId,personSupervisePlan.getId()));
                    }
                }catch (Exception e){
                    throw new ErrorException("导入失败"+e);
                }
            }
 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public void  addPersonSupervisePlanDetails(List<String> list,Integer planId) {
        if(NumberUtil.isInteger(list.get(0)) ) {
            String superviseDate = list.get(1); // 监督日期
            String superviseDes = list.get(2); // 监督目的
            String superviseProject = list.get(3); // 监督项目
            String supervisePerson = list.get(4); // 被监督人员
            String superviseReason = list.get(5); // 监督原因
            String remarks = list.get(6); // 备注
            PersonSupervisePlanDetails personSupervisePlanDetails = new PersonSupervisePlanDetails();
            LocalDate localDate = null;
            String[] parts = superviseDate.split("\\.");
            if (parts.length == 2) {
                try {
                    // 获取年份
                    int year = Integer.parseInt(parts[0]);
                    // 获取月份
                    int month = Integer.parseInt(parts[1]);
                    // 创建 LocalDate 对象,日期设为该月第一天
                    localDate = LocalDate.of(year, month, 1);
                } catch (NumberFormatException e) {
                   throw  new ErrorException("输入的字符串无法转换为有效的年份或月份: " + e.getMessage());
                }
            }
            personSupervisePlanDetails.setSuperviseDate(localDate);
            personSupervisePlanDetails.setSuperviseDes(superviseDes);
            personSupervisePlanDetails.setSuperviseProject(superviseProject);
            personSupervisePlanDetails.setSupervisePerson(supervisePerson);
            personSupervisePlanDetails.setSuperviseReason(superviseReason);
            personSupervisePlanDetails.setRemarks(remarks);
            personSupervisePlanDetails.setPlanId(planId); // 父id
            personSupervisePlanDetailsMapper.insert(personSupervisePlanDetails);
        }
    }
 
 
 
    /**
     * 导出人员监督计划
     * @param id
     * @param response
     */
    @Override
    public void exportSuperVisePlan(Integer id, HttpServletResponse response) {
        Map<String, Object> data = new HashMap<>();
        data.put("year","");
        data.put("supervisor","");
        // 查询详情
        PersonSupervisePlan personSupervisePlan = baseMapper.selectById(id);
 
 
        //获取提交人的签名地址
        String organizationUrl = userMapper.selectById(personSupervisePlan.getOrganizationPersonId()).getSignatureUrl();
        if (StringUtils.isBlank(organizationUrl)) {
            throw new ErrorException("找不到检验人的签名");
        }
 
        //获取批准人的签名地址
        String approvalUrl = null;
        if (personSupervisePlan.getApprovalId() != null) {
            approvalUrl = userMapper.selectById(personSupervisePlan.getApprovalId()).getSignatureUrl();
            if (StringUtils.isBlank(approvalUrl)) {
                throw new ErrorException("找不到批准人的签名");
            }
        }
 
        // 查询详情
        List<PersonSupervisePlanDetails> detailedDtos = personSupervisePlanDetailsService.list(Wrappers.<PersonSupervisePlanDetails>lambdaQuery()
                .eq(PersonSupervisePlanDetails::getPlanId, id));
 
 
        // 查询监督记录
        List<PersonSupervisionRecord> personSupervisionRecords = personSupervisionRecordMapper.selectList(new LambdaQueryWrapper<PersonSupervisionRecord>()
                .orderByAsc(PersonSupervisionRecord::getId));
        if(CollectionUtils.isNotEmpty(personSupervisionRecords)) {
            Integer supervisorId = personSupervisionRecords.get(0).getSupervisorId();
            String name = userMapper.selectById(supervisorId).getName();
            data.put("supervisor",name);
        }
 
 
        int index = 1;
        for (PersonSupervisePlanDetails detailedDto : detailedDtos) {
            detailedDto.setIndex(index);
            index++;
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = detailedDto.getSuperviseDate().format(dateTimeFormatter);
            detailedDto.setSuperviseDateString(format);
            int year = detailedDto.getSuperviseDate().getYear();
            data.put("year",year);
        }
        System.out.println("data: " + data);
        // 获取路径
        InputStream inputStream = this.getClass().getResourceAsStream("/static/super-vise-plan.docx");
        Configure configure = Configure.builder()
                .bind("supervisePlanDetailsList", new HackLoopTableRenderPolicy())
                .build();
        String finalApprovalUrl = approvalUrl;
        XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
                new HashMap<String, Object>() {{
                    put("data",data);
                    put("supervisePlanDetailsList", detailedDtos);
                    put("organizationUrl", StringUtils.isNotBlank(organizationUrl) ? Pictures.ofLocal(imgUrl + "/" + organizationUrl).create() : null);
                    put("approvalUrl", StringUtils.isNotBlank(finalApprovalUrl) ? Pictures.ofLocal(imgUrl + "/" + finalApprovalUrl).create() : null);
                    put("writeDateUrl", personSupervisePlan.getOrganizationDate() != null ?
                            Pictures.ofStream(DateImageUtil.createDateImage(personSupervisePlan.getOrganizationDate())).create() : null);
                    put("ratifyDateUrl", personSupervisePlan.getApprovalDate() != null ?
                            Pictures.ofStream(DateImageUtil.createDateImage(personSupervisePlan.getApprovalDate())).create() : null);
                }});
        try {
            response.setContentType("application/msword");
            String fileName = URLEncoder.encode(
                    "人员监督计划导出", "UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName + ".docx");
            OutputStream os = response.getOutputStream();
            template.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败");
        }
    }
}