BigScreenController.java 13.8 KB
package com.huaheng.api.tv.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaheng.api.tv.domain.BigScreenTask;
import com.huaheng.api.tv.domain.MaterialTable;
import com.huaheng.api.tv.service.BigScreenService;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.report.excelReport.mapper.ExcelReportMapper;
import com.huaheng.pc.system.user.controller.IndexController;
import com.huaheng.pc.task.taskDetail.domain.TaskDetail;
import com.huaheng.pc.task.taskDetail.service.TaskDetailService;
import com.huaheng.pc.task.taskHeader.domain.TaskHeader;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping
public class BigScreenController {
    @Resource
    private IndexController indexController;
    @Resource
    ExcelReportMapper mapper;
    @Resource
    private BigScreenService bigScreenService;

    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private TaskDetailService taskDetailService;
    @Resource
    private TaskHeaderService taskHeaderService;


    @CrossOrigin
    @RequestMapping("/mainA")
    private JSON mainA() {
        return BigScreenData("A");
    }

    @CrossOrigin
    @RequestMapping("/mainB")
    private JSON mainB() {
        return BigScreenData("B");
    }

    @CrossOrigin
    @RequestMapping("/mainC")
    private JSON mainC() {
        return BigScreenData("C");
    }

    //主看板

    private JSON BigScreenData(String zone) {
        JSONObject jsonObject = new JSONObject();
        //左上方
        Map<String, Object> upperLeft = (Map<String, Object>) upperLeft(zone).getData();
        jsonObject.put("upperLeft", upperLeft);

        //右上方
        Map<String, Object> upperRight = (Map<String, Object>) upperRight(zone).getData();
        jsonObject.put("upperRight", upperRight);

        //右下方
        Map<String, Object> bottomRight = (Map<String, Object>) bottomRight(zone).getData();
        jsonObject.put("bottomRight", bottomRight);

        //物料表格
        if (zone.equals("B")) {
            Map<String, Object> materialTable = (Map<String, Object>) materialTable(zone).getData();
            jsonObject.put("headerRight", materialTable);
        }
        return jsonObject;
    }


    private MaterialTable createMaterialTable(String name) {
        MaterialTable materialTable = new MaterialTable();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 查询 InventoryDetail 数据
        List<InventoryDetail> inventoryDetails = inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>().eq(InventoryDetail::getMaterialName, name));
        if (!inventoryDetails.isEmpty()) {
            BigDecimal totalQty = inventoryDetails.stream().map(InventoryDetail::getQty).reduce(BigDecimal.ZERO, BigDecimal::add);
            materialTable.setTotalQty(totalQty);
            materialTable.setMaterialName(inventoryDetails.get(0).getMaterialName());

            // 设置材料单位
            if ("铜箔".equals(name)) {
                materialTable.setMaterialUnit("千克");
            } else if ("PP卷 内销PR".equals(name) || "PP卷 外销BR".equals(name)) {
                materialTable.setMaterialUnit("米");
            } else if ("PP片压合".equals(name)) {
                materialTable.setMaterialUnit("张");
            }
        }

        // 查询 TaskDetail 数据(限制结果集大小)
        List<TaskDetail> taskDetails = taskDetailService.list(new LambdaQueryWrapper<TaskDetail>().eq(TaskDetail::getMaterialName, name).orderByDesc(TaskDetail::getId).last("limit 3000"));

        // 查询 TaskHeader 数据(限制结果集大小)
        List<TaskHeader> taskHeaders = taskHeaderService.list(new LambdaQueryWrapper<TaskHeader>().orderByDesc(TaskHeader::getId).last("limit 2000"));

        // 使用 taskId 关联 TaskDetail 和 TaskHeader
        Map<Integer, TaskHeader> taskHeaderMap = taskHeaders.stream().collect(Collectors.toMap(TaskHeader::getId, taskHeader -> taskHeader));

        // 筛选 TaskHeader.status 为 100 的记录,并关联相应的 TaskDetail
        taskDetails = taskDetails.stream()
                .filter(taskDetail -> {
                    TaskHeader taskHeader = taskHeaderMap.get(taskDetail.getTaskId());
                    return taskHeader != null && taskHeader.getStatus() == 100;
                })
                .collect(Collectors.toList());

        // 筛选出 lastUpdated 为当天的数据
        List<TaskDetail> todayTaskDetails = taskDetails.stream()
                .filter(taskDetail -> {
                    LocalDate lastUpdatedDate = taskDetail.getLastUpdated().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    return currentDate.equals(lastUpdatedDate);
                })
                .collect(Collectors.toList());

