CZT
2023-09-06 71c4fa1e27f75ae4b765c95c67a3069c84dc72ba
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package com.ld.igds.inout.manager;
 
import com.bstek.dorado.annotation.Expose;
import com.ld.igds.constant.FoodVariety;
import com.ld.igds.constant.RespCodeEnum;
import com.ld.igds.data.PageResponse;
import com.ld.igds.file.CoreFileService;
import com.ld.igds.inout.dto.InoutParam;
import com.ld.igds.m.dto.NoticeInData;
import com.ld.igds.m.service.InoutCommonService;
import com.ld.igds.m.service.HInoutCustomerService;
import com.ld.igds.models.InoutCustomer;
import com.ld.igds.util.ContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 解析Excel文件
 *
 * @author
 */
@Component(ExcelManager.BEAN_ID)
public class ExcelManager {
 
    public static final String BEAN_ID = "sys.execlManager";
 
    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";
 
    @Autowired
    private CoreFileService fileService;
    @Autowired
    private InoutCommonService inoutManagerService;
    @Autowired
    private HInoutCustomerService customerService;
 
    /**
     * sys.execlManager#updateExcelData
     *
     * @param   fileName
     * @return
     */
    @Expose
    public PageResponse<String> updateExcelData(String fileName) {
 
        // 读取的Excel文件数据
        List<NoticeInData> readResult = readExcel(fileName);
        if (null == readResult) {
            return new PageResponse<String>(RespCodeEnum.CODE_1111.getCode(),
                    "导入失败:没有解析到文件中数据!");
        }
 
        // 查询到的所有供应商信息
        InoutParam param = new InoutParam();
        List<InoutCustomer> allCustomer = inoutManagerService.listCustomer(param);
 
        //新建任务存放集合
        List<NoticeInData> newCustomerTaskList = new ArrayList<>();
        Map<String, NoticeInData> newMap = new HashMap<>();
 
        //存放编码和名称不一致的信息
        StringBuilder stringBuilder = new StringBuilder();
 
        //用tempFlag在后面来判断解析到的客户是否在客户表中存在
        boolean tempFlag;
 
        int max = 0;
        for (NoticeInData noticeInData : readResult) {
            //获取客户任务数据中的客户名称和编码
            String customerName = noticeInData.getCustomerName();
            String customerId = noticeInData.getCustomerId();
            //判断编码是否为空,为空则给出提示,不进行操作
            if(StringUtils.isEmpty(customerName)){
                stringBuilder.append("客户‘").append(customerName).append("’信息不完整,不导入此条数据;\n");
                continue;
            }
 
            tempFlag = true;
 
            for (InoutCustomer customer : allCustomer) {
                //获取供应商名称和编码
                String name = customer.getName();
                String id = customer.getId();
                //判断名称是否相同
                if(customerName.equals(name)){
                    //名称相同,则客户在表中存在
                    tempFlag = false;
                    //判断编码是否相同
                    if(StringUtils.isEmpty(customerId) || !id.equals(customerId)){
 
                        noticeInData.setCustomerId(id);
                    }
                    noticeInData.setCompanyId(customer.getCompanyId());
                    //身份证号
                    if(StringUtils.isEmpty(noticeInData.getCardId())){
                        noticeInData.setCardId(customer.getCardId());
                    }
                    //地址
                    if(StringUtils.isEmpty(noticeInData.getAddress())){
                        noticeInData.setAddress(customer.getAddress());
                    }
                    //电话
                    if(StringUtils.isEmpty(noticeInData.getPhone())){
                        noticeInData.setPhone(customer.getPhone());
                    }
                    //一卡通号
                    if(StringUtils.isEmpty(noticeInData.getBankNum())){
                        noticeInData.setBankNum(customer.getBankNum());
                    }
                }
            }
 
            if(tempFlag){
                if(max == 0){
                    max = Integer.parseInt(inoutManagerService.getMaxCustomerId(null));
                }
                max += 1;
                noticeInData.setCustomerId(max + "");
            }
 
            newCustomerTaskList.add(noticeInData);
 
            newMap.putIfAbsent(noticeInData.getCustomerName(), noticeInData);
        }
 
        //更新客户信息表
        if(newMap.size() > 0){
            for (NoticeInData noticeInData : newMap.values()) {
                int i = inoutManagerService.updateCustomer(noticeInData);
                if (i == 0) {
                    //说明没有更新到客户信息,进行新增
                    InoutCustomer data = new InoutCustomer();
                    data.setId(noticeInData.getCustomerId());
                    data.setName(noticeInData.getCustomerName());
                    data.setCardId(noticeInData.getCardId());
                    data.setBankNum(noticeInData.getBankNum());
                    data.setAddress(noticeInData.getAddress());
                    data.setPhone(noticeInData.getPhone());
                    customerService.saveOrUpdateData(data);
                }
            }
        }
 
        //判断任务集合是否为空
        if (newCustomerTaskList.isEmpty()) {
            return new PageResponse<String>(RespCodeEnum.CODE_1111.getCode(),
                    "导入失败!\n" + stringBuilder.toString());
        } else {
            //更新任务表
            int temp = 1;
            for (NoticeInData noticeInData : newCustomerTaskList) {
                //设置客户通知单的组织编码等信息
                noticeInData.setCompanyId(ContextUtil.getCompanyId());
                noticeInData.setDeptId(ContextUtil.subDeptId(null));
                noticeInData.setCreateUser(ContextUtil.getLoginUserCName());
                if(temp < 10){
                    noticeInData.setId(ContextUtil.getTimeId() + "00" + temp);
                }else if(temp < 100){
                    noticeInData.setId(ContextUtil.getTimeId() + "0" + temp);
                }else {
                    noticeInData.setId(ContextUtil.getTimeId() + temp);
                }
 
                //更新客户任务信息,如果更新失败,则进行插入操作
                inoutManagerService.updateNoticeIn(noticeInData);
                temp += 1;
            }
            if(StringUtils.isEmpty(stringBuilder.toString())){
                return new PageResponse<String>(RespCodeEnum.CODE_0000.getCode(), "数据全部导入成功!");
            }else {
                String message = "数据部分导入成功!\n"+ stringBuilder.toString();
                return new PageResponse<String>(RespCodeEnum.CODE_0000.getCode(), message);
            }
 
        }
    }
 
