TemplateGroupServiceImpl.java 30.1 KB
Newer Older
1 2
package pwc.taxtech.atms.service.impl;

eddie.woo's avatar
eddie.woo committed
3 4
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
eddie.woo's avatar
eddie.woo committed
5
import com.google.common.collect.Maps;
eddie.woo's avatar
eddie.woo committed
6 7
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
8
import org.apache.poi.ss.usermodel.*;
eddie.woo's avatar
eddie.woo committed
9
import org.springframework.beans.factory.annotation.Autowired;
10
import org.springframework.stereotype.Service;
11
import org.springframework.transaction.annotation.Propagation;
eddie.woo's avatar
eddie.woo committed
12 13
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
frank.xa.zhang's avatar
frank.xa.zhang committed
14
import pwc.taxtech.atms.common.CommonUtils;
eddie.woo's avatar
eddie.woo committed
15 16 17
import pwc.taxtech.atms.common.POIUtil;
import pwc.taxtech.atms.common.message.ErrorMessage;
import pwc.taxtech.atms.common.message.TemplateMessage;
eddie.woo's avatar
eddie.woo committed
18
import pwc.taxtech.atms.constant.Constant;
19
import pwc.taxtech.atms.constant.enums.CellDataSourceType;
frank.xa.zhang's avatar
frank.xa.zhang committed
20
import pwc.taxtech.atms.constant.enums.TemplateGroupType;
21
import pwc.taxtech.atms.dao.CellTemplateConfigDao;
22
import pwc.taxtech.atms.dao.CellTemplateConfigMapper;
23
import pwc.taxtech.atms.dao.CellTemplateDao;
24
import pwc.taxtech.atms.dao.CellTemplateMapper;
25 26
import pwc.taxtech.atms.dao.TemplateDao;
import pwc.taxtech.atms.dao.TemplateGroupDao;
27 28
import pwc.taxtech.atms.dao.TemplateGroupMapper;
import pwc.taxtech.atms.dao.TemplateMapper;
29
import pwc.taxtech.atms.dto.OperationResultDto;
frank.xa.zhang's avatar
frank.xa.zhang committed
30
import pwc.taxtech.atms.dto.TemplateGroupDto;
31 32 33 34 35 36 37 38
import pwc.taxtech.atms.entity.CellTemplate;
import pwc.taxtech.atms.entity.CellTemplateConfig;
import pwc.taxtech.atms.entity.CellTemplateConfigExample;
import pwc.taxtech.atms.entity.CellTemplateExample;
import pwc.taxtech.atms.entity.Template;
import pwc.taxtech.atms.entity.TemplateExample;
import pwc.taxtech.atms.entity.TemplateGroup;
import pwc.taxtech.atms.entity.TemplateGroupExample;
39
import pwc.taxtech.atms.exception.ServiceException;
40 41 42
import pwc.taxtech.atms.vat.dao.PeriodDataSourceMapper;
import pwc.taxtech.atms.vat.entity.PeriodCellData;
import pwc.taxtech.atms.vat.entity.PeriodDataSource;
43

eddie.woo's avatar
eddie.woo committed
44 45 46
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
47 48
import java.math.BigDecimal;
import java.util.*;
49
import java.util.stream.Collectors;
frank.xa.zhang's avatar
frank.xa.zhang committed
50

