EquipmentSparepartController.java 38.6 KB
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 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
package com.skua.modules.equipment.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.skua.core.util.ConvertUtils;
import com.skua.tool.dfs.MapDFS;
import org.apache.commons.lang.StringUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
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.skua.aop.annotation.CustomExceptionAnno;
import com.skua.core.api.vo.Result;
import com.skua.core.aspect.annotation.AutoLog;
import com.skua.core.context.SpringContextUtils;
import com.skua.core.query.QueryGenerator;
import com.skua.core.util.zxing.QRCodeUtil;
import com.skua.modules.common.service.ICommonSqlService;
import com.skua.modules.equipment.dto.EquipmentSparepartDTO;
import com.skua.modules.equipment.entity.EquipmentIn;
import com.skua.modules.equipment.entity.EquipmentInChild;
import com.skua.modules.equipment.entity.EquipmentOut;
import com.skua.modules.equipment.entity.EquipmentOutChild;
import com.skua.modules.equipment.entity.EquipmentSparepart;
import com.skua.modules.equipment.service.IEquipmentInChildService;
import com.skua.modules.equipment.service.IEquipmentInService;
import com.skua.modules.equipment.service.IEquipmentOutChildService;
import com.skua.modules.equipment.service.IEquipmentOutService;
import com.skua.modules.equipment.service.IEquipmentSparepartService;
import com.skua.modules.equipment.util.EquipmentUtils;
import com.skua.modules.equipment.vo.EquipmentSparepartVO;
import com.skua.modules.supplies.entity.EquipmentSparepartSupplies;
import com.skua.modules.supplies.entity.EquipmentSparepartType;
import com.skua.modules.supplies.entity.SuppliesWarehouse;
import com.skua.modules.supplies.service.IEquipmentSparepartTypeService;
import com.skua.redis.component.Key2ValueService;
import com.skua.redis.util.CustomRedisUtil;
import com.skua.tool.mpp.BaseFactory;
import com.skua.tool.query.WrapperFactory;
import com.skua.tool.util.BeanExtUtils;
import com.skua.tool.util.UniqIdUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 备品备件表
 */
@Slf4j
@Api(tags = "设备管理/库存管理/库存查询")
@RestController
@RequestMapping("/web/equipment/equipmentSparepart")
public class EquipmentSparepartController {

    @Value("${skua.path.upload}")
    private String upLoadPath;
    @Autowired
    private IEquipmentSparepartService equipmentSparepartService;
    @Autowired
    private ICommonSqlService iCommonSqlService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private CustomRedisUtil customRedisUtil;
    @Autowired
    private Key2ValueService key2ValueService;
    @Autowired
    private IEquipmentInService equipmentInService;
    @Autowired
    private IEquipmentInChildService equipmentInChildService;
    @Autowired
    private IEquipmentOutService equipmentOutService;
    @Autowired
    private IEquipmentOutChildService equipmentOutChildService;
    @Autowired
    private IEquipmentSparepartTypeService equipmentSparepartTypeService;

    @CustomExceptionAnno(description = "备品备件表-上下限阈值")
    @AutoLog(value = "备品备件表-上下限阈值")
    @ApiOperation(value = "备品备件表-上下限阈值", notes = "备品备件表-上下限阈值")
    @GetMapping(value = "/max-min-limit")
    public Result<Map<String, Object>> maxMinLimitCtrl(@RequestParam("departId") String departId) {
        Result<Map<String, Object>> result = new Result<>();
        String[] itemValues = this.getMaxMinLimitFunc();
        Map<String, Object> map = new HashMap<>();
        map.put("storageMinNum", itemValues[0]);
        map.put("storageMaxNum", itemValues[1]);
        result.setResult(map);
        return result;
    }

    private String[] getMaxMinLimitFunc() {
        String sql = "select sdi.item_text as itemText, sdi.item_value as itemValue from sys_dict_item as sdi inner join sys_dict as sd on sdi.dict_id = sd.id and sd.dict_code = 'equipment-equipment_sparepart'";
        List<Map<String, Object>> mapList = iCommonSqlService.queryForList(sql);
        String itemValue = String.valueOf(mapList.get(0).get("itemValue"));
        return itemValue.split("\\|");
    }

