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
package com.ruoyi.basic.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.dto.*;
import com.ruoyi.basic.mapper.ProductMapper;
import com.ruoyi.basic.mapper.ProductModelMapper;
import com.ruoyi.basic.pojo.Product;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.basic.service.IProductModelService;
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.other.mapper.TempFileMapper;
import com.ruoyi.other.service.impl.TempFileServiceImpl;
import com.ruoyi.production.mapper.ProductProcessMapper;
import com.ruoyi.production.pojo.ProductProcess;
import com.ruoyi.sales.mapper.CommonFileMapper;
import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
import com.ruoyi.sales.service.impl.CommonFileServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-19
 */
@Service
@AllArgsConstructor
public class ProductModelServiceImpl extends ServiceImpl<ProductModelMapper, ProductModel> implements IProductModelService {
 
    private final ProductMapper productMapper;
    private final SalesLedgerProductMapper salesLedgerProductMapper;
    private ProductModelMapper productModelMapper;
    private final CommonFileServiceImpl commonFileService;
    private final ProductProcessMapper productProcessMapper;
 
    private final TempFileServiceImpl tempFileService;
 
    @Override
    public int addOrEditProductModel(ProductModelDto productModelDto) throws IOException {
        if(StringUtils.isEmpty(productModelDto.getProductName())){
            throw new RuntimeException("产品名称不能为空");
        }
        Product product = productMapper.selectOne(new LambdaQueryWrapper<Product>()
//                        .eq(Product::getModel, productModelDto.getModel())
                        .eq(Product::getProductName, productModelDto.getProductName()));
        if (productModelDto.getId() == null) {
            if(product == null){
                product = new Product();
                product.setProductName(productModelDto.getProductName());
                productMapper.insert(product);
            }
            ProductModel productModel = new ProductModel();
            BeanUtils.copyProperties(productModelDto,productModel);
            productModel.setProductId(product.getId());
            productModelMapper.insert(productModel);
            if(CollectionUtils.isNotEmpty(productModelDto.getTempFileIds())){
                commonFileService.migrateTempFilesToFormal(productModel.getId(), productModelDto.getTempFileIds());
            }
            return 1;
        } else {
            Product product1 = productMapper.selectById(productModelDto.getProductId());
            if(product1 != null){
                product1.setProductName(productModelDto.getProductName());
                productMapper.updateById(product1);
            }
            commonFileService.deleteByBusinessIds(Collections.singletonList(productModelDto.getId()), FileNameType.PRODUCT_MODEL.getValue());
            if(CollectionUtils.isNotEmpty(productModelDto.getTempFileIds())){
                commonFileService.migrateTempFilesToFormal(productModelDto.getId(), productModelDto.getTempFileIds());
            }
            return productModelMapper.updateById(productModelDto);
        }
 
    }
 
 
 
    @Override
    public int delProductModel(Long[] ids) {
        List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectList(new QueryWrapper<SalesLedgerProduct>()
                .lambda().in(SalesLedgerProduct::getProductModelId, ids));
        if (salesLedgerProducts != null && salesLedgerProducts.size() > 0) {
 
            throw new RuntimeException("已经存在该产品的销售台账和采购台账");
        }
        return productModelMapper.deleteBatchIds(Arrays.asList(ids));
    }
 