51
@Service
52
public class TemplateGroupServiceImpl extends AbstractService {
eddie.woo's avatar
eddie.woo committed
53
    @Autowired
eddie.woo's avatar
eddie.woo committed
54
    private HttpFileService httpFileService;
eddie.woo's avatar
eddie.woo committed
55 56 57 58 59 60 61
    @Autowired
    private TemplateGroupDao templateGroupDao;
    @Autowired
    private TemplateGroupMapper templateGroupMapper;
    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
eddie.woo's avatar
eddie.woo committed
62 63
    private TemplateDao templateDao;
    @Autowired
eddie.woo's avatar
eddie.woo committed
64 65
    private CellTemplateMapper cellTemplateMapper;
    @Autowired
eddie.woo's avatar
eddie.woo committed
66 67
    private CellTemplateDao cellTemplateDao;
    @Autowired
eddie.woo's avatar
eddie.woo committed
68
    private CellTemplateConfigMapper cellTemplateConfigMapper;
eddie.woo's avatar
eddie.woo committed
69 70
    @Autowired
    private CellTemplateConfigDao cellTemplateConfigDao;
71 72
    @Autowired
    private PeriodDataSourceMapper periodDataSourceMapper;
73

74
    public List<TemplateGroupDto> get() {
frank.xa.zhang's avatar
frank.xa.zhang committed
75 76 77 78 79 80 81 82 83 84
        List<TemplateGroup> templateGroups = templateGroupMapper.selectByExample(new TemplateGroupExample());
        List<TemplateGroupDto> templateGroupDtos = new ArrayList<>();
        for (TemplateGroup templateGroup : templateGroups) {
            TemplateGroupDto templateGroupDto = new TemplateGroupDto();
            CommonUtils.copyProperties(templateGroup, templateGroupDto);
            templateGroupDtos.add(templateGroupDto);
        }
        return templateGroupDtos;
    }

85
    public List<TemplateGroupDto> get(int serviceTypeId, Integer taxPayType, String industryId) {
frank.xa.zhang's avatar
frank.xa.zhang committed
86 87 88 89
        TemplateGroupExample example = new TemplateGroupExample();

        TemplateGroupExample.Criteria criteria = example.createCriteria();

90
        criteria.andServiceTypeIdEqualTo(String.valueOf(serviceTypeId)).andGroupTypeEqualTo(TemplateGroupType.TaxReturn.getCode());
frank.xa.zhang's avatar
frank.xa.zhang committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104

        if (taxPayType != null) {
            criteria.andPayTaxTypeEqualTo(TemplateGroupType.TaxReturn.getCode());
        }

        List<TemplateGroup> templateGroups = templateGroupMapper.selectByExample(example);
        List<TemplateGroupDto> templateGroupDtos = new ArrayList<>();
        for (TemplateGroup templateGroup : templateGroups) {
            TemplateGroupDto dto = new TemplateGroupDto();
            CommonUtils.copyProperties(templateGroup, dto);
            templateGroupDtos.add(dto);
        }
        return templateGroupDtos;
    }
105

106
    public OperationResultDto<Object> updateTemplateGroupName(TemplateGroupDto templateGroupDto) {
107
        TemplateGroup entity = templateGroupMapper.selectByPrimaryKey(Long.parseLong(templateGroupDto.getId()));
108
        TemplateGroupExample example = new TemplateGroupExample();
109
        example.createCriteria().andNameEqualTo(templateGroupDto.getName()).andIdNotEqualTo(Long.parseLong(templateGroupDto.getId())).andServiceTypeIdEqualTo(entity.getServiceTypeId()).andIndustryIdsEqualTo(entity.getIndustryIds()).andPayTaxTypeEqualTo(entity.getPayTaxType());
110 111 112 113
        List<TemplateGroup> templateGroups = templateGroupMapper.selectByExample(example);
        if (!templateGroups.isEmpty()) {
            OperationResultDto<Object> result = new OperationResultDto<>();
            result.setResult(false);
114
            result.setResultMsg(TemplateGroupMessage.TEMPLATE_GROUP_NAME_EXIST);
115 116 117 118 119 120 121 122
        }
        entity.setName(templateGroupDto.getName());
        templateGroupMapper.updateByPrimaryKey(entity);
        OperationResultDto<Object> result = new OperationResultDto<>();
        result.setResult(true);
        return result;
    }

123
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
124 125
    public OperationResultDto<Object> deleteTemplateGroup(TemplateGroupDto templateGroupDto) {
        OperationResultDto<Object> result = new OperationResultDto<>();
126
        TemplateGroup templateGroupDb = templateGroupMapper.selectByPrimaryKey(Long.parseLong(templateGroupDto.getId()));
127 128 129 130 131 132 133

        if (templateGroupDb.getIsSystemType()) {
            result.setResult(false);
            result.setResultMsg(TemplateGroupMessage.SYSTEM_TYPE_CANNOT_DELETE);
            return result;
        }

134
        List<String> userOranizationNameList = organizationServiceTemplateGroupMapper.getOrgnizationServiceTemplateGroupOrgNames(Long.parseLong(templateGroupDto.getId()));
135 136 137 138 139 140 141
        if (userOranizationNameList != null && !userOranizationNameList.isEmpty()) {
            result.setResult(false);
            result.setResultMsg(TemplateGroupMessage.ORGANIZATION_USED_TEMPLATE_GROUP);
            return result;
        }

        List<Template> allTemplateDbList = templateMapper.selectByExample(new TemplateExample());
142
        List<Template> templateDbList = allTemplateDbList.stream().filter(a -> a.getTemplateGroupId().equals(templateGroupDb.getId())).collect(Collectors.toList());
143 144 145
        List<String> pathList = new ArrayList<>();

        for (Template templateDb : templateDbList) {
146
            boolean anySameCodeExists = allTemplateDbList.stream().anyMatch(a -> a.getCode() == templateDb.getCode() && a.getName() == templateDb.getCode());
147 148 149 150 151 152

            if (!anySameCodeExists) {
                pathList.add((templateDb.getPath()));
            }
            deleteTemplate(templateDb);
        }
153
        templateGroupMapper.deleteByPrimaryKey(templateGroupDb.getId());
154 155 156 157 158 159 160

        result.setResult(true);
        result.setData(pathList);
        return result;
    }

