package com.wms_main.service.controller.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms_main.dao.impl.*;
import com.wms_main.model.po.*;
import com.wms_main.service.controller.IDataControllerService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据控制器服务实现类
 */
@Service
@RequiredArgsConstructor
public class DataControllerServiceImpl implements IDataControllerService {

    private final TAppTaskServiceImpl tAppTaskService;
    private final TAppOutsServiceImpl tAppOutsService;
    private final TAppPickTaskServiceImpl tAppPickTaskService;
    private final TAppTaskBakServiceImpl tAppTaskBakService;
    private final TAppStockServiceImpl tAppStockService;

    /**
     * 获取任务类型为1的任务数据
     * @return 任务类型为1的任务列表
     */
    @Override
    public List<TAppTask> getTaskTypInData(int pageNum, int pageSize, int standId) {
        LambdaQueryWrapper<TAppTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TAppTask::getTaskType, 1);

        // 如果 standId 等于 1，则筛选终点以 "A1" 或 "A2" 开头的数据
        if (standId == 1) {
            queryWrapper.and(wrapper -> wrapper.likeRight(TAppTask::getDestination, "A1")
                    .or()
                    .likeRight(TAppTask::getDestination, "A2"));
        }else if (standId == 2){
            queryWrapper.and(wrapper -> wrapper.likeRight(TAppTask::getDestination, "A3")
                    .or()
                    .likeRight(TAppTask::getDestination, "A4"));
        } else if (standId == 3) {
            queryWrapper.and(wrapper -> wrapper.likeRight(TAppTask::getDestination, "A5")
                    .or()
                    .likeRight(TAppTask::getDestination, "A6"));
        }

