package com.zbf.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbf.common.annotation.DataSource;
import com.zbf.common.enums.DataSourceType;
import com.zbf.system.domain.*;
import com.zbf.system.domain.vo.Quest;
import com.zbf.system.mapper.*;
import com.zbf.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LargeScreenServiceImpl implements LargeScreenService {

    @Autowired
    private ITCkPickingwavegoodsService goodsService;

    @Autowired
    private ITOngoodsshelfService ongoodsshelfService;


    @Autowired
    private ITCkPickingwavegoodsBakService bakService;

    @Autowired
    private ITOngoodsshelfBakService ongoodsshelfBakService;


    @Autowired
    private TBaseStorageAreaLocationMapper storageAreaLocationMapper;

    @Autowired
    private TMiStockMapper tMiStockMapper;

    @Autowired
    private TAgvMapper tAgvMapper;

    @Autowired
    private TErrorLogMapper tErrorLogMapper;
    @Autowired
    private TBaseGoodsMapper mapper;

    @Autowired
    private ITMiStockService miStockService;

    @Autowired
    private ITSafetyStockService itSafetyStockService;


    /**
     * 饼图  仓位统计
     *
     * @return
     */
    @Override
    public Map<String, Object> pieChart() {
        // 使用MyBatis Plus的QueryWrapper来进行分组统计
        QueryWrapper<TBaseStorageAreaLocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("status", "COUNT(*) as count")
                .groupBy("status");
        List<Map<String, Object>> statusCounts = storageAreaLocationMapper.selectMaps(queryWrapper);
        // 计算库存占用的库位总数
        QueryWrapper<TMiStock> stockQueryWrapper = new QueryWrapper<>();
        stockQueryWrapper.isNull("location_id"); // 使用isNull来表示LEFT JOIN
        int occupiedCount = tMiStockMapper.selectCount(stockQueryWrapper);
        // 构建前端所需的数据结构
        int total = 0;
        int free = 0;
        int occupied = 0;
        for (Map<String, Object> statusCount : statusCounts) {
            int count = ((Number) statusCount.get("count")).intValue();
            total += count;

            if ("0".equals(statusCount.get("status").toString())) {
                free = count;
            } else if ("1".equals(statusCount.get("status").toString())) {
                occupied = count;
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("free", free);
        result.put("occupied", occupied);
        result.put("occupiedCount", occupiedCount);
        return result;
    }




    /**
     * 这折线图统计
     *
     * @return
     */
    @Override
    public List<List<Object>> line() {
        //出库
        LambdaQueryWrapper<TCkPickingwavegoodsBak> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TCkPickingwavegoodsBak::getWareDate, LocalDate.now());
        List<TCkPickingwavegoodsBak> list = bakService.list(queryWrapper);

        int sum = list.stream()
                .map(TCkPickingwavegoodsBak::getGoodsNum)  // 假设字段为 decimalField
                .mapToInt(BigDecimal::intValue)                // 转换为 int 值
                .sum();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy'年'M'月'd'日'");

        String formattedDate = LocalDate.now().format(formatter);

        List<Object> header = Arrays.asList("product", formattedDate);


        LambdaQueryWrapper<TOngoodsshelfBak> eq = new LambdaQueryWrapper<>();
        eq.eq(TOngoodsshelfBak::getOndate, LocalDate.now());
        List<TOngoodsshelfBak> lists = ongoodsshelfBakService.list(eq);

        int sums = lists.stream()
                .map(TOngoodsshelfBak::getAccNum)  // 假设字段为 decimalField
                .mapToInt(BigDecimal::intValue)                // 转换为 int 值
                .sum();

        List<Object> outStock = Arrays.asList("出库", sum);  // 出库总数
        List<Object> inStock = Arrays.asList("入库", sums);  // 入库总数





        return Arrays.asList(header, outStock, inStock);
    }

    /**
     * 出库入库任务表格
     *
     * @return
     */

    @Override
    public List<Quest> quest() {
        List<Quest> result = new ArrayList<>();
        Map<String, String> statusMap = new HashMap<>();
        statusMap.put("0", "待执行");
        statusMap.put("1", "执行中");
        statusMap.put("2", "完成");
        // 出库任务
        List<TCkPickingwavegoods> pickingGoodsList = goodsService.list(new LambdaQueryWrapper<TCkPickingwavegoods>());
        for (TCkPickingwavegoods goods : pickingGoodsList) {
            result.add(createQuest(goods.getId(),goods.getGoodsId(), goods.getStorageId(),goods.getStorageShortName(), goods.getGoodsName(), "出库", goods.getLocationId(),goods.getCtl(),goods.getGoodsNum()));
        }
        // 入库任务
        List<TOngoodsshelf> onShelfGoodsList = ongoodsshelfService.list(new LambdaQueryWrapper<TOngoodsshelf>());
        for (TOngoodsshelf goods : onShelfGoodsList) {
            result.add(createQuest(goods.getId(),goods.getGoodsId(), goods.getStorageId(),goods.getStorageShortName(), goods.getGoodsName(),"入库",goods.getLocationId(),goods.getCtl(),goods.getAccNum()));
        }
        return result;
    }

    private Quest createQuest(String id,String goodsId, String storageId, String storageShortName,String goodsName, String type, String locationId, String ctl, BigDecimal goodsNum) {
        Quest quest = new Quest();
        quest.setId(id);
        quest.setGoodsId(goodsId);
        quest.setStorageId(storageId);
        quest.setStorageShortName(storageShortName);
        quest.setGoodsName(goodsName);
        quest.setType(type);
        quest.setLocationId(locationId);
        quest.setCtl(ctl);
        quest.setNum(goodsNum);
        return quest;
    }


    /**
     * 出入库任务数量统计
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> task() {
        List<Map<String, Object>> source = new ArrayList<>();
        // 出库任务
        source.add(goodsService.createTaskData("出库任务", Arrays.asList(0, 1, 2)));
        // 入库任务
        source.add(ongoodsshelfService.createTaskData("入库任务", Arrays.asList(0, 1, 2)));
        return source;
    }

    /**
     * 设备状态
     * @return
     */
    @Override
    public List<TAgv> equipmentStatu() {
        List<TAgv> tAgvs = tAgvMapper.selectList(new LambdaQueryWrapper<TAgv>());
        return tAgvs;
    }

    @Override
    public List<Map<String,Long>> police() {
        List<TErrorLog> tErrorLogs = tErrorLogMapper.selectList(new LambdaQueryWrapper<TErrorLog>());
        //根据状态分组

        //名称
        Map<String, Long> errorCountMap = tErrorLogs.stream()
                .collect(Collectors.groupingBy(TErrorLog::getErrName, Collectors.counting()));

        // 创建状态到标签的映射
        Map<String, String> statusToLabel = new HashMap<>();
        statusToLabel.put("1", "报警解决");
        statusToLabel.put("0", "正常报警");

        // 使用映射来转换状态
        Map<String, Long> collect = tErrorLogs.stream()
                .collect(Collectors.groupingBy(
                        log -> statusToLabel.getOrDefault(log.getSts(), "未知状态"), // 使用getOrDefault以处理未知状态
                        Collectors.counting()
                ));

        List<Map<String,Long>> list = new ArrayList<>();
        list.add(errorCountMap);
        list.add(collect);

        return list;
    }

    /**
     * 货值分布
     *
     * @return
     */
    public List<Map<String, Object>> distribution() {
        List<Map<String, Object>> list = mapper.selectTotalPriceBy();
        // 使用BigDecimal进行精确计算
        BigDecimal totalBigDecimal = list.stream()
                .map(map -> (BigDecimal) map.get("total_price")) // 确保这里的键与数据库查询中的别名匹配
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 使用reduce进行累加

        // 将BigDecimal转换为int
        int total = totalBigDecimal.intValueExact(); // 使用intValueExact确保没有精度丢失，如果有超出int范围的值，将抛出异常

        Map<String, Object> totalMap = new HashMap<>();
        totalMap.put("total", total); // 将总计数作为一个键值对存储

        list.add(0, totalMap); // 将总计数Map添加到列表的开始位置

        return list;


    }

    /**
     * 货值分布子项
     * @return
     */
    @Override
    public List<Map<String, Object>> child() {
        List<Map<String, Object>> list = mapper.selectChild();
        return list;
    }

    /**
     * 首页报警数据
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public Map<String, Integer> alarmData() {

        HashMap<String, Integer> map = new HashMap<>();

        //超期
        TMiStock stock = new TMiStock();
        stock.setFlag("1");
        List<TMiStock> overdue = miStockService.selectTMiStockLists(stock);


        //超保
        TMiStock tMiStock = new TMiStock();
        QueryWrapper<TMiStock> wrapper = new QueryWrapper<>(tMiStock);
        wrapper.isNotNull("mark");
        List<TMiStock> overProtected = miStockService.list(wrapper);


        //安全库存预警
        List<SafetyStockVO> security = itSafetyStockService.selectList(new SafetyStockVO());
        /*List<SafetyStockVO> filteredList = security.stream()
                .filter(s -> BigDecimal.valueOf(s.getShelvesNum()).compareTo(s.getWarnUp()) > 0 ||
                        BigDecimal.valueOf(s.getShelvesNum()).compareTo(s.getWarnDown()) < 0)
                .collect(Collectors.toList());*/

        map.put("overdue",overdue.size());
        map.put("overProtected",overProtected.size());
        map.put("security",security.size());

        return map;
    }


    // 示例的日期格式化方法
    private String formatDate(String date) {
        String[] parts = date.split("-");
        return parts[0].substring(2) + "年" + Integer.parseInt(parts[1]) + "月";
    }




}