    private void deleteTemplate(Template templateDb) {
161 162
        cellTemplateConfigMapper.deleteCellTemplateConfigByCellTemplate(templateDb.getId());
        keyValueReferenceMapper.deleteKeyValueReferenceByCellTemplate(templateDb.getId());
163
        CellTemplateExample example = new CellTemplateExample();
164
        example.createCriteria().andReportTemplateIdEqualTo(templateDb.getId());
165 166 167
        cellTemplateMapper.deleteByExample(example);
    }

168
    public class TemplateGroupMessage {
169 170 171
        static final String TEMPLATE_GROUP_NAME_EXIST = "TemplateGroupNameExist";
        static final String SYSTEM_TYPE_CANNOT_DELETE = "SystemTypeCannotDelete";
        static final String ORGANIZATION_USED_TEMPLATE_GROUP = "OrganizationUsedTemplateGroup";
172 173
    }

eddie.woo's avatar
eddie.woo committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    public List<String> getSheetNameList(MultipartFile file) {
        try {
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            List<String> nameList = Lists.newArrayList();
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                nameList.add(workbook.getSheetName(i));
            }
            return nameList;
        } catch (Exception e) {
            logger.error("getSheetNameList error.", e);
        }
        return Collections.emptyList();
    }

    @Transactional
