package org.jeecg.modules.material.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.material.entity.BuMaterialStock;
import org.jeecg.modules.material.entity.BuMaterialUsage;
import org.jeecg.modules.material.entity.BuMaterialUsageBo;
import org.jeecg.modules.material.entity.BuMaterialUsageStatistic;
import org.jeecg.modules.material.service.IBuMaterialUsageService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags="物料消耗统计")
@RestController
@RequestMapping("/material/buMaterialUsage")
@Slf4j
@AllArgsConstructor
public class BuMaterialUsageController {
    private final IBuMaterialUsageService materialUsageService;
    @ApiOperation(value="物料消耗统计-分页列表查询", notes="物料消耗统计-分页列表查询")
    @GetMapping(value = "/statistics")
    public Result<IPage<BuMaterialUsageStatistic>> queryPageList(BuMaterialUsageBo buMaterialUsageBo,
                                                                 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                                 HttpServletRequest req) {
        LambdaQueryWrapper<BuMaterialUsage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(buMaterialUsageBo.getMaterialId()), BuMaterialUsage::getMaterialId, buMaterialUsageBo.getMaterialId());
        queryWrapper.between(buMaterialUsageBo.getUsageTimeBegin()!=null && buMaterialUsageBo.getUsageTimeEnd()!=null, BuMaterialUsage::getAlterTime, buMaterialUsageBo.getUsageTimeBegin(), buMaterialUsageBo.getUsageTimeEnd());
        List<BuMaterialUsage> data = materialUsageService.list(queryWrapper);
        List<BuMaterialUsageStatistic> statisticsData = new ArrayList<>();
        Map<String, List<BuMaterialUsage>> groupedByCategory = data.stream()
                .collect(Collectors.groupingBy(BuMaterialUsage::getMaterialId));
        groupedByCategory.forEach((mat, matData) -> {
            if(!matData.isEmpty()){
                BuMaterialUsageStatistic statistic = new BuMaterialUsageStatistic();
                statistic.setMaterialId(mat);
                BuMaterialUsage usage = matData.get(0);
                statistic.setUnit(usage.getUnit());
                statistic.setMaterialName(usage.getMaterialName());
                statistic.setSpecification(usage.getSpecifaction());
                statistic.setUsageCount(matData.size());
                Optional<Date> maxDate = matData.stream()
                        .map(BuMaterialUsage::getAlterTime)
                        .max(Date::compareTo);
                maxDate.ifPresent(statistic::setLastUsageTime);
                statistic.setTotalQuantity(matData.stream().mapToDouble(BuMaterialUsage::getQuantity).sum());
                statisticsData.add(statistic);
            }
        });
        IPage<BuMaterialUsageStatistic> pageList = new Page<>();
        pageList.setSize(pageSize);
        pageList.setCurrent(pageNo);
        pageList.setPages((int) Math.ceil((double) statisticsData.size() / pageSize));
        // 校正页码
        pageNo = Math.toIntExact(Math.min(pageNo, pageList.getPages()));
        //分页查询
        pageList.setRecords(statisticsData.stream().skip((long) pageNo * pageSize).limit(pageSize).toList());
        return Result.OK(pageList);
    }
}
