MobileInventoryController.java 33 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
package com.huaheng.mobile.invenory;

import com.alibaba.fastjson.JSONException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaheng.api.wcs.domain.WcsTask;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.support.Convert;
import com.huaheng.common.utils.DataUtils;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.aspectj.lang.annotation.Log;
import com.huaheng.framework.aspectj.lang.constant.BusinessType;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.mobile.receipt.MaterialInfo;
import com.huaheng.mobile.task.TaskDomain;
import com.huaheng.pc.config.container.domain.Container;
import com.huaheng.pc.config.container.service.ContainerService;
import com.huaheng.pc.config.location.domain.Location;
import com.huaheng.pc.config.location.service.LocationService;
import com.huaheng.pc.inventory.cycleCountDetail.domain.CycleCountDetail;
import com.huaheng.pc.inventory.cycleCountDetail.domain.CycleCountDetailChild;
import com.huaheng.pc.inventory.cycleCountDetail.service.CycleCountDetailChildService;
import com.huaheng.pc.inventory.cycleCountDetail.service.CycleCountDetailService;
import com.huaheng.pc.inventory.cycleCountHeader.domain.CycleCountHeader;
import com.huaheng.pc.inventory.cycleCountHeader.mapper.CycleCountHeaderMapper;
import com.huaheng.pc.inventory.cycleCountHeader.service.CycleCountHeaderService;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.inventory.inventoryHeader.domain.InventoryHeader;
import com.huaheng.pc.inventory.inventoryHeader.service.InventoryHeaderService;
import com.huaheng.pc.inventory.inventoryTransaction.domain.InventoryTransaction;
import com.huaheng.pc.inventory.inventoryTransaction.service.InventoryTransactionService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.report.excelReport.mapper.ExcelReportMapper;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import com.huaheng.pc.task.taskHeader.service.TransferTaskService;
import com.huaheng.pc.task.taskHeader.service.WorkTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author Enzo Cotter
 * @date 2019/12/15
 */
@CrossOrigin
@RestController
@RequestMapping("/mobile/inventory")
@Api(tags = {"手机立体库库存相关"}, value = "手机立体库库存相关MobileInventoryController")
public class MobileInventoryController {

    @Resource
    private InventoryHeaderService inventoryService;
    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private InventoryTransactionService inventoryTransactionService;
    @Resource
    private TaskHeaderService taskService;
    @Resource
    private TransferTaskService transferTaskService;
    @Resource
    private WorkTaskService workTaskService;

    @Resource
    private LocationService locationService;
    @Resource
    ExcelReportMapper mapper;
    @Resource
    private CycleCountDetailService cycleCountDetailService;
    @Resource
    private ContainerService containerService;
    @Resource
    private CycleCountHeaderService cycleCountHeaderService;
    @Resource
    private CycleCountDetailChildService cycleCountDetailChildService;
    @Resource
    private CycleCountHeaderMapper cycleCountHeaderMapper;

    @PostMapping("/getInventoryInfo")
    @ApiOperation("移动端获得库存详情")
    @Log(title = "移动端获得库存详情", action = BusinessType.OTHER)
    public AjaxResult getInventoryInfo(@RequestBody @ApiParam(value="物料编码或者库位号") Map<String, String> param) {
        if  (param.get("code") == null || param.get("code").trim().length() < 1) {
            throw new JSONException("查询码(code)不能为空");
        }
        if  (param.get("companyCode") == null || param.get("companyCode").trim().length() < 1) {
            throw new JSONException("(companyCode)不能为空");
        }
        return  inventoryService.getInventory(param.get("code"), param.get("companyCode"));
    }

    @PostMapping("/createCheckOutTask")
    @ApiOperation("移动端创建出库查看任务")
    @ResponseBody
    public AjaxResult createCheckOutTask(@RequestBody @ApiParam(value="库存ids") Map<String, String> param){
        String ids = param.get("ids");
        String port = param.get("port");
        Integer companyId = DataUtils.getInteger(param.get("companyId")) ;
        String companyCode = param.get("companyCode");
        if(StringUtils.isEmpty(ids)){
            return AjaxResult.error("ids不能为空");
        }
        return workTaskService.createCheckOutTaskByIds(Arrays.asList(Convert.toIntArray(ids)), port);
    }