189
    public void importTemplateGroupExcelFile(MultipartFile file, boolean allowManual, TemplateGroupDto templateGroupDto) throws ServiceException {
eddie.woo's avatar
eddie.woo committed
190 191 192 193 194 195 196 197 198 199 200 201 202
        List<String> sheetNameList = templateGroupDto.getSheetNameList();
        if (CollectionUtils.isEmpty(sheetNameList)) {
            throw new ServiceException(ErrorMessage.NoSelectSheet);
        }
        try {
            List<TemplateGroup> groupList = templateGroupDao.getByGroupName(templateGroupDto.getName());
            if (CollectionUtils.isNotEmpty(groupList)) {
                throw new ServiceException(TemplateMessage.TemplateGroupNameExist);
            }
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            Workbook workbook = WorkbookFactory.create(inputStream);
            List<Template> filePathList = Lists.newArrayList();
203
            Long templateGroupId = distributedIdService.nextId();
eddie.woo's avatar
eddie.woo committed
204 205 206
            Date now = new Date();
            TemplateGroup templateGroup = new TemplateGroup();
            CommonUtils.copyProperties(templateGroupDto, templateGroup);
207
            templateGroup.setId(templateGroupId);
eddie.woo's avatar
eddie.woo committed
208
            templateGroup.setGroupType(1);//todo 整理枚举
209
            templateGroup.setCopyFrom(0L);
eddie.woo's avatar
eddie.woo committed
210 211 212
            templateGroup.setIsSystemType(false);
            templateGroup.setUpdateTime(now);
            templateGroupMapper.insertSelective(templateGroup);
frank.xa.zhang's avatar
frank.xa.zhang committed
213
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
eddie.woo's avatar
eddie.woo committed
214
                String sheetName = workbook.getSheetName(i);
215
                if(!sheetNameList.contains(sheetName)){
sherlock's avatar
sherlock committed
216 217
                    continue;
                }
eddie.woo's avatar
eddie.woo committed
218 219 220 221 222 223 224 225
                String newName = sheetName + CommonUtils.getUUID() + POIUtil.getFileSuffix(fileName).get();
                Sheet sheet = workbook.getSheetAt(i);
                Optional<Workbook> optional = POIUtil.cloneNewSheet(sheet, fileName);
                if (!optional.isPresent()) {
                    throw new ServiceException(ErrorMessage.SystemError);
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                optional.get().write(bos);
eddie.woo's avatar
eddie.woo committed
226
                String tmpPath = httpFileService.uploadTemplate(newName, file);
eddie.woo's avatar
eddie.woo committed
227 228 229 230 231
                String[] arr = sheetName.split("_");
                String name = arr.length >= 2 ? arr[1] : arr[0];
                Template template = new Template();
                template.setCode(arr[0]);
                template.setCreateTime(now);
232
                template.setId(distributedIdService.nextId());
eddie.woo's avatar
eddie.woo committed
233 234 235 236 237 238
                template.setIsActiveAssociation(true);
                template.setIsSystemType(false);
                template.setName(name);
                template.setOrderIndex(i + 1);
                template.setPath(tmpPath);
//                template.setReportType(tmpPath);
239
                template.setTemplateGroupId(templateGroupId);
eddie.woo's avatar
eddie.woo committed
240 241 242 243
                filePathList.add(template);
                templateMapper.insertSelective(template);
                List<CellTemplate> cellTemplateList = Lists.newArrayList();
                List<CellTemplateConfig> cellTemplateConfigList = Lists.newArrayList();
244
                List<PeriodDataSource> periodDataSourceList = Lists.newArrayList();
frank.xa.zhang's avatar
frank.xa.zhang committed
245
                for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) {
eddie.woo's avatar
eddie.woo committed
246 247 248 249 250 251 252 253 254 255 256
                    Row row = sheet.getRow(r);
                    for (int c = row.getFirstCellNum(); c <= row.getLastCellNum(); c++) {
                        Cell cell = row.getCell(c);
                        if (cell == null) {
                            continue;//todo cell == null 如何处理
                        }
                        CellTemplate cellTemplate = new CellTemplate();
                        cellTemplate.setColumnIndex(c);
                        cellTemplate.setCreateTime(now);
                        cellTemplate.setUpdateTime(now);
                        cellTemplate.setRowIndex(r);
frank.xa.zhang's avatar
frank.xa.zhang committed
257 258 259 260 261 262 263
                        cellTemplate.setRowName(StringUtils.EMPTY);
                        cellTemplate.setColumnName(StringUtils.EMPTY);
                        cellTemplate.setComment(StringUtils.EMPTY);
                        cellTemplate.setCopyFromId(0L);
                        cellTemplate.setCreateBy("Admin");
                        cellTemplate.setUpdateBy("Admin");
                        cellTemplate.setDataType(0);
264
                        cellTemplate.setReportTemplateId(template.getId());
265
                        cellTemplate.setId(distributedIdService.nextId());
eddie.woo's avatar
eddie.woo committed
266 267 268
                        if (cell.getCellComment() != null) {
                            cellTemplate.setComment(cell.getCellComment().getString().getString());
                        }
frank.xa.zhang's avatar
frank.xa.zhang committed
269
                        cellTemplate.setIsReadOnly(cell.getCellStyle().getLocked());
eddie.woo's avatar
eddie.woo committed
270
                        cellTemplateList.add(cellTemplate);
eddie.woo's avatar
eddie.woo committed
271
                        //todo: 这里没有Config数据只有在上传模板以后,在界面里面可以配置公式
272
                        if (!cell.getCellStyle().getLocked() && hasKeyIn(cell)) {
eddie.woo's avatar
eddie.woo committed
273
                            cell.setCellValue(StringUtils.EMPTY);
274 275 276
                            if(allowManual){
                                addManualConfig(cellTemplate, template, cell, now, cellTemplateConfigList);
                            }
eddie.woo's avatar
eddie.woo committed
277
                        }
278
                        if(!cell.getCellStyle().getLocked() && StringUtils.isNotBlank(POIUtil.getCellFormulaString(cell))) {
279 280 281 282
                            CellTemplateConfig config = new CellTemplateConfig();
                            config.setId(distributedIdService.nextId());
                            config.setCellTemplateId(cellTemplate.getId());
                            config.setReportTemplateId(template.getId());
283
                            config.setDataSourceType(CellDataSourceType.Formula.getCode());//todo 枚举
284 285
                            config.setFormula(POIUtil.getCellFormulaString(cell));
//                        config.setFormula(cell.getCellFormula());
286
                            config.setFormulaDataSource("报表数据"); //todo KV相关
287 288 289
                            config.setUpdateTime(now);
                            config.setUpdateBy(authUserHelper.getCurrentUserId());
                            cellTemplateConfigList.add(config);
eddie.woo's avatar
eddie.woo committed
290 291
                            if (allowManual) {
                                addManualConfig(cellTemplate, template, cell, now, cellTemplateConfigList);
292 293
                            }

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
                            PeriodDataSource pds = new PeriodDataSource();
                            pds.setAmount(BigDecimal.ZERO);
                            pds.setUpdateBy("Admin");
                            pds.setUpdateTime(new Date());
                            pds.setId(distributedIdService.nextId());
                            pds.setCreateTime(new Date());
                            pds.setCellTemplateId(cellTemplate.getId());
                            pds.setCreateBy("Admin");
                            pds.setDescription(" ");
                            pds.setName("ReportDataSource");
                            Calendar cal = Calendar.getInstance();
                            pds.setPeriod(cal.get(Calendar.MONTH) + 1);
                            pds.setType(5);
                            pds.setColumnIndex(cell.getColumnIndex());
                            pds.setRowIndex(cell.getRowIndex());
                            periodDataSourceList.add(pds);
310
                        }
eddie.woo's avatar
eddie.woo committed
311 312 313
                    }
                }
                List<List<CellTemplate>> tmpList = CommonUtils.subListWithLen(cellTemplateList, CommonUtils.BATCH_NUM);
frank.xa.zhang's avatar
frank.xa.zhang committed
314
                tmpList.forEach(list -> cellTemplateMapper.batchInsert2(list));
eddie.woo's avatar
eddie.woo committed
315
                List<List<CellTemplateConfig>> tmpConfigList = CommonUtils.subListWithLen(cellTemplateConfigList, CommonUtils.BATCH_NUM);
eddie.woo's avatar
eddie.woo committed
316
                tmpConfigList.forEach(list -> cellTemplateConfigMapper.batchInsert(list));
317 318
                List<List<PeriodDataSource>> tmpPeriodList = CommonUtils.subListWithLen(periodDataSourceList, CommonUtils.BATCH_NUM);
                tmpPeriodList.forEach(list -> periodDataSourceMapper.batchInsert(list));
eddie.woo's avatar
eddie.woo committed
319 320 321 322 323 324 325 326
            }

        } catch (Exception e) {
            logger.error("importTemplateGroupExcelFile error.", e);
            throw new ServiceException(ErrorMessage.SystemError);
        }
    }

