package cn.iocoder.yudao.module.pms.controller.admin.iotoutbound;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotoutbound.vo.IotOutboundPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotoutbound.vo.IotOutboundRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotoutbound.vo.IotOutboundSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotoutbound.IotOutboundDO;
import cn.iocoder.yudao.module.pms.service.iotoutbound.IotOutboundService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - PMS 出库")
@RestController
@RequestMapping("/pms/iot-outbound")
@Validated
public class IotOutboundController {

    @Resource
    private IotOutboundService iotOutboundService;

    @PostMapping("/create")
    @Operation(summary = "创建PMS 出库")
    @PreAuthorize("@ss.hasPermission('pms:iot-outbound:create')")
    public CommonResult<Long> createIotOutbound(@Valid @RequestBody IotOutboundSaveReqVO createReqVO) {
        return success(iotOutboundService.createIotOutbound(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新PMS 出库")
    @PreAuthorize("@ss.hasPermission('pms:iot-outbound:update')")
    public CommonResult<Boolean> updateIotOutbound(@Valid @RequestBody IotOutboundSaveReqVO updateReqVO) {
        iotOutboundService.updateIotOutbound(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除PMS 出库")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('pms:iot-outbound:delete')")
    public CommonResult<Boolean> deleteIotOutbound(@RequestParam("id") Long id) {
        iotOutboundService.deleteIotOutbound(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得PMS 出库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pms:iot-outbound:query')")
    public CommonResult<IotOutboundRespVO> getIotOutbound(@RequestParam("id") Long id) {
        IotOutboundDO iotOutbound = iotOutboundService.getIotOutbound(id);
        return success(BeanUtils.toBean(iotOutbound, IotOutboundRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得PMS 出库分页")
    @PreAuthorize("@ss.hasPermission('pms:iot-outbound:query')")
    public CommonResult<PageResult<IotOutboundRespVO>> getIotOutboundPage(@Valid IotOutboundPageReqVO pageReqVO) {
        PageResult<IotOutboundDO> pageResult = iotOutboundService.getIotOutboundPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, IotOutboundRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出PMS 出库 Excel")
    @PreAuthorize("@ss.hasPermission('pms:iot-outbound:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotOutboundExcel(@Valid IotOutboundPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotOutboundDO> list = iotOutboundService.getIotOutboundPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "PMS 出库.xls", "数据", IotOutboundRespVO.class,
                        BeanUtils.toBean(list, IotOutboundRespVO.class));
    }

    @GetMapping("/materials/top")
    @Operation(summary = "出库处理")
    @PreAuthorize("@ss.hasPermission('pms:iot-outbound:query')")
    public CommonResult<List<Map<String, Object>>> getIotOutboundMaterialTop() {
        LocalDate today = LocalDate.now();
        // 计算七天前的日期
        LocalDate sevenDaysAgo = today.minusDays(7);
        // 构建起始日期的LocalDateTime（当天的开始时间：00:00:00）
        LocalDateTime startDateTime = sevenDaysAgo.atStartOfDay();
        // 构建结束日期的LocalDateTime（今天的结束时间：23:59:59.999999999）
        LocalDateTime endDateTime = today.atTime(LocalTime.MAX);
        IotOutboundPageReqVO iotOutboundPageReqVO = new IotOutboundPageReqVO();
        LocalDateTime[] createTime = new LocalDateTime[]{startDateTime, endDateTime};
        iotOutboundPageReqVO.setCreateTime(createTime);
        iotOutboundPageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<IotOutboundDO> pageResult = iotOutboundService.getIotOutboundPage(iotOutboundPageReqVO);
        List<IotOutboundDO> list = pageResult.getList();
        List<IotOutboundDO> collect = list.stream().filter(e ->Objects.nonNull(e.getMaterialName())).collect(Collectors.toList());


        // 按name字段分组并计数
        Map<String, Long> countByName = collect.stream()
                .collect(Collectors.groupingBy(IotOutboundDO::getMaterialName, Collectors.counting()));

        // 转换为Entry列表并按计数排序
        List<Map.Entry<String, Long>> sortedEntries = new ArrayList<>(countByName.entrySet());
        sortedEntries.sort(Map.Entry.<String, Long>comparingByValue().reversed());

        // 获取前五个
        List<Map.Entry<String, Long>> topFive = sortedEntries.stream()
                .limit(5)
                .collect(Collectors.toList());
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, Long> stringLongEntry : topFive) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", stringLongEntry.getKey());
            map.put("value", stringLongEntry.getValue());
            result.add(map);
        }
        return success(result);
    }
}