    @PostMapping("/transfer")
    @ApiOperation("移动端创建移库任务")
    @ResponseBody
    public AjaxResult transfer(@RequestBody @ApiParam(value="库位情况") Map<String, String> param){
        String sourceLocation = param.get("sourceLocation");
        String destinationLocation = param.get("destinationLocation");
        return transferTaskService.createTransferTask(sourceLocation, destinationLocation);
    }

    @PostMapping( "/execute")
    @ApiOperation("执行立库任务")
    @ResponseBody
    public AjaxResult execute(@RequestBody @ApiParam(value="任务id") Map<String, String> param) {
        String taskId = param.get("taskId");
        if (StringUtils.isEmpty(taskId)) {
            return AjaxResult.error("taskId不能为空");
        }

        AjaxResult ajaxResult = taskService.sendTaskToWcs(Convert.toIntArray(taskId));
        if(ajaxResult.hasErr()) {
            AjaxResult.success("执行失败");
        }
        return AjaxResult.success("下发执行成功");
    }

    @PostMapping( "/executeList")
    @ApiOperation("执行立库任务")
    @Log(title = "执行立库任务", action = BusinessType.OTHER)
    public AjaxResult executeList(@RequestBody List<TaskIds> taskDetails) {
        Integer[] taskIds = new Integer[taskDetails.size()];
        for(int i=0; i<taskDetails.size() ; i++) {
            TaskIds taskDetail = taskDetails.get(i);
            taskIds[i] = taskDetail.getTaskId();
        }
        AjaxResult ajaxResult = taskService.sendTaskToWcs(taskIds);
        return ajaxResult;
    }

    @PostMapping( "/completeTaskByWMS")
    @ApiOperation("完成立库任务")
    @ResponseBody
    public AjaxResult completeTaskByWMS(@RequestBody @ApiParam(value="任务id") Map<String, String> param) throws Exception {
        String taskId = param.get("taskId");
        if (StringUtils.isEmpty(taskId)) {
            return AjaxResult.error("taskId不能为空");
        }

        AjaxResult ajaxResult = taskService.completeTaskByWMS(Convert.toIntArray(taskId), null);
        return ajaxResult;
    }

    @PostMapping( "/completeTaskListByWMS")
    @ApiOperation("完成立库任务")
    @ResponseBody
    public AjaxResult completeTaskListByWMS(@RequestBody List<TaskIds> taskDetails) throws Exception {
        Integer[] taskIds = new Integer[taskDetails.size()];
        for(int i=0; i<taskDetails.size() ; i++) {
            TaskIds taskDetail = taskDetails.get(i);
            taskIds[i] = taskDetail.getTaskId();
        }
        AjaxResult ajaxResult = taskService.completeTaskByWMS(taskIds, null);
        return ajaxResult;
    }

