package cn.iocoder.yudao.module.mes.controller.admin.app;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductUnitDO;
import cn.iocoder.yudao.module.erp.framework.bean.ProductTypeEnum;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import cn.iocoder.yudao.module.erp.service.product.ErpProductUnitService;
import cn.iocoder.yudao.module.mes.controller.admin.app.service.AppService;
import cn.iocoder.yudao.module.mes.controller.admin.app.vo.AppProductVo;
import cn.iocoder.yudao.module.mes.controller.admin.app.vo.ProduceReportTimeVO;
import cn.iocoder.yudao.module.mes.controller.admin.producereport.vo.ProduceReportPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.producereport.vo.ReportStatusEnum;
import cn.iocoder.yudao.module.mes.dal.dataobject.producereport.ProduceReportDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.producereport.ViewReportUserDateSummary;
import cn.iocoder.yudao.module.mes.service.producereport.ProduceReportService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
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.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

@Tag(name = "app - 工位安排")
@RestController
@RequestMapping("/mes/app/product")
@Validated
public class AppProductController {


    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private AppService appService;
    @Resource
    private ErpProductService erpProductService;
    @Resource
    private ErpProductUnitService erpProductUnitService;
    @Resource
    private ProduceReportService produceReportService;

    @GetMapping("/getItemList")
    @Operation(summary = "获得原料列表")
    public CommonResult<List<AppProductVo>> getItemList() {
        List<ErpProductRespVO> list = erpProductService.getProductVOListByCategory(ProductTypeEnum.ITEM.getTypeId());
        return success(convertList(list, item -> new AppProductVo().setValue(item.getId()).setText(item.getName())));
    }
    @GetMapping("/getUnitList")
    @Operation(summary = "获得单位列表")
    public CommonResult<List<AppProductVo>> getUnitList() {
        List<ErpProductUnitDO> list = erpProductUnitService.getProductUnitListByStatus(CommonStatusEnum.ENABLE.getStatus());
        return success(convertList(list, unit -> new AppProductVo().setValue(unit.getId()).setText(unit.getName())));
    }

    @GetMapping("/get30DaysReportList")
    @Operation(summary = "获得某用户近三十天报工汇总")
    public CommonResult<List<ViewReportUserDateSummary>> get30DaysReportList(@RequestParam("userId") Long userId) {
        if(userId==null) return success(new ArrayList<>());
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime day30 = now.plusDays(-30);

        String[] days = {LocalDateTimeUtil.format(day30,DatePattern.NORM_DATE_PATTERN),
                LocalDateTimeUtil.format(now,DatePattern.NORM_DATE_PATTERN)};
        List<ViewReportUserDateSummary> list = produceReportService.selectBy(userId,null,days);
        return success(list);
    }
    @GetMapping("/getThisMonthSum")
    @Operation(summary = "获得某用户本月报工汇总")
    public CommonResult<ViewReportUserDateSummary> getThisMonthSum(@RequestParam("userId") Long userId) {
        ViewReportUserDateSummary result = new ViewReportUserDateSummary().setUserId(userId)
                .setSumNumber(BigDecimal.ZERO).setTotalQualityNumber(BigDecimal.ZERO).setTotalWasteNumber(BigDecimal.ZERO);
        if(userId==null)  return success(result);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime firstDay = now.with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天

        String[] days = {LocalDateTimeUtil.format(firstDay,DatePattern.NORM_DATE_PATTERN),
                LocalDateTimeUtil.format(now,DatePattern.NORM_DATE_PATTERN)};

        result = produceReportService.selectSumBy(userId,days);
        return success(result);
    }
    @GetMapping("/getLastMonthSum")
    @Operation(summary = "获得某用户上个月的报工汇总")
    public CommonResult<ViewReportUserDateSummary> getLastMonthSum(@RequestParam("userId") Long userId) {
        ViewReportUserDateSummary result = new ViewReportUserDateSummary().setUserId(userId)
                .setSumNumber(BigDecimal.ZERO).setTotalQualityNumber(BigDecimal.ZERO).setTotalWasteNumber(BigDecimal.ZERO);
        if(userId==null)  return success(result);
        LocalDateTime lastMonth = LocalDateTime.now().plusMonths(-1);
        LocalDateTime firstDay = lastMonth.with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天
        LocalDateTime lastDay = lastMonth.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天

        String[] days = {LocalDateTimeUtil.format(firstDay,DatePattern.NORM_DATE_PATTERN),
                LocalDateTimeUtil.format(lastDay,DatePattern.NORM_DATE_PATTERN)};

        result = produceReportService.selectSumBy(userId,days);
        return success(result);
    }

