shiyunteng
2026-08-25 dd4284136cb12dc3c2e498e0f0ff002d553763af
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
package com.by4cloud.platformx.business.service.impl;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by4cloud.platformx.business.dto.ProductAddDTO;
import com.by4cloud.platformx.business.dto.ProductQueryDTO;
import com.by4cloud.platformx.business.dto.SyncProductDTO;
import com.by4cloud.platformx.business.entity.BusinessCustomer;
import com.by4cloud.platformx.business.entity.Product;
import com.by4cloud.platformx.business.entity.TaxCode;
import com.by4cloud.platformx.business.mapper.ProductMapper;
import com.by4cloud.platformx.business.mapper.TaxCodeMapper;
import com.by4cloud.platformx.business.service.ProductService;
import com.by4cloud.platformx.business.vo.ProductExcelVO;
import com.by4cloud.platformx.business.vo.ProductSelectVo;
import com.by4cloud.platformx.common.core.util.R;
import com.by4cloud.platformx.common.data.datascope.DataScope;
import com.by4cloud.platformx.common.excel.vo.ErrorMessage;
import com.by4cloud.platformx.common.security.util.SecurityUtils;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
 
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
;
 
/**
 * 产品信息
 *
 * @author platformx
 * @date 2026-05-07 10:17:52
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
 
    private final TaxCodeMapper taxCodeMapper;
 
    @Value("${erp.smj}")
    private String smjErp;
 
    @Override
    public List<Tree<Long>> treeList() {
        List<TreeNode<Long>> collect = baseMapper
                .selectListByScope(Wrappers.<Product>lambdaQuery()
                        .orderByAsc(Product::getCreateTime), DataScope.of("comp_id"))
                .stream().map(getNodeFunction()).collect(Collectors.toList());
 
        // 模糊查询 不组装树结构 直接返回 表格方便编辑
//        if (StrUtil.isNotBlank(productName)) {
//            return collect.stream().map(node -> {
//                Tree<Long> tree = new Tree<>();
//                tree.putAll(node.getExtra());
//                BeanUtils.copyProperties(node, tree);
//                return tree;
//            }).collect(Collectors.toList());
//        }
        TreeNode<Long> parent = new TreeNode<>();
        parent.setId(0L);
        parent.setName("目录");
        parent.setParentId(-1L);
        collect.add(parent);
        return TreeUtil.build(collect, 0L);
    }
 
    @Override
    public List<ProductSelectVo> getProductList(Product product) {
        return baseMapper.getProductListByScope(product,DataScope.of("comp_id"));
    }
 
 
    @NotNull
    private Function<Product, TreeNode<Long>> getNodeFunction() {
        return product -> {
            TreeNode<Long> node = new TreeNode<>();
            node.setId(product.getId());
            node.setName(product.getProductName());
            node.setParentId(product.getParentId());
            //node.setWeight(product.getParentId());
            // 扩展属性
//            Map<String, Object> extra = new HashMap<>();
//            extra.put("picPath", category.getPicPath());
//            extra.put("Type", category.getType());
//            extra.put("isShow", category.getIsShow());
//            extra.put("iconPicPath", category.getIconPath());
//            extra.put("status", category.getStatus());
 
            // 适配 vue3
//            Map<String, Object> meta = new HashMap<>();
           /* meta.put("title", product.getProductName());
            meta.put("icon", product.getPrice());*/
 
            //extra.put("meta", meta);
            //node.setExtra(extra);
            return node;
        };
    }
 
    @Override
    public R getProductListByParentId(ProductQueryDTO queryDTO) {
        String[] erpCodes = new String[]{"house_rental","electricity_bill","water_bill"};
//        MPJLambdaWrapper<Product> wrapper = new MPJLambdaWrapper<Product>()
//                .selectAs("( SELECT count(1) FROM product t1 WHERE t1.parent_id = t.id )",Product::getChildNum)
//                .selectAll(Product.class)
//                .like(StrUtil.isNotEmpty(queryDTO.getProductName()),Product::getProductName,queryDTO.getProductName())
//                .eq(StrUtil.isNotEmpty(queryDTO.getParentId()),Product::getParentId,queryDTO.getParentId())
//                .in(StrUtil.isNotEmpty(queryDTO.getContractCategory())&&StrUtil.equals(queryDTO.getContractCategory(), "water_house"),
//                        Product::getErpCode,erpCodes);
        if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"","2089995177814495234")||
                StrUtil.equals(SecurityUtils.getUser().getCompId()+"","2089996921978040321")||
                StrUtil.equals(SecurityUtils.getUser().getCompId()+"","2089997578009128962")){
            List<ProductSelectVo> selectVos = baseMapper.getProductSMJListByParentId(queryDTO, Arrays.asList(erpCodes));
            if (selectVos.size()>2000){
                return R.ok(selectVos.subList(0,1999));
            }
            return R.ok(selectVos);
        }
        List<ProductSelectVo> selectVos = baseMapper.getProductListByParentId(queryDTO, Arrays.asList(erpCodes),DataScope.of("comp_id"));
        if (selectVos.size()>2000){
            return R.ok(selectVos.subList(0,1999));
        }
        return R.ok(selectVos);
    }
 
    @Override
    public R saveErpProduct(List<ProductAddDTO> addDTOS) {
        if (CollUtil.isNotEmpty(addDTOS)){
            for (ProductAddDTO addDTO:addDTOS
                 ) {
                List<Product> classPro = baseMapper.selectListByScope(Wrappers.<Product>lambdaQuery()
                                .eq(StrUtil.isNotEmpty(addDTO.getErpTypeCode()),Product::getErpCode,addDTO.getErpTypeCode())
                                .eq(StrUtil.isNotEmpty(addDTO.getErpTypeName()),Product::getProductName,addDTO.getErpTypeName())
                        , DataScope.of("comp_id"));
                if (CollUtil.isEmpty(classPro)){
                    Product product = new Product();
                    product.setProductName(addDTO.getErpTypeName());
                    product.setProductType(addDTO.getSpecification());
                    product.setParentId(0L);
                    product.setParentName("根级产品");
                    product.setErpCode(addDTO.getErpTypeCode());
                    TaxCode taxCode = taxCodeMapper.selectOne(Wrappers.<TaxCode>lambdaQuery().eq(TaxCode::getBm,addDTO.getTaxCode()).last("limit 1"));
                    if (ObjUtil.isNotNull(taxCode)){
                        product.setTaxClass(taxCode.getMc());
                        product.setTaxRate(Double.valueOf(taxCode.getSl().replace("%","")));
                    }
                    baseMapper.insert(product);
                    classPro.add(product);
                }
                Product product = new Product();
                product.setProductName(addDTO.getErpName());
                product.setProductType(addDTO.getSpecification());
                product.setParentId(classPro.get(0).getId());
                product.setParentName(classPro.get(0).getProductName());
                product.setErpCode(addDTO.getErpCode());
                TaxCode taxCode = taxCodeMapper.selectOne(Wrappers.<TaxCode>lambdaQuery().eq(TaxCode::getBm,addDTO.getTaxCode()).last("limit 1"));
                if (ObjUtil.isNotNull(taxCode)){
                    product.setTaxClass(taxCode.getMc());
                    product.setTaxRate(Double.valueOf(taxCode.getSl().replace("%","")));
                }
                baseMapper.insert(product);
            }
        }
        return R.ok();
    }
 
    @Override
    public R importProduct(List<ProductExcelVO> excelVOList, BindingResult bindingResult) {
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
        if (CollUtil.isNotEmpty(excelVOList)) {
            List<List<ProductExcelVO>> groups = splitList(excelVOList, 5000);
            groups.stream().forEach(group->{
                for (ProductExcelVO addDTO:group
                     ) {
                    Set<String> errorMsg = new HashSet<>();
 
                    if (StrUtil.isEmpty(addDTO.getErpTypeCode())&&StrUtil.isEmpty(addDTO.getErpTypeName())) {
                        errorMsg.add("产品分类信息没有");
                    }
                    List<Product> one = this.listByScope(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, addDTO.getErpCode()));
                    if (CollUtil.isNotEmpty(one)){
                        errorMsg.add("产品erp编码已存在");
                    }
                    if (CollUtil.isEmpty(errorMsg)){
                        List<Product> classPro = baseMapper.selectListByScope(Wrappers.<Product>lambdaQuery()
                                        .eq(StrUtil.isNotEmpty(addDTO.getErpTypeCode()),Product::getErpCode,addDTO.getErpTypeCode())
                                        .eq(StrUtil.isNotEmpty(addDTO.getErpTypeName()),Product::getProductName,addDTO.getErpTypeName())
                                , DataScope.of("comp_id"));
                        if (CollUtil.isEmpty(classPro)){
                            Product product = new Product();
                            product.setProductName(addDTO.getErpTypeName());
                            product.setProductType(addDTO.getSpecification());
                            product.setParentId(0L);
                            product.setParentName("根级产品");
                            product.setErpCode(addDTO.getErpTypeCode());
                            TaxCode taxCode = taxCodeMapper.selectOne(Wrappers.<TaxCode>lambdaQuery().eq(TaxCode::getBm,addDTO.getTaxCode()).last("limit 1"));
                            if (ObjUtil.isNotNull(taxCode)){
                                product.setTaxClass(taxCode.getMc());
                                product.setTaxRate(Double.valueOf(taxCode.getSl().replace("%","")));
                            }
                            baseMapper.insert(product);
                            classPro.add(product);
                        }
                        Product product = new Product();
                        product.setProductName(addDTO.getErpName());
                        product.setProductType(addDTO.getSpecification());
                        product.setParentId(classPro.get(0).getId());
                        product.setParentName(classPro.get(0).getProductName());
                        product.setErpCode(addDTO.getErpCode());
                        TaxCode taxCode = taxCodeMapper.selectOne(Wrappers.<TaxCode>lambdaQuery().eq(TaxCode::getBm,addDTO.getTaxCode()).last("limit 1"));
                        if (ObjUtil.isNotNull(taxCode)){
                            product.setTaxClass(taxCode.getMc());
                            product.setTaxRate(Double.valueOf(taxCode.getSl().replace("%","")));
                        }
                        baseMapper.insert(product);
                    }
                }
            });
        }
        if (CollUtil.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        }
        return R.ok();
    }
 
    public static <T> List<List<T>> splitList(List<T> list, int batchSize) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
 
        int totalSize = list.size();
        // 计算需要分成多少组
        int batchCount = (totalSize + batchSize - 1) / batchSize;
 
        return IntStream.range(0, batchCount)
                .mapToObj(i -> list.subList(i * batchSize,
                        Math.min((i + 1) * batchSize, totalSize)))
                .collect(Collectors.toList());
    }
 
    @Override
    public R syncSMJByDate(SyncProductDTO dto) {
        String startDate = "";
        if (StrUtil.isBlank(dto.getStartDate())){
            startDate = DateUtil.formatDate(DateUtil.offsetDay(new Date(), -1));
        }else {
            startDate = dto.getStartDate();
        }
        JSONObject loginJson = new JSONObject();
        loginJson.put("username", "admin");
        loginJson.put("password", "Zimafold@2026");
        log.info("石煤机产品获取token入参:{}", loginJson.toJSONString());
        String loginResp = HttpUtil.post(smjErp + "/api/account/v1/login", loginJson.toJSONString());
        log.info("石煤机产品获取token回参:{}", loginResp);
        JSONObject respJson = JSONObject.parseObject(loginResp);
        if (respJson.getInteger("code") == 0) {
            JSONObject dataJson = JSONObject.parseObject(respJson.getString("data"));
            HttpResponse response = HttpRequest.get(smjErp + "/api/item/v1/byDateCre?startDate=" + startDate)
                    .header("token", dataJson.getString("token"))       // 添加认证头
                    .execute();                                         // 执行请求.post(ymjErp,request.toJSONString());
            log.info("石煤机产品获取回参:{}", response.body());
            JSONObject proResult = JSONObject.parseObject(response.body());
            JSONArray items = proResult.getJSONArray("data");
            if (CollUtil.isNotEmpty(items)){
                log.info("石煤机产品获取数量:{}", items.size());
                items.stream().forEach(item->{
                    JSONObject product = (JSONObject) item;
                    Product productClass = baseMapper.selectOne(Wrappers.<Product>lambdaQuery()
                            .eq(Product::getProductName,product.getString("itemClassName"))
                            .and(wrapper -> wrapper.eq(Product::getCompId,"2089995177814495234")
                                    .or().eq(Product::getCompId,"2089996921978040321")
                                    .or().eq(Product::getCompId,"2089997578009128962")
                                    )
                            .last("limit 1")
                    );
                    if(ObjUtil.isNull(productClass)){
                        log.info("产品分类:{}不存在",product.getString("itemClassName"));
                        productClass = new Product();
                        productClass.setProductName(product.getString("itemClassName"));
                        productClass.setErpCode(product.getString("itemClassName"));
                        productClass.setParentId(0L);
                        productClass.setCompId(2089995177814495234L);
                        baseMapper.insert(productClass);
                        log.info("产品分类:{}新增成功",product.getString("itemClassName"));
                    }
                    Product productNew = baseMapper.selectOne(Wrappers.<Product>lambdaQuery()
                            .eq(Product::getErpCode,product.getString("itemNo"))
                            .and(wrapper -> wrapper.eq(Product::getCompId,"2089995177814495234")
                                    .or().eq(Product::getCompId,"2089996921978040321")
                                    .or().eq(Product::getCompId,"2089997578009128962")
                            )
                            .last("limit 1")
                    );
                    if(ObjUtil.isNull(productNew)){
                        log.info("产品:{}不存在",product.getString("itemNo"));
                        productNew = new Product();
                        productNew.setProductName(product.getString("note"));
                        productNew.setErpCode(product.getString("itemNo"));
                        productNew.setProductType(product.getString("grade"));
                        productNew.setCompId(2089995177814495234L);
                        productNew.setParentId(productClass.getId());
                        baseMapper.insert(productNew);
                        log.info("产品:{}新增成功",product.getString("itemNo"));
                        return;
                    }
                    log.info("产品:{}存在",product.getString("itemNo"));
                });
            }
        }
        return R.ok();
    }
}