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

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.mes.controller.admin.producereport.vo.ProduceReportDetailRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.producereport.vo.ProduceReportPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.producereport.vo.ProduceReportRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.producereport.vo.ProduceReportSaveReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.producereport.ProduceReportDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.workteam.WorkTeamDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.workteam.WorkTeamDetailDO;
import cn.iocoder.yudao.module.mes.service.producereport.ProduceReportService;
import cn.iocoder.yudao.module.mes.service.workteam.WorkTeamService;
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.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.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
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;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 生产报工单")
@RestController
@RequestMapping("/mes/produce-report")
@Validated
public class ProduceReportController {

    @Resource
    private ProduceReportService produceReportService;

    @PostMapping("/create")
    @Operation(summary = "创建生产报工单")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:create')")
    public CommonResult<Long> createProduceReport(@Valid @RequestBody ProduceReportSaveReqVO createReqVO) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(createReqVO.getReportDateString(), formatter);
        createReqVO.setReportDate(localDateTime);
        return success(produceReportService.createProduceReport(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产报工单")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:update')")
    public CommonResult<Boolean> updateProduceReport(@Valid @RequestBody ProduceReportSaveReqVO updateReqVO) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(updateReqVO.getReportDateString(), formatter);
        updateReqVO.setReportDate(localDateTime);
        produceReportService.updateProduceReport(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产报工单")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:delete')")
    public CommonResult<Boolean> deleteProduceReport(@RequestParam("id") Long id) {
        produceReportService.deleteProduceReport(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产报工单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:query')")
    public CommonResult<ProduceReportRespVO> getProduceReport(@RequestParam("id") Long id) {
        ProduceReportDO produceReport = produceReportService.getProduceReport(id);
        return success(BeanUtils.toBean(produceReport, ProduceReportRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产报工单分页")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:query')")
    public CommonResult<PageResult<ProduceReportRespVO>> getProduceReportPage(@Valid ProduceReportPageReqVO pageReqVO) {

        PageResult<ProduceReportDO> pageResult = produceReportService.getProduceReportPage(pageReqVO);
        return success(new PageResult<>(produceReportService.buildVOList(pageResult.getList()),pageResult.getTotal()));
    }
    @GetMapping("/pageDailyReport")
    @Operation(summary = "获得生产报工单分页")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:query')")
    public CommonResult<PageResult<ProduceReportRespVO>> getPageDailyReport(@Valid ProduceReportPageReqVO pageReqVO) {

        PageResult<ProduceReportDO> pageResult = produceReportService.getProduceReportPage(pageReqVO);
        return success(new PageResult<>(produceReportService.buildVOList(pageResult.getList()),pageResult.getTotal()));
    }
    @Resource
    private WorkTeamService workTeamService;

    @GetMapping("/pageReplace")
    @Operation(summary = "获得生产报工单分页-代报工")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:query')")
    public CommonResult<PageResult<ProduceReportRespVO>> getProduceReportPageReplace(@Valid ProduceReportPageReqVO pageReqVO) {
        Long userId =  getLoginUserId();
        WorkTeamDO workTeamDO = new WorkTeamDO().setTeamLeaderId(userId);
        List<WorkTeamDO> listTeam = workTeamService.selectBy(workTeamDO);
        if(listTeam!=null && listTeam.size()>0){
            List<Long> idList = listTeam.stream()
                    .map(WorkTeamDO::getId)
                    .collect(Collectors.toList());
            List<WorkTeamDetailDO> detailDOList = workTeamService.getDetailByWorkTeamIds(idList);
            List<Long> userList = detailDOList.stream()
                    .map(WorkTeamDetailDO::getUserId)
                    .collect(Collectors.toList());
            pageReqVO.setUserIds(userList);
        }
        PageResult<ProduceReportDO> pageResult = produceReportService.getProduceReportPage(pageReqVO);
        return success(new PageResult<>(produceReportService.buildVOList(pageResult.getList()),pageResult.getTotal()));
    }
    @GetMapping("/export-excel")
    @Operation(summary = "导出生产报工单 Excel")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProduceReportExcel(@Valid ProduceReportPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ProduceReportDO> list = produceReportService.getProduceReportPage(pageReqVO).getList();
        List<ProduceReportRespVO> list2 = produceReportService.buildVOList(list);
        // 导出 Excel
        ExcelUtils.write(response, "生产计时报表.xls", "数据", ProduceReportRespVO.class,
                        list2);
    }

    // ==================== 子表（生产报工明细） ====================\

    @GetMapping("/produce-report-detail/list-by-report-id")
    @Operation(summary = "获得生产报工明细列表")
    @Parameter(name = "reportId", description = "报工单id")
    //@PreAuthorize("@ss.hasPermission('mes:produce-report:query')")
    public CommonResult<List<ProduceReportDetailRespVO>> getProduceReportDetailListByReportId(@RequestParam("reportId") Long reportId) {
        return success(produceReportService.getDetailListByReportId(reportId));
    }
    @GetMapping("/updateStatus")
    @Operation(summary = "提交报工单")
    public CommonResult<Boolean> updateStatus(@RequestParam("id") Long id,
                                              @RequestParam("status") Integer status) {
        produceReportService.updateStatus(id,status);
        return success(true);
    }

    //获取个人30天内生产报工单，以时间排序
    @GetMapping("/getMyList")
    @Operation(summary = "获得生产报工单")
    public CommonResult<List<ProduceReportRespVO>> getMyList() {
        Long userId =  getLoginUserId();
        ProduceReportPageReqVO pageReqVO = new ProduceReportPageReqVO();
        pageReqVO.setUserId(userId);
        LocalDateTime[] dateTimes= {LocalDateTime.now().plusDays(-10),LocalDateTime.now()};
        pageReqVO.setReportDate(dateTimes);
        List<ProduceReportDO> reportDOList = produceReportService.getList(pageReqVO);
        return success(produceReportService.buildVOList(reportDOList));
    }
    @GetMapping("/getOtherList")
    @Operation(summary = "获得生产报工单")
    public CommonResult<List<ProduceReportRespVO>> getOtherList(ProduceReportPageReqVO pageReqVO) {
        if(pageReqVO.getReportDate()==null || pageReqVO.getReportDate().length==0){
            LocalDateTime[] dateTimes= {LocalDateTime.now().plusDays(-1),LocalDateTime.now()};
            pageReqVO.setReportDate(dateTimes);
        }
        List<ProduceReportDO> reportDOList = produceReportService.getList(pageReqVO);
        return success(produceReportService.buildVOList(reportDOList));
    }
}