eddie.woo's avatar
eddie.woo committed
327
    @Transactional
328
    public void importTemplateExcelFile(MultipartFile file, boolean allowManual, Long templateGroupId, String reportType, String sheetList) throws ServiceException {
eddie.woo's avatar
eddie.woo committed
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
        if (null == file) {
            throw new ServiceException(ErrorMessage.NoFile);
        }
        try {
            if (StringUtils.isBlank(sheetList)) {
                throw new ServiceException(ErrorMessage.NoSelectSheet);
            }
            List<String> sheetNameList = JSON.parseArray(sheetList, String.class);
            if (CollectionUtils.isEmpty(sheetNameList)) {
                throw new ServiceException(ErrorMessage.NoSelectSheet);
            }
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            Workbook workbook = WorkbookFactory.create(inputStream);
            List<Template> filePathList = Lists.newArrayList();
            Date now = new Date();
sherlock's avatar
sherlock committed
345 346 347
            TemplateExample t = new TemplateExample();
            t.createCriteria().andTemplateGroupIdEqualTo(templateGroupId);
            int length = templateMapper.selectByExample(t).size();
348
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
eddie.woo's avatar
eddie.woo committed
349
                String sheetName = workbook.getSheetName(i);
350 351 352
                if(!sheetNameList.contains(sheetName)){
                    continue;
                }
eddie.woo's avatar
eddie.woo committed
353 354 355 356 357 358 359
                String newName = sheetName + CommonUtils.getUUID() + POIUtil.getFileSuffix(fileName).get();
                Sheet sheet = workbook.getSheetAt(i);
                Optional<Workbook> optional = POIUtil.cloneNewSheet(sheet, fileName);
                if (!optional.isPresent()) {
                    throw new ServiceException(ErrorMessage.SystemError);
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
sherlock's avatar
sherlock committed
360 361 362 363 364 365
                Workbook wtemp = optional.get();
                Sheet temp = wtemp.getSheetAt(0);
                for(int j = temp.getFirstRowNum(); j < temp.getLastRowNum(); j ++){
                    Row row = temp.getRow(j);
                    for(int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++){
                        Cell cell = row.getCell(k);
sherlock's avatar
sherlock committed
366
                        cell.setCellType(CellType.STRING);
sherlock's avatar
sherlock committed
367
                        if(!cell.getCellStyle().getLocked()  && "${KeyIn}".equalsIgnoreCase(cell.getStringCellValue())){
sherlock's avatar
sherlock committed
368 369 370 371 372
                            cell.setCellValue("");
                        }
                    }
                }
                wtemp.write(bos);
eddie.woo's avatar
eddie.woo committed
373
                String tmpPath = httpFileService.uploadTemplate(newName, file);
eddie.woo's avatar
eddie.woo committed
374 375 376 377 378
                String[] arr = sheetName.split("_");
                String name = arr.length >= 2 ? arr[1] : arr[0];
                Template template = new Template();
                template.setCode(arr[0]);
                template.setCreateTime(now);
379
                template.setId(distributedIdService.nextId());
eddie.woo's avatar
eddie.woo committed
380 381 382
                template.setIsActiveAssociation(true);
                template.setIsSystemType(false);
                template.setName(name);
sherlock's avatar
sherlock committed
383
                template.setOrderIndex(i + length);
eddie.woo's avatar
eddie.woo committed
384 385
                template.setPath(tmpPath);
                template.setReportType(StringUtils.isBlank(reportType) ? null : Integer.valueOf(reportType));
386
                template.setTemplateGroupId(templateGroupId);
eddie.woo's avatar
eddie.woo committed
387 388 389 390
                filePathList.add(template);
                templateMapper.insertSelective(template);
                List<CellTemplate> cellTemplateList = Lists.newArrayList();
                List<CellTemplateConfig> cellTemplateConfigList = Lists.newArrayList();
391
                List<PeriodDataSource> periodDataSourceList = Lists.newArrayList();
392
                for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) {
eddie.woo's avatar
eddie.woo committed
393 394 395 396 397 398 399 400 401 402 403
                    Row row = sheet.getRow(r);
                    for (int c = row.getFirstCellNum(); c <= row.getLastCellNum(); c++) {
                        Cell cell = row.getCell(c);
                        if (cell == null) {
                            continue;//todo cell == null 如何处理
                        }
                        CellTemplate cellTemplate = new CellTemplate();
                        cellTemplate.setColumnIndex(c);
                        cellTemplate.setCreateTime(now);
                        cellTemplate.setUpdateTime(now);
                        cellTemplate.setRowIndex(r);
404
                        cellTemplate.setReportTemplateId(template.getId());
405
                        cellTemplate.setId(distributedIdService.nextId());
eddie.woo's avatar
eddie.woo committed
406 407 408
                        if (cell.getCellComment() != null) {
                            cellTemplate.setComment(cell.getCellComment().getString().getString());
                        }
409
                        cellTemplate.setIsReadOnly(cell.getCellStyle().getLocked() ? true : false);
eddie.woo's avatar
eddie.woo committed
410
                        cellTemplateList.add(cellTemplate);
eddie.woo's avatar
eddie.woo committed
411
                        //todo: 这里没有Config数据只有在上传模板以后,在界面里面可以配置公式
412
                        if (!cell.getCellStyle().getLocked() && hasKeyIn(cell)) {
eddie.woo's avatar
eddie.woo committed
413
                            cell.setCellValue(StringUtils.EMPTY);
414 415 416
                            if(allowManual){
                                addManualConfig(cellTemplate, template, cell, now, cellTemplateConfigList);
                            }
eddie.woo's avatar
eddie.woo committed
417
                        }
418
                        if(!cell.getCellStyle().getLocked() && StringUtils.isNotBlank(POIUtil.getCellFormulaString(cell))) {
sherlock's avatar
sherlock committed
419 420 421 422 423 424 425
                            CellTemplateConfig config = new CellTemplateConfig();
                            config.setId(distributedIdService.nextId());
                            config.setCellTemplateId(cellTemplate.getId());
                            config.setReportTemplateId(template.getId());
                            config.setDataSourceType(1);//todo 枚举
                            config.setFormula(POIUtil.getCellFormulaString(cell));
//                        config.setFormula(cell.getCellFormula());
426
                            config.setFormulaDataSource("报表数据"); //todo KV相关
sherlock's avatar
sherlock committed
427 428 429
                            config.setUpdateTime(now);
                            config.setUpdateBy(authUserHelper.getCurrentUserId());
                            cellTemplateConfigList.add(config);
eddie.woo's avatar
eddie.woo committed
430 431 432
                            //noinspection Duplicates
                            if (allowManual) {
                                addManualConfig(cellTemplate, template, cell, now, cellTemplateConfigList);
433
                            }
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
                            PeriodDataSource pds = new PeriodDataSource();
                            pds.setAmount(BigDecimal.ZERO);
                            pds.setUpdateBy("Admin");
                            pds.setUpdateTime(new Date());
                            pds.setId(distributedIdService.nextId());
                            pds.setCreateTime(new Date());
                            pds.setCellTemplateId(cellTemplate.getId());
                            pds.setCreateBy("Admin");
                            pds.setDescription(" ");
                            pds.setName("ReportDataSource");
                            Calendar cal = Calendar.getInstance();
                            pds.setPeriod(cal.get(Calendar.MONTH) + 1);
                            pds.setType(5);
                            pds.setColumnIndex(cell.getColumnIndex());
                            pds.setRowIndex(cell.getRowIndex());
                            periodDataSourceList.add(pds);
sherlock's avatar
sherlock committed
450
                        }
eddie.woo's avatar
eddie.woo committed
451 452 453
                    }
                }
                List<List<CellTemplate>> tmpList = CommonUtils.subListWithLen(cellTemplateList, CommonUtils.BATCH_NUM);
eddie.woo's avatar
eddie.woo committed
454 455
//                tmpList.forEach(list -> cellTemplateMapper.batchInsert2(list));
                tmpList.forEach(list -> cellTemplateDao.batchInsert(list));//todo 批量插入优化
eddie.woo's avatar
eddie.woo committed
456
                List<List<CellTemplateConfig>> tmpConfigList = CommonUtils.subListWithLen(cellTemplateConfigList, CommonUtils.BATCH_NUM);
eddie.woo's avatar
eddie.woo committed
457
                tmpConfigList.forEach(list -> cellTemplateConfigDao.batchInsert(list));
458 459
                List<List<PeriodDataSource>> tmpPeriodList = CommonUtils.subListWithLen(periodDataSourceList, CommonUtils.BATCH_NUM);
                tmpPeriodList.forEach(list -> periodDataSourceMapper.batchInsert(list));
eddie.woo's avatar
eddie.woo committed
460 461 462 463 464 465 466
            }
        } catch (Exception e) {
            logger.error("importTemplateExcelFile error.", e);
            throw new ServiceException(ErrorMessage.SystemError);
        }
    }