    @Override
    public List<ProductModel> selectModelList(ProductDto productDto) {
        LambdaQueryWrapper<ProductModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductModel::getProductId, productDto.getId());
        return productModelMapper.selectList(queryWrapper);
    }
 
    /**
     * 根据id查询产品规格分页查询
     * @param page
     * @param productDto
     * @return
     */
    @Override
    public IPage<ProductModel> modelListPage(Page page, ProductDto productDto) {
        LambdaQueryWrapper<ProductModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductModel::getProductId, productDto.getId());
        return productModelMapper.selectPage(page, queryWrapper);
    }
 
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importProduct(MultipartFile file, HttpServletResponse response) {
        ExcelUtil<ProductModelExcelCopyDto> productModelExcelUtil = new ExcelUtil<>(ProductModelExcelCopyDto.class);
        List<ProductModelExcelCopyDto> productModelList = null;
        try {
            productModelList = productModelExcelUtil.importExcel(file.getInputStream());
        }catch (Exception e) {
            throw new ServiceException("文件解析失败");
        }
        if(CollectionUtils.isNotEmpty(productModelList)){
            // 2. 按产品名称,图纸编号分组
            Map<Map.Entry<String, String>, List<ProductModelExcelCopyDto>> groupedByProductNameAndDrawingNumber =
                    productModelList.stream()
                            .collect(Collectors.groupingBy(
                                    dto -> new AbstractMap.SimpleEntry<>(
                                            dto.getProductName(),
                                            dto.getModel()
                                    )
                            ));
            List<ProductModelExcelCopyErrorDto> errorList = new ArrayList<>();
            // 2. 遍历分组结果处理数据
            for (Map.Entry<Map.Entry<String, String>, List<ProductModelExcelCopyDto>> entry : groupedByProductNameAndDrawingNumber.entrySet()) {
                Map.Entry<String, String> groupKey = entry.getKey();
                String productName = groupKey.getKey(); // 产品名称
                String drawingNumber = groupKey.getValue(); // 图纸编号
                List<ProductModelExcelCopyDto> dtoList = entry.getValue();
 
                // 空列表跳过,避免后续NPE
                if (CollectionUtils.isEmpty(dtoList)) {
                    continue;
                }
                ProductModelExcelCopyDto firstDto = dtoList.get(0);
                String model = firstDto.getModel();
 
                // 3. 查询/新增产品(按产品名称+图纸编号,更精准)
                Product product = getOrCreateProduct(productName, drawingNumber);
 
                // 4. 批量处理产品型号(按图纸编号+型号)
                processProductModel(dtoList, product.getId(), model, drawingNumber,errorList);
            }
            if(CollectionUtils.isNotEmpty(errorList)){
                // 5. 批量处理错误数据
                ExcelUtil<ProductModelExcelCopyErrorDto> errorExcelUtil = new ExcelUtil<>(ProductModelExcelCopyErrorDto.class);
                errorExcelUtil.exportExcel(response,errorList, "错误数据");
            }
        }
 
    }
 
    /**
     * 抽取通用方法:查询或新增产品
     */
    private Product getOrCreateProduct(String productName, String model) {
        // 精准查询:产品名称+型号(避免同名不同型号的问题)
        Product product = productMapper.selectOne(new LambdaQueryWrapper<Product>()
                .eq(Product::getProductName, productName)
//                .eq(Product::getModel, model)
                .last("limit 1"));
 
        if (product == null) {
            product = new Product();
            product.setProductName(productName);
//            product.setModel(model); // 补充型号,字段更完整
            product.setParentId(null);
            productMapper.insert(product);
        }
        return product;
    }
 
    /**
     * 抽取通用方法:处理产品型号(新增/更新)
     */
    private void processProductModel(List<ProductModelExcelCopyDto> dtoList,
                                     Long productId,
                                     String model,
                                     String drawingNumber,
                                     List<ProductModelExcelCopyErrorDto> errorList) {
        // 查询所有工艺路线
        List<ProductProcess> productRoutes = productProcessMapper.selectList(new QueryWrapper<ProductProcess>());
        if(CollectionUtils.isEmpty(productRoutes)){
            productRoutes = new ArrayList<>();
        }
        for (ProductModelExcelCopyDto dto : dtoList) {
            // 查询条件:型号+图纸编号(更精准,符合分组逻辑)
            ProductModel productModel = productModelMapper.selectOne(new LambdaQueryWrapper<ProductModel>()
                    .eq(ProductModel::getModel, model)
                    .last("limit 1"));
            // 通过工艺路线名称匹配最新一条工艺路线
            ProductProcess productRoute = productRoutes.stream()
                    .filter(route -> route.getName().equals(dto.getProcessRoute()))
                    .max(Comparator.comparing(ProductProcess::getCreateTime))
                    .orElse(null);
            if (productModel == null) {
                productModel = new ProductModel();
                BeanUtils.copyProperties(dto, productModel);
                if (productRoute != null) {
                    productModel.setRouteId(productRoute.getId());
                }
                // 兜底默认值,避免空值
                if (productModel.getProductType() == null) {
                    productModel.setProductType(1);
                }
                productModel.setProductId(productId);
                productModelMapper.insert(productModel);
            } else {
                productModel.setRouteId(productRoute != null ? productRoute.getId() : null);
                BeanUtils.copyProperties(dto, productModel);
                productModel.setProductId(productId);
                productModelMapper.updateById(productModel);
            }
        }
    }
 
    /**
     * 递归导入树形产品数据
     * @param excelDto Excel解析后的树形节点
     * @param parentId 父节点ID(顶级节点传null/0)
     */
    @Transactional(rollbackFor = Exception.class) // 事务保证,失败则回滚
    public void recursiveSaveProduct(ProductModelExcelDto excelDto, Long parentId) {
        // 1. 构建当前节点的Product实体
        Product product = new Product();
        product.setProductName(excelDto.getProductName());
        product.setParentId(parentId); // 父节点ID
 
        // 2. 插入当前节点,MyBatis会自动回填product的id属性
        productMapper.insert(product);
        Long currentId = product.getId(); // 获取当前节点主键
 
        // 3. 递归处理子节点
        if (excelDto.getChildren() != null && !excelDto.getChildren().isEmpty()) {
            for (ProductModelExcelDto childDto : excelDto.getChildren()) {
                recursiveSaveProduct(childDto, currentId); // 父ID为当前节点ID
            }
        }
 
        // 4. (可选)处理items数据(如果需要插入到关联表)
         if (excelDto.getItems() != null && !excelDto.getItems().isEmpty()) {
             for (ProductModelExcelItemDto item : excelDto.getItems()) {
                 // 插入item关联数据,关联currentId
                 // 构建ProductModel实体
                 ProductModel productModel = new ProductModel();
                 productModel.setProductId(currentId); // 关联当前产品节点ID
                 productModel.setModel(item.getModel()); // 从ItemDTO获取型号
                 productModel.setUnit(item.getUnit());   // 从ItemDTO获取单位
                 productModel.setDrawingNumber(item.getDrawingNumber()); // 图纸编号
                 productModel.setProductType(item.getProductType());
                 // 插入product_model表
                 productModelMapper.insert(productModel);
             }
         }
    }
}