    @CustomExceptionAnno(description = "备品备件表-所属机构统计")
    @AutoLog(value = "备品备件表-所属机构统计")
    @ApiOperation(value = "备品备件表-所属机构统计", notes = "备品备件表-所属机构统计")
    @GetMapping(value = "/statisticByFactoryId")
    public Result<List<Map<String, Object>>> statisticByFactoryIdCtrl(@RequestParam("id") String id) {
        Result<List<Map<String, Object>>> result = new Result<>();
        String sql = "select count(*) as total, storage_max_num as storageMaxNum, storage_min_num as storageMinNum, depart_id as departId from equipment_sparepart where id = '" + id + "' group by depart_id";
        List<Map<String, Object>> mapList = iCommonSqlService.queryForList(sql);
        result.setResult(mapList);
        return result;
    }

    @CustomExceptionAnno(description = "备品备件表-更新上下限")
    @AutoLog(value = "备品备件表-更新上下限")
    @ApiOperation(value = "备品备件表-更新上下限", notes = "备品备件表-更新上下限")
    @PutMapping(value = "/updateLimit")
    public Result<?> updateLimitCtrl(@RequestBody EquipmentSparepart equipmentSparepart) {
        Result<?> result = new Result<>();
        BigDecimal storageMaxNum = equipmentSparepart.getStorageMaxNum();
        BigDecimal storageMinNum = equipmentSparepart.getStorageMinNum();
        String sql = "update equipment_sparepart set storage_max_num = " + storageMaxNum + " ,storage_min_num=" + storageMinNum;
        String sql2 = "update sys_dict_item set item_value = '" + storageMinNum + "|" + storageMaxNum + "' where dict_id = '6a2531a238ad07d85c274a37c807de39'";
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                int val1 = iCommonSqlService.update(sql);
                int val2 = iCommonSqlService.update(sql2);
                if (val1 == 0 || val2 == 0) {
                    transactionStatus.setRollbackOnly();
                }
            }
        });
        return result;
    }

    @CustomExceptionAnno(description = "备品备件表-出入库详情")
    @AutoLog(value = "备品备件表-出入库详情")
    @ApiOperation(value = "备品备件表-出入库详情", notes = "备品备件表-出入库详情")
    @GetMapping(value = "/detail")
    public Result<Object> detailCtrl(EquipmentSparepartDTO equipmentSparepartDTO,
                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {
        Result<Object> result = new Result<>();
        String sparepartId = equipmentSparepartDTO.getId();
        String inSql = WrapperFactory.joinWrapper()
                .select("sparepart_id", "sparepart_code as sparepartCode", "depart_id as departId", "'入库' as direction", "storage_num as storageNum", "in_num as inOutNum", "use_by as useBy", "in_order as inOutOrder")
                .from(EquipmentInChild.class)
                .innerJoin(EquipmentIn.class, EquipmentIn.class.getDeclaredField("id"), EquipmentInChild.class.getDeclaredField("inId"))
                .innerJoin(EquipmentSparepart.class, EquipmentSparepart.class.getDeclaredField("id"), EquipmentInChild.class.getDeclaredField("sparepartId"))
                .initPrefixSql();
        String outSql = WrapperFactory.joinWrapper()
                .select("sparepart_id", "sparepart_code as sparepartCode", "depart_id as departId", "'出库' as direction", "storage_num as storageNum", "out_num as inOutNum", "use_by as useBy", "out_order as inOutOrder")
                .from(EquipmentOutChild.class)
                .innerJoin(EquipmentOut.class, EquipmentOut.class.getDeclaredField("id"), EquipmentOutChild.class.getDeclaredField("outId"))
                .innerJoin(EquipmentSparepart.class, EquipmentSparepart.class.getDeclaredField("id"), EquipmentOutChild.class.getDeclaredField("sparepartId"))
                .initPrefixSql();
        String sql = "select * from (" + inSql + " union all " + outSql + ") as res";
        QueryWrapper<?> queryWrapper = new QueryWrapper<>()
                .eq("sparepart_id", sparepartId);
        Page<Map<String, Object>> mapPage = iCommonSqlService.queryWrapperForPage(new Page<>(pageNo, pageSize), sql, queryWrapper);
        Map<String, String> sysUserVal2KeyMap = EquipmentUtils.convertFunc("sysUser", false);
        List<Map<String, Object>> convertMapList = WrapperFactory.result()
                .addCallback("useBy", "useByName")
                .addCallback("departId", "departIdName")
                .maps2MapsWithPrefix(mapPage.getRecords(), (targetFieldName, srcFieldVal) -> {
                    if ("departIdName".equals(targetFieldName)) {
                        return customRedisUtil.hget("sys_depart", "" + srcFieldVal, "id", "depart_name");
                    } else if ("useByName".equals(targetFieldName)) {
                        return sysUserVal2KeyMap.get("" + srcFieldVal);
                    }
                    return srcFieldVal;
                });
        mapPage.setRecords(convertMapList);
        result.setResult(mapPage);
        return result;
    }

    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "备品备件表-分页列表查询")
    @ApiOperation(value = "备品备件表-分页列表查询", notes = "备品备件表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<EquipmentSparepartVO>> queryPageList(EquipmentSparepartDTO equipmentSparepartDTO,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {
        Result<IPage<EquipmentSparepartVO>> result = new Result<>();
        Page page = new Page(pageNo, pageSize);
        Set<String> sparepartTypeSet = new HashSet<>();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(equipmentSparepartDTO.getSparepartType())) {
            String typeId = equipmentSparepartDTO.getSparepartType();
            // 查询子集
            MapDFS mapDFS = new MapDFS();
            List<Map<String, Object>> tree = mapDFS.buildTree(equipmentSparepartTypeService.listMaps(new QueryWrapper<EquipmentSparepartType>().select("id, parent_id as parentId")));
            LinkedList<LinkedList<Map<String, Object>>> routeList = mapDFS.getRouteList(tree);
            for (LinkedList<Map<String, Object>> route: routeList) {
                for (int i = 0; i < route.size(); i++) {
                    if (typeId.equals(route.get(i).get("id"))) {
                        for (int j = i; j < route.size(); j++) {
                            sparepartTypeSet.add(ConvertUtils.getString(route.get(j).get("id")));
                        }
                    }
                }
            }
        }
        IPage<Map<String, Object>> mapPage = BaseFactory.JOIN()
                .select(EquipmentSparepartSupplies.class)
                .select(SuppliesWarehouse.class)
                .select("equipment_sparepart.depart_id,equipment_sparepart.id,equipment_sparepart.storage_num storageNum,equipment_sparepart.supplies_warehouse_id suppliesWarehouseId,equipment_sparepart_supplies.id suppliesId")
                .from(EquipmentSparepart.class)
                .innerJoin(SuppliesWarehouse.class, SuppliesWarehouse.class.getDeclaredField("id"), EquipmentSparepart.class.getDeclaredField("suppliesWarehouseId"))
                .innerJoin(EquipmentSparepartSupplies.class, EquipmentSparepartSupplies.class.getDeclaredField("id"), EquipmentSparepart.class.getDeclaredField("suppliesId"))
                .where()
                .ge(equipmentSparepartDTO.getNum()>0, "equipment_sparepart.storage_num", equipmentSparepartDTO.getNum())
                .like(StringUtils.isNotEmpty(equipmentSparepartDTO.getSparepartCode()), "equipment_sparepart_supplies.sparepart_code", equipmentSparepartDTO.getSparepartCode())
                .like(StringUtils.isNotEmpty(equipmentSparepartDTO.getSpecification()), "equipment_sparepart_supplies.specification", equipmentSparepartDTO.getSpecification())
                .like(StringUtils.isNotEmpty(equipmentSparepartDTO.getSparepartName()), "equipment_sparepart_supplies.sparepart_name", equipmentSparepartDTO.getSparepartName())
                .like(StringUtils.isNotEmpty(equipmentSparepartDTO.getIsEmergency()), "equipment_sparepart.is_emergency", equipmentSparepartDTO.getIsEmergency())
                .like(StringUtils.isNotEmpty(equipmentSparepartDTO.getIsDangerous()), "equipment_sparepart.is_dangerous", equipmentSparepartDTO.getIsDangerous())
                .in(!sparepartTypeSet.isEmpty(), "equipment_sparepart_supplies.sparepart_type", sparepartTypeSet)
                .like(StringUtils.isNotEmpty(equipmentSparepartDTO.getWarehouseName()), "warehouse_name", equipmentSparepartDTO.getWarehouseName())
                .like(StringUtils.isNotEmpty(equipmentSparepartDTO.getSuppliesWarehouseId()), "supplies_warehouse_id", equipmentSparepartDTO.getSuppliesWarehouseId())
                .between(StringUtils.isNotEmpty(equipmentSparepartDTO.getStartTime()) && StringUtils.isNotEmpty(equipmentSparepartDTO.getEndTime()), "inventory_update_time", equipmentSparepartDTO.getStartTime(), equipmentSparepartDTO.getEndTime())
                .apply("库存不足".equals(equipmentSparepartDTO.getStorageWarn()), "equipment_sparepart_supplies.storage_num < equipment_sparepart_supplies.storage_min_num")
                .apply("库存过量".equals(equipmentSparepartDTO.getStorageWarn()), "equipment_sparepart.equipment_sparepart_supplies > equipment_sparepart_supplies.storage_max_num")
                .orderBy(true, false, "equipment_sparepart.inventory_update_time").queryForPage(page);
        Map<String, String> equipmentSparepartTypeVal2KeyMap = key2ValueService.dictKey2Val("equipmentSparepartType", false);
        Map<String, String> suppliesWarehouseVal2KeyMap = key2ValueService.dictKey2Val("suppliesWarehouse", false);
        Map<String, String> departInfoVal2KeyMap = key2ValueService.dictKey2Val("sysDepart", false);
        Map<String, String> unitInfoVal2KeyMap = key2ValueService.dictKey2Val("equipment-sparepart_measuring_unit", false);

        JdbcTemplate masterDB = (JdbcTemplate) SpringContextUtils.getBean("master");
        //品牌厂商
        List<Map<String, Object>> purchaseSupplierMapList = masterDB.queryForList("select * from equipment_brand");

        Map<String, String> manufacturerMap = purchaseSupplierMapList.stream().collect(Collectors.toMap(item -> "" + item.get("id"), item -> "" + item.get("brand_company")));
        List<Map<String, Object>> convertMapList = WrapperFactory.result()
                .addCallback("EquipmentSparepartSupplies_sparepartType", "sparepartType_dictText")
                .addCallback("EquipmentSparepartSupplies_manufacturer", "manufacturer_dictText")
                .addCallback("suppliesWarehouseId", "suppliesWarehouseId_dictText")
                .addCallback("SuppliesWarehouse_departId", "departIdName")
                .addCallback("EquipmentSparepartSupplies_measuringUnit", "measuringUnit_dictText")
                .maps2MapsWithoutPrefix(mapPage.getRecords(), (targetFieldName, srcFieldVal) -> {
                    if ("departIdName".equals(targetFieldName) && srcFieldVal != null) {
                    	return departInfoVal2KeyMap.getOrDefault("" + srcFieldVal, "");
                    } else if ("sparepartType_dictText".equals(targetFieldName)) {
                        return equipmentSparepartTypeVal2KeyMap.getOrDefault("" + srcFieldVal, "");
                    } else if ("manufacturer_dictText".equals(targetFieldName)) {
                        return manufacturerMap.getOrDefault(srcFieldVal, "");
                    }else if ("suppliesWarehouseId_dictText".equals(targetFieldName)) {
                        return suppliesWarehouseVal2KeyMap.getOrDefault(srcFieldVal, "");
                    }else if ("measuringUnit_dictText".equals(targetFieldName)) {
                        return unitInfoVal2KeyMap.getOrDefault(srcFieldVal, "");
                    }
                    return srcFieldVal;
                });
        page.setTotal(mapPage.getTotal());
        page.setRecords(convertMapList);
        result.setSuccess(true);
        result.setResult(page);
        return result;
    }

    /**
     * 添加
     *
     * @param equipmentSparepart
     * @return
     */
    @AutoLog(value = "备品备件表-添加")
    @ApiOperation(value = "备品备件表-添加", notes = "备品备件表-添加")
    @PostMapping(value = "/add")
    public Result<EquipmentSparepart> add(@RequestBody EquipmentSparepart equipmentSparepart) {
        Result<EquipmentSparepart> result = new Result<>();
        try {
            if (equipmentSparepart.getInventoryUpdateTime() == null) {
                equipmentSparepart.setInventoryUpdateTime(new Date());
            }
            int count = equipmentSparepartService.count(new QueryWrapper<EquipmentSparepart>()
                    .eq("sparepart_name", equipmentSparepart.getSparepartName())
                    .eq("sparepart_alias", equipmentSparepart.getSparepartAlias())
                    .eq("sparepart_aliass", equipmentSparepart.getSparepartAliass())
                    .eq("specification", equipmentSparepart.getSpecification())
                    .eq("manufacturer", equipmentSparepart.getManufacturer()));
            if (count > 0) {
                result.error500("已存在此物资!");
                return result;
            }
            String id = UniqIdUtils.getInstance().getUniqID();
            String qrCode = this.createQrCode(id);
            equipmentSparepart.setId(id);
            equipmentSparepart.setQrCode(qrCode);
            if (StringUtils.isEmpty(equipmentSparepart.getSparepartAlias())) {
                equipmentSparepart.setSparepartAlias(equipmentSparepart.getSparepartName());
            }
            if (StringUtils.isEmpty(equipmentSparepart.getSparepartAliass())) {
                equipmentSparepart.setSparepartAliass(equipmentSparepart.getSparepartName());
            }
            equipmentSparepart.setSpecification(equipmentSparepart.getSparepartAlias() + "(" + equipmentSparepart.getSparepartAliass() + ")");
            // 设置sparepartCode
            // 备件类型
            List<EquipmentSparepartType> equipmentSparepartTypeList = equipmentSparepartTypeService.list();
            Map<String, String> value2ParentIdMap = new HashMap<>();
            Map<String, String> id2valueMap = new HashMap<>();
            for (EquipmentSparepartType equipmentSparepartType : equipmentSparepartTypeList) {
                value2ParentIdMap.put(equipmentSparepartType.getItemValue(), equipmentSparepartType.getParentId());
                id2valueMap.put(equipmentSparepartType.getId(), equipmentSparepartType.getItemValue());
            }
            List<EquipmentSparepart> equipmentSparepartList = equipmentSparepartService.list();
            // 每一层的数量总数
            Map<String, Integer> twoCountMap = new LinkedHashMap<>();
            Map<String, Integer> threeCountMap = new LinkedHashMap<>();
            Map<String, Integer> fourCountMap = new LinkedHashMap<>();
            // 统计数量
            for (EquipmentSparepart item : equipmentSparepartList) {
                String sparepartType = item.getSparepartType();
                String code1 = id2valueMap.getOrDefault(value2ParentIdMap.getOrDefault(sparepartType, ""), "");
                String code2 = sparepartType;
                String code3 = item.getSparepartName();
                String code4 = item.getSparepartAlias();
                // key值
                String twoKey = code1 + "=>" + code2;
                String threeKey = code1 + "=>" + code2 + "=>" + code3;
                String fourKey = code1 + "=>" + code2 + "=>" + code3 + "=>" + code4;
                twoCountMap.put(twoKey, 1 + twoCountMap.getOrDefault(twoKey, 0));
                threeCountMap.put(threeKey, 1 + threeCountMap.getOrDefault(threeKey, 0));
                fourCountMap.put(fourKey, 1 + fourCountMap.getOrDefault(fourKey, 0));
            }
            String code1 = id2valueMap.getOrDefault(value2ParentIdMap.getOrDefault(equipmentSparepart.getSparepartType(), ""), "");
            String code2 = equipmentSparepart.getSparepartType();
            String code3 = equipmentSparepart.getSparepartName();
            String code4 = equipmentSparepart.getSparepartAlias();
            // key值
            String twoKey = code1 + "=>" + code2;
            String threeKey = code1 + "=>" + code2 + "=>" + code3;
            String fourKey = code1 + "=>" + code2 + "=>" + code3 + "=>" + code4;
            int twoCount = twoCountMap.getOrDefault(twoKey, 0) + 1;
            int threeCount = threeCountMap.getOrDefault(threeKey, 0) + 1;
            int fourCount = fourCountMap.getOrDefault(fourKey, 0) + 1;
            equipmentSparepart.setSparepartCode(code1 + code2 + twoCount + "-" + threeCount + "-" + fourCount);
            if (equipmentSparepart.getStorageMinNum() == null || equipmentSparepart.getStorageMaxNum() == null) {
                String[] itemValues = getMaxMinLimitFunc();
                equipmentSparepart.setStorageMinNum(new BigDecimal(itemValues[0]));
                equipmentSparepart.setStorageMaxNum(new BigDecimal(itemValues[1]));
            }
            result.success("添加成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    @AutoLog(value = "备品备件表-添加")
    @ApiOperation(value = "备品备件表-添加", notes = "备品备件表-添加")
    @GetMapping(value = "/modify")
    public Result<Object> modifyCtrl(@RequestParam(defaultValue = "0") String paramFlag) {
        Result<Object> result = new Result<>();
        if ("0".equals(paramFlag)) {
            int sparepartNameIndex = 0;
            int sparepartAliasIndex = 0;
            int sparepartAliassIndex = 0;
            List<EquipmentSparepart> equipmentSparepartList = equipmentSparepartService.list();
            for (EquipmentSparepart equipmentSparepart : equipmentSparepartList) {
                if (StringUtils.isEmpty(equipmentSparepart.getSparepartName())) {
                    equipmentSparepart.setSparepartName("sparepartName" + (++sparepartNameIndex));
                }
                if (StringUtils.isEmpty(equipmentSparepart.getSparepartAlias())) {
                    equipmentSparepart.setSparepartAlias("sparepartAlias" + (++sparepartAliasIndex));
                }
                if (StringUtils.isEmpty(equipmentSparepart.getSparepartAliass())) {
                    equipmentSparepart.setSparepartAliass("sparepartAliass" + (++sparepartAliassIndex));
                }
            }
            equipmentSparepartService.updateBatchById(equipmentSparepartList);
        } else if ("1".equals(paramFlag)) {
            List<EquipmentSparepartType> equipmentSparepartTypeList = equipmentSparepartTypeService.list();
            Map<String, String> value2IdMap = new HashMap<>();
            Map<String, String> id2valueMap = new HashMap<>();
            for (EquipmentSparepartType equipmentSparepartType : equipmentSparepartTypeList) {
                value2IdMap.put(equipmentSparepartType.getItemValue(), equipmentSparepartType.getParentId());
                id2valueMap.put(equipmentSparepartType.getId(), equipmentSparepartType.getItemValue());
            }
            Map<String, Integer> type2Name2ValMap = new HashMap<>();
            Map<String, Integer> type2Alias2ValMap = new HashMap<>();
            Map<String, Integer> type2Aliass2ValMap = new HashMap<>();
            List<EquipmentSparepart> equipmentSparepartList = equipmentSparepartService.list();
            for (EquipmentSparepart equipmentSparepart : equipmentSparepartList) {
                if (StringUtils.isEmpty(equipmentSparepart.getSparepartType())) {
                    continue;
                }
                String sparepartType = equipmentSparepart.getSparepartType();
                String code1 = id2valueMap.getOrDefault(value2IdMap.getOrDefault(sparepartType, ""), "");
                if (StringUtils.isEmpty(code1)) {
                    continue;
                }
                String code2 = sparepartType;
                QueryWrapper<EquipmentSparepart> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("sparepart_type", sparepartType).groupBy("sparepart_name");
                List<EquipmentSparepart> countList = equipmentSparepartService.list(queryWrapper);
                type2Name2ValMap.putIfAbsent(sparepartType, countList.size() + 1);
                type2Name2ValMap.put(sparepartType, type2Name2ValMap.get(sparepartType) - 1);
                int code3 = Math.abs(type2Name2ValMap.get(sparepartType));
                queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("sparepart_type", sparepartType).groupBy("sparepart_alias");
                countList = equipmentSparepartService.list(queryWrapper);
                type2Alias2ValMap.putIfAbsent(sparepartType, countList.size() + 1);
                type2Alias2ValMap.put(sparepartType, type2Alias2ValMap.get(sparepartType) - 1);
                int code4 = Math.abs(type2Alias2ValMap.get(sparepartType));
                queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("sparepart_type", sparepartType).groupBy("sparepart_aliass");
                countList = equipmentSparepartService.list(queryWrapper);
                type2Aliass2ValMap.putIfAbsent(sparepartType, countList.size() + 1);
                type2Aliass2ValMap.put(sparepartType, type2Aliass2ValMap.get(sparepartType) - 1);
                int code5 = Math.abs(type2Aliass2ValMap.get(sparepartType));
                String sparepartCode = code1 + code2 + code3 + "-" + code4 + "-" + code5;
                equipmentSparepart.setSparepartCode(sparepartCode);
                equipmentSparepartService.updateById(equipmentSparepart);
            }
        } else if ("2".equals(paramFlag)) {
            // 备件类型
            List<EquipmentSparepartType> equipmentSparepartTypeList = equipmentSparepartTypeService.list();
            Map<String, String> value2ParentIdMap = new HashMap<>();
            Map<String, String> id2valueMap = new HashMap<>();
            for (EquipmentSparepartType equipmentSparepartType : equipmentSparepartTypeList) {
                value2ParentIdMap.put(equipmentSparepartType.getItemValue(), equipmentSparepartType.getParentId());
                id2valueMap.put(equipmentSparepartType.getId(), equipmentSparepartType.getItemValue());
            }
            List<EquipmentSparepart> equipmentSparepartList = equipmentSparepartService.list();
            // 每一个索引
            Map<String, Integer> twoIndexMap = new HashMap<>();
            Map<String, Integer> threeIndexMap = new HashMap<>();
            Map<String, Integer> fourIndexMap = new HashMap<>();
            for (EquipmentSparepart equipmentSparepart : equipmentSparepartList) {
                String sparepartType = equipmentSparepart.getSparepartType();
                String code1 = id2valueMap.getOrDefault(value2ParentIdMap.getOrDefault(sparepartType, ""), "");
                String code2 = sparepartType;
                String code3 = equipmentSparepart.getSparepartName();
                String code4 = equipmentSparepart.getSparepartAlias();
                // key值
                String twoKey = code1 + "=>" + code2;
                String threeKey = code1 + "=>" + code2 + "=>" + code3;
                String fourKey = code1 + "=>" + code2 + "=>" + code3 + "=>" + code4;
                int twoIndex = twoIndexMap.getOrDefault(twoKey, 0) + 1;
                twoIndexMap.put(twoKey, twoIndex);
                int threeIndex = threeIndexMap.getOrDefault(threeKey, 0) + 1;
                threeIndexMap.put(threeKey, threeIndex);
                int fourIndex = fourIndexMap.getOrDefault(fourKey, 0) + 1;
                fourIndexMap.put(fourKey, fourIndex);
                String sparepartCode = code1 + code2 + twoIndex + "-" + threeIndex + "-" + fourIndex;
                equipmentSparepart.setSparepartCode(sparepartCode);
            }
            equipmentSparepartService.updateBatchById(equipmentSparepartList);
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param equipmentSparepart
     * @return
     */
    @AutoLog(value = "备品备件表-编辑")
    @ApiOperation(value = "备品备件表-编辑", notes = "备品备件表-编辑")
    @PutMapping(value = "/edit")
    public Result<EquipmentSparepart> edit(@RequestBody EquipmentSparepart equipmentSparepart) throws Exception {
        Result<EquipmentSparepart> result = new Result<>();
        EquipmentSparepart equipmentSparepartEntity = equipmentSparepartService.getById(equipmentSparepart.getId());
        if (equipmentSparepartEntity == null) {
            result.error500("未找到对应实体");
        } else {
            if (!equipmentSparepart.getSparepartCode().equals(equipmentSparepartEntity.getSparepartCode())) {
                int count = equipmentSparepartService.count();
                equipmentSparepart.setSparepartCode(equipmentSparepart.getSparepartCode() + "-" + (count + 1));
            }
            equipmentSparepart.setSpecification(equipmentSparepart.getSparepartAlias() + "(" + equipmentSparepart.getSparepartAliass() + ")");
            if (equipmentSparepart.getInventoryUpdateTime() == null) {
                equipmentSparepart.setInventoryUpdateTime(new Date());
            }
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "备品备件表-通过id删除")
    @ApiOperation(value = "备品备件表-通过id删除", notes = "备品备件表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            // 备品备件
            String equipmentSparepartSql = "delete from equipment_sparepart where id = '" + id + "'";
            // 一级备品备件
            String equipmentSparepartDemoSql = "delete from equipment_sparepart_demo where id = '" + id + "'";
            // 入库与备品备件关联表
            String equipmentInChildSql = "delete from equipment_in_child where sparepart_id = '" + id + "'";
            // 出库与备品备件关联表
            String equipmentOutChildSql = "delete from equipment_out_child where sparepart_id = '" + id + "'";
            // 盘点与备品备件关联表
            String equipmentCheckChildSql = "delete from equipment_check_child where sparepart_id = '" + id + "'";
            // 设备与备品备件关联表
            String equipmentRelationSql = "delete from equipment_relation where sparepart_id = '" + id + "'";
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                    iCommonSqlService.delete(equipmentSparepartSql);
                    iCommonSqlService.delete(equipmentSparepartDemoSql);
                    iCommonSqlService.delete(equipmentInChildSql);
                    iCommonSqlService.delete(equipmentOutChildSql);
                    iCommonSqlService.delete(equipmentCheckChildSql);
                    iCommonSqlService.delete(equipmentRelationSql);
                }
            });
        } catch (Exception e) {
            log.error("删除失败: {}", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 导出excel
     *
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<EquipmentSparepart> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (StringUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                EquipmentSparepart equipmentSparepart = JSON.parseObject(deString, EquipmentSparepart.class);
                queryWrapper = QueryGenerator.initQueryWrapper(equipmentSparepart, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<EquipmentSparepart> pageList = equipmentSparepartService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "备品备件表列表");
        mv.addObject(NormalExcelConstants.CLASS, EquipmentSparepart.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("备品备件表列表数据", "1"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<EquipmentSparepart> listEquipmentSpareparts = ExcelImportUtil.importExcel(file.getInputStream(), EquipmentSparepart.class, params);
                equipmentSparepartService.saveBatch(listEquipmentSpareparts);
                return Result.ok("文件导入成功!数据行数:" + listEquipmentSpareparts.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败!");
    }

    private String createQrCode(String id) {
        // 生成二维码
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        map.put("type", "equip");
        String jsonString = QRCodeUtil.mapToJsonStr(map);
        String qrCodePath = "files" + File.separator + "qrcode" + File.separator + id + ".png";
        try {
            QRCodeUtil.encode(jsonString, "", upLoadPath + File.separator + qrCodePath, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCodePath;
    }

    @DeleteMapping(value = "/deleteInCheckout")
    public Result<Object> deleteInCheckoutCtrl(@RequestParam String sparepartId) {
        Result<Object> result = new Result<>();
        transactionTemplate.execute(transactionStatus -> {
            // 删除备品备件
            equipmentSparepartService.removeById(sparepartId);

            // 删除入库记录
            QueryWrapper<EquipmentInChild> equipmentInChildQueryWrapper = new QueryWrapper<EquipmentInChild>().eq("sparepart_id", sparepartId);
            List<EquipmentInChild> equipmentInChildList = equipmentInChildService.list(equipmentInChildQueryWrapper);
            List<String> inIdList = equipmentInChildList.stream().map(EquipmentInChild::getInId).collect(Collectors.toList());
            if (!inIdList.isEmpty()) {
                equipmentInService.removeByIds(inIdList);
                equipmentInChildService.remove(equipmentInChildQueryWrapper);
            }

            // 删除出库记录
            QueryWrapper<EquipmentOutChild> equipmentOutChildQueryWrapper = new QueryWrapper<EquipmentOutChild>().eq("sparepart_id", sparepartId);
            List<EquipmentOutChild> equipmentOutChildList = equipmentOutChildService.list(equipmentOutChildQueryWrapper);
            List<String> outIdList = equipmentOutChildList.stream().map(EquipmentOutChild::getOutId).collect(Collectors.toList());
            if (!outIdList.isEmpty()) {
                equipmentOutService.removeByIds(outIdList);
                equipmentOutChildService.remove(equipmentOutChildQueryWrapper);
            }
            return 1;
        });
        return result;
    }

}