eddie.woo's avatar
eddie.woo committed
467 468 469 470 471 472 473
    @Transactional
    public void addTemplateGroup(TemplateGroupDto templateGroupDto) throws ServiceException {
        List<TemplateGroup> groupList = templateGroupDao.getByGroupName(templateGroupDto.getName());
        if (CollectionUtils.isNotEmpty(groupList)) {
            throw new ServiceException(TemplateMessage.TemplateGroupNameExist);
        }
        try {
474
            String uid = authUserHelper.getCurrentUserId();
475
            TemplateGroup templateGroup = templateGroupMapper.selectByPrimaryKey(Long.parseLong(templateGroupDto.getCopyFrom()));
476 477
            Long newGroupId = distributedIdService.nextId();
            Long groupId = templateGroup.getId();
eddie.woo's avatar
eddie.woo committed
478
            Date now = new Date();
479 480
            templateGroup.setCopyFrom(groupId);
            templateGroup.setId(newGroupId);
eddie.woo's avatar
eddie.woo committed
481 482
            templateGroup.setCreateTime(now);
            templateGroup.setUpdateTime(now);
483
            templateGroup.setName(templateGroupDto.getName());
eddie.woo's avatar
eddie.woo committed
484
            templateGroupMapper.insertSelective(templateGroup);
485
            List<Template> templateList = templateDao.getByGroupId(groupId);
eddie.woo's avatar
eddie.woo committed
486
            templateList.stream().forEach(item -> {
487 488 489 490
                Long itemId = item.getId();
                Long newItemId = distributedIdService.nextId();
                item.setId(newItemId);
                item.setTemplateGroupId(newGroupId);
eddie.woo's avatar
eddie.woo committed
491 492 493
                item.setCreateTime(now);
                item.setUpdateTime(now);
                templateMapper.insertSelective(item);
494
                List<CellTemplate> cellTemplateList = cellTemplateDao.getByTemplateId(itemId);
495
                Map<Long, Long> idMapper = Maps.newHashMap();
eddie.woo's avatar
eddie.woo committed
496
                List<List<CellTemplate>> tmpList = CommonUtils.subListWithLen(cellTemplateList.stream().map(cell -> {
497 498 499 500 501
                    Long cellId = cell.getId();
                    Long newCellId = distributedIdService.nextId();
                    cell.setCopyFromId(cellId);
                    cell.setId(newCellId);
                    cell.setReportTemplateId(newItemId);
eddie.woo's avatar
eddie.woo committed
502 503
                    cell.setCreateTime(now);
                    cell.setUpdateTime(now);
504
                    idMapper.put(cellId, newCellId);
eddie.woo's avatar
eddie.woo committed
505 506
                    return cell;
                }).collect(Collectors.toList()), CommonUtils.BATCH_NUM);
507
                tmpList.forEach(list -> cellTemplateMapper.batchInsert2(list));
eddie.woo's avatar
eddie.woo committed
508

509
                List<CellTemplateConfig> configList = getByTemplateId(itemId);
eddie.woo's avatar
eddie.woo committed
510
                List<List<CellTemplateConfig>> tmpConfigList = CommonUtils.subListWithLen(configList.stream().map(cell -> {
511
                    Long newCellId = distributedIdService.nextId();
512 513
                    cell.setCreateBy(uid);
                    cell.setUpdateBy(uid);
514 515
                    cell.setId(newCellId);
                    cell.setReportTemplateId(newItemId);
516
                    cell.setCellTemplateId(idMapper.get(cell.getCellTemplateId()));
eddie.woo's avatar
eddie.woo committed
517 518 519 520 521 522 523 524 525 526 527 528 529
                    cell.setCreateTime(now);
                    cell.setUpdateTime(now);
                    return cell;
                }).collect(Collectors.toList()), CommonUtils.BATCH_NUM);
                tmpConfigList.forEach(list -> cellTemplateConfigMapper.batchInsert(list));
            });
        } catch (Exception e) {
            logger.error("addTemplateGroup error.", e);
            throw new ServiceException(ErrorMessage.SystemError);
        }

    }