    /**
     * 读取Excel文件内容
     *
     * @param
     * @return
     */
    public List<NoticeInData> readExcel(String fileName) {
 
        //获取文件后缀名并判断
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
 
        //获取保存路径
        String path = fileService.getTempFilePath();
        path = path + fileName;
 
        Workbook workbook = null;
        FileInputStream inputStream = null;
 
        try {
            // 获取Excel文件
            File excelFile = new File(path);
            if (!excelFile.exists()) {
                return null;
            }
            // 获取Excel工作簿
            inputStream = new FileInputStream(excelFile);
            workbook = getWorkbook(inputStream, fileType);
 
            // 读取excel中的数据
            return parseExcel(workbook);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 根据文件后缀名类型获取对应的工作簿对象
     * @param inputStream 读取文件的输入流
     * @param fileType 文件后缀名类型(xls或xlsx)
     * @return 包含文件数据的工作簿对象
     * @throws IOException
     */
    public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
        Workbook workbook = null;
        if (fileType.equalsIgnoreCase(XLS)) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileType.equalsIgnoreCase(XLSX)) {
            workbook = new XSSFWorkbook(inputStream);
        }
        return workbook;
    }
 
    /**
     * 解析Excel数据
     *
     * @param workbook
     * @return
     */
    private static List<NoticeInData> parseExcel(Workbook workbook) {
        List<NoticeInData> resultDataList = new ArrayList<>();
        //int numberOfSheets = workbook.getNumberOfSheets();
        // 解析sheet
        for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            Sheet sheet = workbook.getSheetAt(sheetNum);
 
            // 校验sheet是否合法
            if (sheet == null) {
                continue;
            }
 
            // 获取第一行数据,不用处理
            int firstRowNum = sheet.getFirstRowNum();
 
            // 解析每一行的数据,构造数据对象
            int rowStart = firstRowNum + 1;
            int rowEnd = sheet.getPhysicalNumberOfRows();
 
            //定义变量,用于判断数据是否解析完
            boolean flag = false;
 
            for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
                Row row = sheet.getRow(rowNum);
 
                if (null == row) {
                    //此行为空,则之后不再解析,判定为解析完成
                    flag = true;
                    break;
                }
 
                NoticeInData resultData = convertRowToData(row);
 
                String customerName = resultData.getCustomerName();
                String customerId = resultData.getCustomerId();
                if(customerName.isEmpty() && customerId.isEmpty()){
                    //此行数据中如果用户名和编码都为空,则之后不解析,判定解析完成
                    flag = true;
                    break;
                }
                resultDataList.add(resultData);
            }
            if(flag){
                break;
            }
        }
        return resultDataList;
    }
 
    /**
     * 提取每一行中需要的数据,构造成为一个结果数据对象
     *
     * @param row
     * @return
     */
    private static NoticeInData convertRowToData(Row row) {
        NoticeInData resultData = new NoticeInData();
 
        Cell cell;
        int cellNum = 0;
 
        //获取并设置用户编码
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setCustomerId("");
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String customerId = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(customerId)){
                resultData.setCustomerId(customerId);
            }
        }
 
        //获取并设置姓名
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setCustomerName("");
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String name = cell.getStringCellValue().trim().replaceAll(" ","");
            if(StringUtils.isNotEmpty(name)){
                resultData.setCustomerName(name);
            }
        }
 
        //获取并设置身份证号
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setCardId("");
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String cardId = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(cardId)){
                resultData.setCardId(cardId);
            }
        }
 
        //获取并设置一卡通号
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setBankNum("");
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String bankNum = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(bankNum)){
                resultData.setBankNum(bankNum);
            }
        }
 
        //获取并设置地址
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setAddress("");
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String address = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(address)){
                resultData.setAddress(address);
            }
        }
 
        //获取并设置电话
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setPhone("");
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String phoneNum = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(phoneNum)){
                resultData.setPhone(phoneNum);
            }
        }
 
        //获取并设置任务数量
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setTargetNumber(0.0);
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String taskNum = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(taskNum)){
                resultData.setTargetNumber(Double.valueOf(taskNum));
            }
        }
 
        //获取并设置面积
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setFoodArea(0.0);
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String area = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(area)){
                resultData.setFoodArea(Double.valueOf(area));
            }
        }
 
        //获取并设置品种
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setFoodVariety("");
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String breed = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(breed)){
                resultData.setFoodVariety(FoodVariety.getCode(breed.trim()));
            }
        }
 
        //获取并设置年份
        cell = row.getCell(cellNum++);
        if(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
            resultData.setYear("");
        }else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String year = cell.getStringCellValue().trim();
            if(StringUtils.isNotEmpty(year)){
                resultData.setYear(year);
            }
        }
 
        return resultData;
    }
}