    @GetMapping("/getSumReportTime")
    @Operation(summary = "获得某用户本月和上个月的计时汇总")
    public CommonResult<ViewReportUserDateSummary> getSumReportTime(@RequestParam("userId") Long userId) {
        ViewReportUserDateSummary result = new ViewReportUserDateSummary().setUserId(userId)
                .setSumNumber(BigDecimal.ZERO).setTotalQualityNumber(BigDecimal.ZERO).setTotalWasteNumber(BigDecimal.ZERO);
        if(userId==null)  return success(result);
        LocalDateTime lastMonth = LocalDateTime.now().plusMonths(-1);
        LocalDateTime firstDay = lastMonth.with(TemporalAdjusters.firstDayOfMonth()); // 获取前月的第一天
        LocalDateTime lastDay = lastMonth.with(TemporalAdjusters.lastDayOfMonth()); // 获取前月的最后一天
        LocalDateTime[] days = {firstDay,lastDay};

        ProduceReportPageReqVO pageReqVO = new ProduceReportPageReqVO().setUserId(userId)
                .setReportStatus(ReportStatusEnum.通过.getValue());
        pageReqVO.setReportDate(days);
        List<ProduceReportDO> list = produceReportService.getList(pageReqVO);
        BigDecimal lastMonthTime = list.stream()
                .map(ProduceReportDO::getTotalTime).reduce(BigDecimal.ZERO, BigDecimal::add);


        firstDay = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()); // 获取当前月的第一天
        firstDay = firstDay.withHour(0);
        LocalDateTime[] days2 = {firstDay,LocalDateTime.now()};

        pageReqVO.setReportDate(days2);
        list = produceReportService.getList(pageReqVO);
        BigDecimal thisMonthTime = list.stream()
                .map(ProduceReportDO::getTotalTime).reduce(BigDecimal.ZERO, BigDecimal::add);

        ViewReportUserDateSummary summary = new ViewReportUserDateSummary().setUserId(userId)
                .setSumNumber(BigDecimal.ZERO).setTotalQualityNumber(thisMonthTime).setTotalWasteNumber(lastMonthTime);
        return success(summary);
    }
    @GetMapping("/getDay30ReportTime")
    @Operation(summary = "获得某用户30天的计时列表")
    public CommonResult<List<ProduceReportTimeVO>> getDay30ReportTime(@RequestParam("userId") Long userId) {
        if(userId==null)  return success(new ArrayList<>());
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime day30 = now.plusDays(-30);
        LocalDateTime[] days = {day30,now};
        ProduceReportPageReqVO pageReqVO = new ProduceReportPageReqVO().setUserId(userId)
                .setReportStatus(ReportStatusEnum.通过.getValue());;
        pageReqVO.setReportDate(days);
        List<ProduceReportDO> list = produceReportService.getList(pageReqVO);
        List<ProduceReportTimeVO> timeList = new ArrayList<>();
        for (ProduceReportDO reportDO: list) {
            if(reportDO.getTotalTime().compareTo(BigDecimal.ZERO)==1){
                ProduceReportTimeVO timeVO = new ProduceReportTimeVO();
                timeVO.setUserId(userId);
                timeVO.setReportDay(LocalDateTimeUtil.format(reportDO.getReportDate(),DatePattern.NORM_DATE_PATTERN));
                timeVO.setReportTime(reportDO.getTotalTime());
                timeList.add(timeVO);
            }
        }
        return success(timeList);
    }
}