        return tAppTaskService.page(new Page<>(pageNum, pageSize), queryWrapper).getRecords();
    }


    /**
     * 获取出库数据
     * @return 出库数据列表
     */
    @Override
    public List<TAppOuts> getOutsData(int pageNum, int pageSize) {
        LambdaQueryWrapper<TAppOuts> queryWrapper = new LambdaQueryWrapper<>();
        return tAppOutsService.page(new Page<>(pageNum, pageSize), queryWrapper).getRecords();
    }

    /**
     * 获取拣选任务数据
     * @return 拣选任务数据列表
     */
    @Override
    public List<TAppPickTask> getPickTaskDataP1(int pageNum, int pageSize) {
        LambdaQueryWrapper<TAppPickTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TAppPickTask::getPickStand, "P11", "P12", "P13")
                .orderByDesc(TAppPickTask::getPickStatus);
        return tAppPickTaskService.page(new Page<>(pageNum, pageSize), queryWrapper).getRecords();
    }

    @Override
    public List<TAppPickTask> getPickTaskDataP2(int pageNum, int pageSize) {
        LambdaQueryWrapper<TAppPickTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TAppPickTask::getPickStand, "P14", "P15", "P16")
                .orderByDesc(TAppPickTask::getPickStatus);
        return tAppPickTaskService.page(new Page<>(pageNum, pageSize), queryWrapper).getRecords();
    }

    @Override
    public List<TAppPickTask> getPickTaskDataP3(int pageNum, int pageSize) {
        LambdaQueryWrapper<TAppPickTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TAppPickTask::getPickStand, "P17", "P18", "P19")
                .orderByDesc(TAppPickTask::getPickStatus);;
        return tAppPickTaskService.page(new Page<>(pageNum, pageSize), queryWrapper).getRecords();
    }

    @Override
    public List<Map<String, Object>> queryRecentTask() {
        List<Map<String, Object>> result = new ArrayList<>();

        // 获取最近7天的日期
        List<LocalDate> recentDays = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            recentDays.add(LocalDate.now().minusDays(i));
        }

        // 查询最近7天的数据
        for (LocalDate date : recentDays) {
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.atTime(23, 59, 59);

            LambdaQueryWrapper<TAppTaskBak> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.between(TAppTaskBak::getCreateTime, startOfDay, endOfDay);

            List<TAppTaskBak> tasks = tAppTaskBakService.list(queryWrapper);

            // 统计各类任务数量
            int inTaskCount = 0;
            int outTaskCount = 0;
            int moveTaskCount = 0;

            for (TAppTaskBak task : tasks) {
                switch (task.getTaskType()) {
                    case 1: // 入库任务
                        inTaskCount++;
                        break;
                    case 2: // 出库任务
                        outTaskCount++;
                        break;
                    case 3: // 移库任务
                        moveTaskCount++;
                        break;
                }
            }

            Map<String, Object> item = new HashMap<>();
            item.put("dataDate", date.toString());
            item.put("inTaskCount", inTaskCount);
            item.put("outTaskCount", outTaskCount);
            item.put("moveTaskCount", moveTaskCount);
            result.add(item);
        }

        return result;
    }
    /**
     * 根据库位ID查询库存详情
     * @param locationId 库位ID
     * @return 库存详情列表
     */
    @Override
    public List<Map<String, Object>> queryStockDetail(String locationId) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 1. 构造查询条件
        LambdaQueryWrapper<TAppStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TAppStock::getLocationId, locationId);

        // 2. 查询库存数据
        List<TAppStock> stockList = tAppStockService.list(queryWrapper);

        // 3. 转换为 Map 格式返回
        for (TAppStock stock : stockList) {
            Map<String, Object> item = new HashMap<>();
            item.put("goodsId", stock.getGoodsId()); // 物料编号
            item.put("goodsName", stock.getGoodsDesc()); // 物料名称
            item.put("goodsNum", stock.getRealNum()); // 物料数量
            item.put("wareDate", stock.getFirstInTime()); // 库上架时间
            item.put("specialStock", stock.getSpecialStock()); // 质量（kg）
            item.put("specialStockNo", stock.getSpecialStockNo()); // 产期
            item.put("specialStockItemNo", stock.getSpecialStockItemNo()); // 到期期
            item.put("batchId", stock.getBatchNo()); // 批次号
            item.put("subpool", stock.getLocationId()); // 库编码
            result.add(item);
        }

        return result;
    }


    @Override
    public List<Map<String, Object>> queryRunningTask() {
        List<Map<String, Object>> result = new ArrayList<>();

        // 1. 查询运行中的任务数据，优先从 TAppTask 表中查询（最多10条）
        LambdaQueryWrapper<TAppTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.last("LIMIT 10");
        List<TAppTask> taskList = tAppTaskService.list(queryWrapper);

        // 2. 添加实时任务到结果中
        for (TAppTask task : taskList) {
            Map<String, Object> item = new HashMap<>();
            item.put("goodsId", task.getGoodsId()); // 物品编号
            item.put("goodsName", task.getGoodsDesc()); // 物品名称
            item.put("goodsNum", task.getOpNum()); // 物品数量
            item.put("origin", task.getOrigin()); // 搬运起点
            item.put("taskType", task.getTaskType()); // 任务类型
            item.put("destination", task.getDestination()); // 搬运终点
            result.add(item);
        }

        // 3. 如果实时任务不足10条，则从 TAppTaskBak 表中查询最近的任务记录来补足
        if (result.size() < 10) {
            int remainingCount = 10 - result.size();

            LambdaQueryWrapper<TAppTaskBak> bakQueryWrapper = new LambdaQueryWrapper<>();
            bakQueryWrapper.orderByDesc(TAppTaskBak::getCreateTime);
            bakQueryWrapper.last("LIMIT " + remainingCount);

            List<TAppTaskBak> bakTaskList = tAppTaskBakService.list(bakQueryWrapper);

            for (TAppTaskBak task : bakTaskList) {
                Map<String, Object> item = new HashMap<>();
                item.put("goodsId", task.getGoodsId()); // 物品编号
                item.put("goodsName", task.getGoodsDesc()); // 物品名称
                item.put("goodsNum", task.getOpNum()); // 物品数量
                item.put("origin", task.getOrigin()); // 搬运起点
                item.put("taskType", task.getTaskType()); // 任务类型
                item.put("destination", task.getDestination()); // 搬运终点
                result.add(item);
            }
        }

        return result;
    }


}