        // 计算 receiptDay、shipmentDat 和 transactionQty
        BigDecimal receiptDay = todayTaskDetails.stream().filter(taskDetail -> taskDetail.getInternalTaskType() == 100).map(TaskDetail::getQty).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal shipmentDat = todayTaskDetails.stream().filter(taskDetail -> taskDetail.getInternalTaskType() == 200).map(TaskDetail::getQty).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal transactionQty = receiptDay.add(shipmentDat);

        materialTable.setReceiptDay(receiptDay);
        materialTable.setShipmentDat(shipmentDat);
        materialTable.setTransactionQty(transactionQty);

        return materialTable;
    }

    //物料表格
    public AjaxResult materialTable(String zone) {
        ArrayList<MaterialTable> materialTables = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        List<String> materialNames = Arrays.asList("铜箔", "PP卷 内销PR", "PP卷 外销BR", "PP片压合");
        for (String name : materialNames) {
            MaterialTable materialTable = createMaterialTable(name);
            materialTables.add(materialTable);
        }
        map.put("materialTable", materialTables);
        return AjaxResult.success(map);
    }


    //左上方
    public AjaxResult upperLeft(String zone) {
        Map<String, Object> map = new HashMap<>();
        //库位利用率(矮库位有货、矮库位无货、高库位有货、高库位无货)
        String sql1 = "SELECT\n" +
                "SUM(CASE WHEN zoneCode='" + zone + "' AND l.warehouseCode = 'CS0001' AND containerCode !='' AND c.`status`='some' AND high = 0 THEN 1 ELSE 0 END) AS 'lowInStock',\n" +
                "SUM(CASE WHEN zoneCode='" + zone + "' AND l.warehouseCode = 'CS0001' AND containerCode ='' AND high = 0 THEN 1 ELSE 0 END) AS 'lowSoldOut',\n" +
                "SUM(CASE WHEN zoneCode='" + zone + "' AND l.warehouseCode = 'CS0001' AND containerCode !='' AND c.`status`='some' AND high = 1 THEN 1 ELSE 0 END) AS 'highInStock',\n" +
                "SUM(CASE WHEN zoneCode='" + zone + "' AND l.warehouseCode = 'CS0001' AND containerCode ='' AND high = 1 THEN 1 ELSE 0 END) AS 'highSoldOut'\n" +
                "FROM location l left join container c on l.code=c.locationCode;";
        List<LinkedHashMap<String, Object>> locationProportion = mapper.selectCommon(sql1);
        map.put("locationProportion", locationProportion);


        //库存物料
        String sql2 = "SELECT m.`name`,sum(i.qty) as total from inventory_detail i join material m on i.materialCode = m.`code`  and zoneCode='" + zone + "' and i.warehouseCode = m.warehouseCode AND i.warehouseCode = '" + ShiroUtils.getWarehouseCodeCS0001() + "' \n" +
                "GROUP BY m.`name` ORDER BY total desc;";
        List<LinkedHashMap<String, Object>> inventoryMaterial = mapper.selectCommon(sql2);
        map.put("inventoryMaterial", inventoryMaterial);


        //空托盘
        String sql3 = "";
        if ("A".equals(zone)) {
            sql3 = "SELECT ct.name, COUNT(*) AS count FROM container c JOIN container_type ct ON c.containerType = ct.code \n" +
                    "WHERE c.status = 'empty' and c.locationCode!='' AND c.containerType in ('A') GROUP BY ct.name;";
        } else if ("B".equals(zone)) {
            sql3 = "SELECT ct.name, COUNT(*) AS count FROM container c JOIN container_type ct ON c.containerType = ct.code \n" +
                    "WHERE c.status = 'empty' and c.locationCode!='' AND c.containerType in ('B', 'C', 'D', 'E') GROUP BY ct.name;";
        } else {
            sql3 = "SELECT ct.name, COUNT(*) AS count FROM container c JOIN container_type ct ON c.containerType = ct.code \n" +
                    "WHERE c.status = 'empty' and c.locationCode!='' AND c.containerType in ('F', 'G') GROUP BY ct.name;";
        }
        List<LinkedHashMap<String, Object>> emptyPallet = mapper.selectCommon(sql3);
        map.put("emptyPallet", emptyPallet);

        return AjaxResult.success(map);
    }


    //右下方
    public AjaxResult bottomRight(String zone) {
        Map<String, Object> map = new HashMap<>();
        //出入库任务
        List<BigScreenTask> receiptTasks = bigScreenService.selectReceiptTask(zone);
        List<BigScreenTask> shipmentTasks = bigScreenService.selectShipmentTask(zone);
        map.put("receiptTasks", receiptTasks);
        map.put("shipmentTasks", shipmentTasks);
        return AjaxResult.success(map);
    }

    //右上方
    public AjaxResult upperRight(String zone) {
        String condition = " and warehouseCode = '" + ShiroUtils.getWarehouseCodeCS0001() + "'";
        Map<String, Object> map = new HashMap<>();

        //库存交易量
        String bllCount = "select ifnull(sum( d.qty ),0) 'total' FROM task_header h join task_detail d on h.id =d.taskId WHERE DATEDIFF(NOW(), h.completeTime) = 0 and (h.taskType=100 or h.taskType=200 or h.taskType=300 or h.taskType=400) and h.zoneCode='" + zone + "' and h.status=100";
        List<LinkedHashMap<String, Object>> temp1 = mapper.selectCommon(bllCount);
        map.put("bllCount", temp1.get(0).entrySet().iterator().next().getValue());

        //今日入库量
        String receiptTotal = "select ifnull(sum( d.qty ),0) 'total' FROM task_header h join task_detail d on h.id =d.taskId WHERE DATEDIFF(NOW(), h.completeTime) = 0 and (h.taskType=100 or h.taskType=200) and h.zoneCode='" + zone + "' and  h.status=100";
        List<LinkedHashMap<String, Object>> temp2 = mapper.selectCommon(receiptTotal);
        map.put("receiptTotal", temp2.get(0).entrySet().stream().findFirst().get().getValue());

        //今日出库量
        String shipmentTotal = "select ifnull(sum( d.qty ),0) 'total' FROM task_header h join task_detail d on h.id =d.taskId WHERE DATEDIFF(NOW(), h.completeTime) = 0 and (h.taskType=300 or h.taskType=400) and h.zoneCode='" + zone + "' and h.status=100";
        List<LinkedHashMap<String, Object>> temp3 = mapper.selectCommon(shipmentTotal);
        map.put("shipmentTotal", temp3.get(0).entrySet().stream().findFirst().get().getValue());

        //库存总量
        String inventoryTotal = "SELECT IFNULL(SUM(totalQty),0) 'total' from inventory_header  where 1=1  and zoneCode='" + zone + "'";
        List<LinkedHashMap<String, Object>> temp4 = mapper.selectCommon(inventoryTotal);
        map.put("inventoryTotal", temp4.get(0).entrySet().stream().findFirst().get().getValue());

        //库内空托盘数
        String availableLocationCount = "SELECT COUNT(*) 'total' FROM location t WHERE t.STATUS = 'empty' AND t.containerCode != '' AND t.containerCode IS NOT NULL AND t.containerCode NOT IN ( SELECT h.containerCode FROM task_header h WHERE STATUS < 100  ) AND t.`code` NOT IN ( SELECT b.locationCode FROM inventory_detail b )  and zoneCode='" + zone + "'";
        List<LinkedHashMap<String, Object>> temp5 = mapper.selectCommon(availableLocationCount);
        map.put("availableLocationCount", temp5.get(0).entrySet().stream().findFirst().get().getValue());

        //未完成任务
        String taskUncompletedTotal = "SELECT ifnull(COUNT(*),0) 'total' from task_header  WHERE zoneCode='" + zone + "' and  status < 100";
        List<LinkedHashMap<String, Object>> temp6 = mapper.selectCommon(taskUncompletedTotal);
        map.put("taskUncompletedTotal", temp6.get(0).entrySet().stream().findFirst().get().getValue());

        //有货托盘数
        String someContainerCount = "SELECT count(*) 'total' from inventory_header  where 1=1  and zoneCode='" + zone + "'";
        List<LinkedHashMap<String, Object>> temp7 = mapper.selectCommon(someContainerCount);
        map.put("someContainerCount", temp7.get(0).entrySet().stream().findFirst().get().getValue());

        //剩余库位
        String surplusLocationCount = "SELECT COUNT(*) 'total' from location where containerCode ='' and zoneCode='" + zone + "' and status='empty'";
        List<LinkedHashMap<String, Object>> temp8 = mapper.selectCommon(surplusLocationCount);
        map.put("surplusLocationCount", temp8.get(0).entrySet().stream().findFirst().get().getValue());

        //String materialCount = "SELECT ifnull(count(DISTINCT materialCode),0) 'total'  from inventory_detail  WHERE h.zoneCode='" + zone + "'";
        //List<LinkedHashMap<String, Object>> temp7 = mapper.selectCommon(materialCount);
        //map.put("materialCount", temp7.get(0).entrySet().stream().findFirst().get().getValue());

        return AjaxResult.success(map);
    }
}