530
    private List<CellTemplateConfig> getByTemplateId(Long id) {
531 532 533 534 535 536
        CellTemplateConfigExample example = new CellTemplateConfigExample();
        CellTemplateConfigExample.Criteria criteria = example.createCriteria();
        criteria.andReportTemplateIdEqualTo(id);
        return cellTemplateConfigMapper.selectByExample(example);
    }

eddie.woo's avatar
eddie.woo committed
537 538 539 540 541 542 543 544 545
    /**
     * 替换占位符
     * @param cell cell
     * @return Boolean
     */
    private Boolean hasKeyIn(Cell cell) {
        if (null == cell) {
            return false;
        }
eddie.woo's avatar
eddie.woo committed
546 547 548 549
        CellType cellType = cell.getCellTypeEnum();
        if (!CellType.STRING.equals(cellType)) {
            return false;
        }
eddie.woo's avatar
eddie.woo committed
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
        String v = cell.getStringCellValue();
        if (StringUtils.isBlank(v)) {
            return false;
        }
        return StringUtils.equals(v, Constant.ReplaceKeyword.KEY_IN);
    }

    /**
     * 添加手工数据源
     */
    private void addManualConfig(CellTemplate cellTemplate, Template template, Cell cell, Date now, List<CellTemplateConfig> list) {
        CellTemplateConfig configManual = new CellTemplateConfig();
        configManual.setId(distributedIdService.nextId());
        configManual.setCellTemplateId(cellTemplate.getId());
        configManual.setReportTemplateId(template.getId());
        configManual.setDataSourceType(CellDataSourceType.KeyIn.getCode());
        configManual.setFormula(POIUtil.getCellFormulaString(cell));
//        config.setFormula(cell.getCellFormula());
//        configManual.setFormulaDataSource("报表数据"); //todo KV相关
        configManual.setUpdateTime(now);
        configManual.setUpdateBy(authUserHelper.getCurrentUserId());
        list.add(configManual);
    }

574
}