    @PostMapping( "/isLocation")
    @ApiOperation("判断是不是库位")
    @ResponseBody
    public AjaxResult isLocation(@RequestBody @ApiParam(value="任务id") Map<String, String> param) {
        String code = param.get("code");
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("location不能为空");
        }
        LambdaQueryWrapper<Location> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Location::getCode, code);
        Location location = locationService.getOne(queryWrapper);
        if(location == null) {
            return AjaxResult.error("没有这个库位");
        }
        return AjaxResult.success("库位存在").setData(code);
    }

    @PostMapping( "/isContainer")
    @ApiOperation("判断是不是库位")
    @ResponseBody
    public AjaxResult isContainer(@RequestBody @ApiParam(value="任务id") Map<String, String> param) {
        String code = param.get("code");
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("location不能为空");
        }
        LambdaQueryWrapper<Container> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Container::getCode, code);
        Container container = containerService.getOne(queryWrapper);
        if(container == null) {
            return AjaxResult.error("没有这个容器");
        }
        return AjaxResult.success("容器存在").setData(code);
    }

    @PostMapping("/getLocationCode")
    @ApiOperation("移动端获得库位联想词")
    @Log(title = "移动端获得库位联想词", action = BusinessType.OTHER)
    public AjaxResult getLocationCode(@RequestBody @ApiParam(value="库位号") Map<String, String> param) {
        if  (param.get("code") == null || param.get("code").trim().length() < 1) {
            throw new JSONException("查询码(code)不能为空");
        }
        String type = param.get("type");
        if  (type == null || type.trim().length() < 1) {
            throw new JSONException("type不能为空");
        }

        return  inventoryService.getLocationForecast(param.get("code"), Integer.parseInt(type));
    }

    @PostMapping("/createEmptyIn")
    @ApiOperation("移动端空托入库")
    @Log(title = "移动端空托入库", action = BusinessType.OTHER)
    public AjaxResult createEmptyIn(@RequestBody Map<String, String> param) {
        if  (param.get("containerCode") == null || param.get("containerCode").trim().length() < 1) {
            throw new JSONException("容器号不能为空");
        }
//        if  (param.get("destinationLocation") == null || param.get("destinationLocation").trim().length() < 1) {
//            throw new JSONException("目的库位不能为空");
//        }
        String containerCode = param.get("containerCode");
        String destinationLocation = param.get("destinationLocation");
        String companyCode = param.get("companyCode");
        return  inventoryService.createEmptyIn(containerCode, destinationLocation);
    }

    @PostMapping("/createEmptyOut")
    @ApiOperation("移动端空托出库")
    @Log(title = "移动端空托出库", action = BusinessType.OTHER)
    public AjaxResult createEmptyOut(@RequestBody Map<String, String> param) {
        if  (param.get("containerCode") == null || param.get("containerCode").trim().length() < 1){
           throw new JSONException("容器号不能为空");
        }
        if  (param.get("sourceLocation") == null || param.get("sourceLocation").trim().length() < 1) {
            throw new JSONException("源库位不能为空");
        }
        String containerCode = param.get("containerCode");
        String sourceLocation = param.get("sourceLocation");
        return  inventoryService.createEmptyOut(containerCode, sourceLocation);
    }

    @PostMapping("/get7daysShipment")
    @ApiOperation("移动端获取7天收货和出货量")
    @Log(title = "移动端获取7天收货和出货量", action = BusinessType.OTHER)
    public AjaxResult get7daysShipment(@RequestBody Map<String, String> param) {
        String sql = "select a.click_date as date,ifnull(b.taskQty,0) as qty\n" +
                "from (\n" +
                "    SELECT curdate() as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 1 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 2 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 3 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 4 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 5 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 6 day) as click_date\n" +
                ") a left join (\n" +
                "SELECT DATE(h.created) AS created , SUM(d.qty) AS taskQty from shipment_container_detail d join shipment_container_header h on d.shippingContainerId = h.id and h.warehouseCode='"+ShiroUtils.getWarehouseCode()+"' WHERE h.created >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND h.status=30 GROUP BY DATE(h.created)\n" +
                ") b on a.click_date = b.created ORDER BY a.click_date;";
        List<LinkedHashMap<String, Object>> list = mapper.selectCommon(sql);

        sql = "select a.click_date as date,ifnull(b.taskQty,0) as qty\n" +
                "from (\n" +
                "    SELECT curdate() as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 1 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 2 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 3 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 4 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 5 day) as click_date\n" +
                "    union all\n" +
                "    SELECT date_sub(curdate(), interval 6 day) as click_date\n" +
                ") a left join (\n" +
                "SELECT DATE(h.created) AS created , SUM(d.qty) AS taskQty from receipt_container_detail d join receipt_container_header h on d.receiptContainerId = h.id and h.warehouseCode='"+ShiroUtils.getWarehouseCode()+"' WHERE h.created >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND d.status=30 GROUP BY DATE(h.created)\n" +
                ") b on a.click_date = b.created ORDER BY a.click_date;";
        List<LinkedHashMap<String, Object>> list2 = mapper.selectCommon(sql);


        List<LinkedHashMap<String, Object>>  result = new ArrayList<>();
        result.addAll(list);
        result.addAll(list2);

        List<InventoryDetails> inventoryDetailList = new ArrayList<>();
        for(LinkedHashMap<String, Object> map : result) {
            Iterator iter = map.entrySet().iterator();
            String date = null;
            BigDecimal qty = new BigDecimal(0);
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                if(date == null) {
                    date = val.toString();
                } else {
                    qty = (BigDecimal) val;
                }
            }
            inventoryDetailList.add(newInventoryDetail(date, qty));
        }
        return AjaxResult.success(inventoryDetailList);
    }

    private InventoryDetails newInventoryDetail(String date, BigDecimal qty) {
        InventoryDetails inventoryDetail = new InventoryDetails();
        inventoryDetail.setDate(date);
        inventoryDetail.setQty(qty);
        return inventoryDetail;
    }

    @PostMapping("/getTodayShipmentDetail")
    @ApiOperation("移动端获得今天发货详情")
    @Log(title = "移动端获得今天发货详情", action = BusinessType.OTHER)
    public AjaxResult getTodayShipmentDetail(@RequestBody Map<String, String> param) {
        String sql = "select d.materialName, SUM(d.qty) as qty " +
                "from shipment_container_header h join shipment_container_detail d " +
                "on d.shippingContainerId = h.id WHERE h.created >= CURDATE() AND h.`status`>19 GROUP BY d.materialName";
        List<LinkedHashMap<String, Object>> list = mapper.selectCommon(sql);

        sql = "select m.name, b.taskQty as qty \n" +
                "from material m \n" +
                "join (\n" +
                "select d.materialCode as material, SUM(d.qty) " +
                "as taskQty from receipt_container_header h join receipt_container_detail d " +
                "on d.receiptContainerId = h.id WHERE h.created >= CURDATE() AND h.`status`>19 GROUP BY d.materialCode\n" +
                ") b on m.`code` = b.material ORDER BY m.name";
        List<LinkedHashMap<String, Object>> list2 = mapper.selectCommon(sql);
        List<com.huaheng.mobile.invenory.ShipmentDetail> shipmentDetails = getShipmentDetails(list);
        shipmentDetails.add(newShipmentDetail("delete", new BigDecimal(0)));
        shipmentDetails.addAll(getShipmentDetails(list2));

        return AjaxResult.success(shipmentDetails);
    }

    private List<com.huaheng.mobile.invenory.ShipmentDetail> getShipmentDetails(List<LinkedHashMap<String, Object>> list) {
        List<com.huaheng.mobile.invenory.ShipmentDetail> shipmentDetails = new ArrayList<>();
        for (LinkedHashMap<String, Object> map : list) {
            Iterator iter = map.entrySet().iterator();
            String materialName = null;
            BigDecimal qty = new BigDecimal(0);
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                if (materialName == null) {
                    materialName = val.toString();
                } else {
                    qty = (BigDecimal) val;
                }
            }
            shipmentDetails.add(newShipmentDetail(materialName, qty));
        }
        return shipmentDetails;
    }

    private  com.huaheng.mobile.invenory.ShipmentDetail newShipmentDetail(String materialName, BigDecimal qty){
        com.huaheng.mobile.invenory.ShipmentDetail shipmentDetail = new com.huaheng.mobile.invenory.ShipmentDetail();
        shipmentDetail.setMaterialName(materialName);
        shipmentDetail.setQty(qty);
        return shipmentDetail;
    }

    /**
     * 移动端根据容器编码获取盘点任务
     * @param param
     * @return
     */
    @ResponseBody
    @PostMapping("/findTransferByContainerCode")
    public AjaxResult findTransferByContainerCode(@RequestBody Map<String, String> param) {
        String containCode = param.get("containCode");
        if (StringUtils.isEmpty(containCode)){
            return AjaxResult.error("容器编码为空");
        } else {
            return AjaxResult.success(taskService.mobileFindTransferTask(containCode));
        }
    }

    /**
     * 移动端实盘登记
     * @return
     */
    @ResponseBody
    @PostMapping("/confirmGapQty")
    public AjaxResult confirmGapQty(@RequestBody List<MaterialInfo> materialInfos) {
        for(MaterialInfo materialInfo : materialInfos) {
            int detailId = materialInfo.getBillDetailId();
            BigDecimal qty = new BigDecimal(materialInfo.getQty());
//            CycleCountDetail cycleCountDetail = cycleCountDetailService.getById(detailId);
            LambdaQueryWrapper<CycleCountDetailChild> cycleCountDetailChildLambdaQueryWrapper = Wrappers.lambdaQuery();
            cycleCountDetailChildLambdaQueryWrapper.eq(CycleCountDetailChild::getCycleCountDetailId, detailId)
            .eq(CycleCountDetailChild::getMaterialCode, materialInfo.getMaterialCode());
            CycleCountDetailChild cycleCountDetailChild = cycleCountDetailChildService.getOne(cycleCountDetailChildLambdaQueryWrapper);
            AjaxResult ajaxResult = cycleCountDetailService.confirmGapQty(cycleCountDetailChild.getId(), qty);
            if(ajaxResult.hasErr()) {
                return AjaxResult.error("盘点失败");
            }
        }
        return AjaxResult.success("盘点成功");
    }

    @PostMapping("/getEmptyContainerInLocation")
    @ApiOperation("选取空托出库的库位")
    @Log(title = "选取空托出库的库位", action = BusinessType.OTHER)
    public AjaxResult getEmptyContainerInLocation(@RequestBody Map<String, String> param) {
        String warehouCOde =  ShiroUtils.getWarehouseCode();
        List<Location> list = containerService.getEmptyContainerInLocation(null, null,null,ShiroUtils.getWarehouseCode());
        return  AjaxResult.success(list);
    }

    @PostMapping("/pickLocation")
    @ApiOperation("选取补充入库的库位")
    @Log(title = "选取补充入库的库位", action = BusinessType.OTHER)
    public AjaxResult pickLocation(@RequestBody Map<String, String> param) {
        List<Location> locations = locationService.pickLocation();
        Container condition = new Container();
        condition.setWarehouseCode(ShiroUtils.getWarehouseCode());
        LambdaQueryWrapper lambda3 = Wrappers.lambdaQuery(condition);
        List<Container> containers = containerService.list(lambda3);
        for(Location  location : locations) {
            for(Container container : containers) {
                if(container.getCode().equals(location.getContainerCode())) {
                    if(QuantityConstant.STATUS_CONTAINER_SOME.equals(container.getStatus())) {
                        location.setStatus(QuantityConstant.STATUS_LOCATION_LOCK);
                    }
                }
            }
        }
        return  AjaxResult.success(locations);
    }

    @PostMapping("/searchInventory")
    @ApiOperation("移动端查询库存")
    @Log(title = "移动端查询库存", action = BusinessType.OTHER)
    public AjaxResult searchInventory(@RequestBody @ApiParam(value = "物料号") Map<String, String> param){
        String companyCode = param.get("companyCode");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = df.format(new Date());
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, -7);
        Date first = c.getTime();
        String start = df.format(first);//前一天
        LambdaQueryWrapper<InventoryDetail> inventoryQueryWrapper = Wrappers.lambdaQuery();
        inventoryQueryWrapper.eq(InventoryDetail::getCompanyCode, companyCode)
                .eq(InventoryDetail::getWarehouseCode, ShiroUtils.getWarehouseCode())
                .orderByDesc(InventoryDetail::getCreated);
        List<InventoryDetail> inventoryDetailList = inventoryDetailService.list(inventoryQueryWrapper);
        return AjaxResult.success(inventoryDetailList);
    }

    @PostMapping("/searchInventoryInCondition")
    @ApiOperation("移动端查询库存")
    @Log(title = "移动端查询库存", action = BusinessType.OTHER)
    public AjaxResult searchInventoryInCondition(@RequestBody @ApiParam(value = "物料号") Map<String, String> param){
        String companyCode = param.get("companyCode");
        String containerCode = param.get("containerCode");
        String materialCode = param.get("materialCode");
        String materialName = param.get("materialName");
        String materialSpec = param.get("materialSpec");
        String startTime = param.get("startTime");
        String endTime = param.get("endTime");
        LambdaQueryWrapper<InventoryDetail> inventoryQueryWrapper = Wrappers.lambdaQuery();
        inventoryQueryWrapper.eq(InventoryDetail::getCompanyCode, companyCode)
                .eq(InventoryDetail::getWarehouseCode, ShiroUtils.getWarehouseCode())
                .eq(StringUtils.isNotEmpty(containerCode), InventoryDetail::getContainerCode, containerCode)
                .like(StringUtils.isNotEmpty(materialCode), InventoryDetail::getMaterialCode, materialCode)
                .like(StringUtils.isNotEmpty(materialName), InventoryDetail::getMaterialName, materialName)
                .like(StringUtils.isNotEmpty(materialSpec), InventoryDetail::getMaterialSpec, materialSpec)
                .gt(StringUtils.isNotEmpty(startTime), InventoryDetail::getCreated, startTime)
                .le(StringUtils.isNotEmpty(endTime), InventoryDetail::getCreated, endTime)
                .orderByDesc(InventoryDetail::getCreated);
        List<InventoryDetail> inventoryDetailList = inventoryDetailService.list(inventoryQueryWrapper);
        return AjaxResult.success(inventoryDetailList);
    }


    @PostMapping("/findInventory")
    @ApiOperation("移动端查询库存详情")
    @Log(title = "移动端查询库存详情", action = BusinessType.OTHER)
    public AjaxResult findInventory(@RequestBody @ApiParam(value = "物料号") Map<String, String> param){
        String inventoryDetailId = param.get("inventoryDetailId");
        String companyCode = param.get("companyCode");
        if (StringUtils.isNull(inventoryDetailId)){
            return AjaxResult.error("任务id为空");
        } else if (StringUtils.isNull(companyCode)){
            return AjaxResult.error("公司编码为空");
        }

        /* 查询入库单,如果数据库中不存在,则调用ERP接口拉取单据,成功后再次查询返回结果*/
        LambdaQueryWrapper<InventoryDetail> inventoryQueryWrapper = Wrappers.lambdaQuery();
        inventoryQueryWrapper.eq(InventoryDetail::getId, inventoryDetailId)
                .eq(InventoryDetail::getCompanyCode, companyCode);
        InventoryDetail inventoryDetail = inventoryDetailService.getOne(inventoryQueryWrapper);
        if(inventoryDetail == null) {
            return AjaxResult.error("没有找到库存详情");
        }
        return AjaxResult.success(inventoryDetail);
    }

    @PostMapping("/searchInventoryTransactionInCondition")
    @ApiOperation("移动端查询库存交易记录")
    @Log(title = "移动端查询库存交易记录", action = BusinessType.OTHER)
    public AjaxResult searchInventoryTransactionInCondition(@RequestBody @ApiParam(value = "物料号") Map<String, String> param){
        String companyCode = param.get("companyCode");
        String transactionType = param.get("transactionType");
        String containerCode = param.get("containerCode");
        String materialCode = param.get("materialCode");
        String materialName = param.get("materialName");
        String materialSpec = param.get("materialSpec");
        String startTime = param.get("startTime");
        String endTime = param.get("endTime");
        LambdaQueryWrapper<InventoryTransaction> inventoryTransactionLambdaQueryWrapper = Wrappers.lambdaQuery();
        inventoryTransactionLambdaQueryWrapper.eq(InventoryTransaction::getCompanyCode, companyCode)
                .eq(InventoryTransaction::getWarehouseCode, ShiroUtils.getWarehouseCode())
                .eq(StringUtils.isNotEmpty(transactionType), InventoryTransaction::getTransactionType, transactionType)
                .eq(StringUtils.isNotEmpty(containerCode), InventoryTransaction::getContainerCode, containerCode)
                .like(StringUtils.isNotEmpty(materialCode), InventoryTransaction::getMaterialCode, materialCode)
                .like(StringUtils.isNotEmpty(materialName), InventoryTransaction::getMaterialName, materialName)
                .like(StringUtils.isNotEmpty(materialSpec), InventoryTransaction::getMaterialSpec, materialSpec)
                .gt(StringUtils.isNotEmpty(startTime), InventoryTransaction::getCreated, startTime)
                .le(StringUtils.isNotEmpty(endTime), InventoryTransaction::getCreated, endTime)
                .orderByDesc(InventoryTransaction::getCreated);
        List<InventoryTransaction> inventoryDetailList = inventoryTransactionService.list(inventoryTransactionLambdaQueryWrapper);
        return AjaxResult.success(inventoryDetailList);
    }


    @PostMapping("/circleCount")
    @ApiOperation("移动端盘点库存")
    @Log(title = "移动端盘点库存", action = BusinessType.OTHER)
    public AjaxResult circleCount(@RequestBody List<CircleBean> circleBeanList){
        String locaitonCode = circleBeanList.get(0).getLocaitonCode();
        String containerCode = circleBeanList.get(0).getContainerCode();
        String circleCode = addCircleHeader(circleBeanList);
        boolean diff = false;
        for(CircleBean circleBean : circleBeanList) {
            LambdaQueryWrapper<CycleCountDetailChild> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(CycleCountDetailChild::getContainerCode, containerCode)
                    .eq(CycleCountDetailChild::getLocationCode, locaitonCode)
                    .eq(CycleCountDetailChild::getCycleCountHeadCode, circleCode)
                    .eq(CycleCountDetailChild::getChildStatus, 1)
                    .eq(CycleCountDetailChild::getMaterialCode, circleBean.getMaterialCode());
            CycleCountDetailChild cycleCountDetailChild = cycleCountDetailChildService.getOne(lambdaQueryWrapper);
            AjaxResult result = cycleCountDetailService.confirmGapQty(cycleCountDetailChild.getId(), new BigDecimal(circleBean.getQty()));
            cycleCountDetailChild = (CycleCountDetailChild)result.getData();
            LambdaQueryWrapper<CycleCountDetail> lambdaQueryWrapper1 = Wrappers.lambdaQuery();
            lambdaQueryWrapper1.eq(CycleCountDetail::getId, cycleCountDetailChild.getCycleCountDetailId());
            CycleCountDetail cycleCountDetail = cycleCountDetailService.getOne(lambdaQueryWrapper1);
            if(cycleCountDetailChild.getGapQty().compareTo(BigDecimal.ZERO) != 0){
                cycleCountDetailChild.setChildStatus(QuantityConstant.CYCLECOUNT_STATUS_DIFFERENCE);
                cycleCountDetail.setEnableStatus(QuantityConstant.CYCLECOUNT_STATUS_DIFFERENCE);
                diff = true;
            }else{
                cycleCountDetailChild.setChildStatus(QuantityConstant.CYCLECOUNT_STATUS_COMPLETED);
                cycleCountDetail.setEnableStatus(QuantityConstant.CYCLECOUNT_STATUS_COMPLETED);
            }
        }
        LambdaQueryWrapper<CycleCountHeader> lambdaQueryWrapper2 = Wrappers.lambdaQuery();
        lambdaQueryWrapper2.eq(CycleCountHeader::getCode, circleCode);
        CycleCountHeader cycleCountHeader = cycleCountHeaderService.getOne(lambdaQueryWrapper2);
        if(diff) {
            cycleCountHeader.setStatusCyc(QuantityConstant.CYCLECOUNT_STATUS_DIFFERENCE);
        } else {
            cycleCountHeader.setStatusCyc(QuantityConstant.CYCLECOUNT_STATUS_COMPLETED);
        }
        cycleCountHeaderService.updateById(cycleCountHeader);
        return AjaxResult.success();
    }

    private String addCircleHeader(List<CircleBean> circleBeanList) {
        String maxCode =  cycleCountHeaderMapper.getLastCode();
        LambdaQueryWrapper<CycleCountHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(CycleCountHeader::getCode, maxCode)
                .le (CycleCountHeader::getStatusCyc, 105);
        CycleCountHeader cycleCountHeader = new CycleCountHeader();
        CycleCountHeader header = cycleCountHeaderService.getOne(lambdaQueryWrapper);
        if(header == null) {
            cycleCountHeader.setCreated(new Date());
            cycleCountHeader.setCreatedBy(ShiroUtils.getLoginName());
            cycleCountHeader.setCountType("static");
            cycleCountHeader.setCode(createCode());
            cycleCountHeader.setPreferenceCode("ccp2019101700001");
            cycleCountHeader.setRound(1);
            cycleCountHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
            cycleCountHeader.setStatusCyc(1);
            cycleCountHeader.setCountAttribute(1);
            cycleCountHeader.setTotalLocs(0);
            cycleCountHeader.setTotalItems(0);
            cycleCountHeader.setLastUpdated(new Date());
            cycleCountHeader.setLastUpdatedBy(ShiroUtils.getLoginName());
            cycleCountHeader.setEnable(true);
            cycleCountHeaderService.save(cycleCountHeader);
        } else {
            cycleCountHeader = header;
        }
        LambdaQueryWrapper<InventoryHeader> inventoryHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        inventoryHeaderLambdaQueryWrapper.eq(InventoryHeader::getLocationCode, circleBeanList.get(0).getLocaitonCode());
        InventoryHeader inventoryHeader = inventoryService.getOne(inventoryHeaderLambdaQueryWrapper);
        Integer[] inventoryHeaderIds = new Integer[]{inventoryHeader.getId()};
        cycleCountDetailService.addDetails(cycleCountHeader.getCode(), inventoryHeaderIds);
        return cycleCountHeader.getCode();
    }

    /**
     * 生成盘点单主Code
     * @return
     */
    public String createCode() {
        String code;
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String maxCode =  cycleCountHeaderMapper.getLastCode();;
        //如果指定类型的最后的code存在,并且日期一致。那么 code = 单类型 + 年月日 + (排序号 + 1)
        if (maxCode != null && maxCode.substring(maxCode.length() - 13, maxCode.length() - 5).equals(df.format(now)))
        {
            Integer Count = Integer.valueOf(maxCode.substring(maxCode.length() - 5,maxCode.length()));
            code = "PD" + df.format(now) + String.format("%05d", Count + 1);
        }
        else
        {
            code = "PD" + df.format(now) + "00001";
        }
        return code;
    }

}