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

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.task.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.task.TaskDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.task.TaskDetailDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.task.ViewTaskProductSummary;
import cn.iocoder.yudao.module.mes.service.task.TaskService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
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.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

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

@Tag(name = "管理后台 - 生产任务单")
@RestController
@RequestMapping("/mes/task")
@Validated
public class TaskController {

    @Resource
    private TaskService taskService;

    @PostMapping("/create")
    @Operation(summary = "创建生产任务单")
    @PreAuthorize("@ss.hasPermission('mes:task:create')")
    public CommonResult<Long> createTask(@Valid @RequestBody TaskSaveReqVO createReqVO) {
        return success(taskService.createTask(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产任务单")
    @PreAuthorize("@ss.hasPermission('mes:task:update')")
    public CommonResult<Boolean> updateTask(@Valid @RequestBody TaskSaveReqVO updateReqVO) {
        taskService.updateTask(updateReqVO);
        return success(true);
    }
    @GetMapping("/changeStatus")
    @Operation(summary = "更改任务单状态")
    public CommonResult<Boolean> changeStatus(@RequestParam("id") Long id, @RequestParam("status") Integer status) {
        TaskDO task = taskService.getTask(id);
        task.setStatus(status);
        if(status.equals(TaskStatusEnum.下达.getValue()))
            task.setOrderDate(LocalDateTime.now());
        int result = taskService.updateTask(task);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产任务单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:task:delete')")
    public CommonResult<Boolean> deleteTask(@RequestParam("id") Long id) {
        taskService.deleteTask(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产任务单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:task:query')")
    public CommonResult<TaskRespVO> getTask(@RequestParam("id") Long id) {
        TaskDO task = taskService.getTask(id);
        return success(BeanUtils.toBean(task, TaskRespVO.class));
    }

    @GetMapping("/getTaskList")
    @Operation(summary = "获得可查询计划的生产任务单列表")
    public CommonResult<List<TaskDO>> getTaskList() {
        List<TaskDO> taskDOList = taskService.selectList(TaskStatusEnum.getEnablePlanStatus());
        return success(taskDOList);
    }

    @GetMapping("/getPlanTaskList")
    @Operation(summary = "获得可做计划的生产任务单列表")
    public CommonResult<List<TaskDO>> getPlanTaskList() {
        List<Integer> statusList = new ArrayList<>();
        statusList.add(TaskStatusEnum.下达.getValue());
        statusList.add(TaskStatusEnum.已排产.getValue());
        statusList.add(TaskStatusEnum.开工.getValue());
        List<TaskDO> taskDOList = taskService.selectList(statusList);

        return success(taskDOList);
    }

    @GetMapping("/pagePlanTask")
    @Operation(summary = "获得可安排计划的任务单分页")
    @PreAuthorize("@ss.hasPermission('mes:task:query')")
    public CommonResult<PageResult<TaskRespVO>> pagePlanTask(@Valid TaskPageReqVO pageReqVO) {
        PageResult<TaskDO> pageResult = taskService.getTaskPage2(pageReqVO);
        return success(BeanUtils.toBean(pageResult, TaskRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产任务单分页")
    @PreAuthorize("@ss.hasPermission('mes:task:query')")
    public CommonResult<PageResult<TaskRespVO>> getTaskPage(@Valid TaskPageReqVO pageReqVO) {
        PageResult<TaskDO> pageResult = taskService.getTaskPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, TaskRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出生产任务单 Excel")
    @PreAuthorize("@ss.hasPermission('mes:task:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTaskExcel(@Valid TaskPageReqVO pageReqVO,
                                HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TaskDO> list = taskService.getTaskPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "生产任务单.xls", "数据", TaskRespVO.class,
                BeanUtils.toBean(list, TaskRespVO.class));
    }

    // ==================== 子表（生产任务单明细） ====================

    @GetMapping("/task-detail/list-by-task-id")
    @Operation(summary = "获得生产任务单明细列表")
    @Parameter(name = "taskId", description = "task ID")
    @PreAuthorize("@ss.hasPermission('mes:task:query')")
    public CommonResult<List<TaskDetailRespVO>> getTaskDetailListByTaskId(@RequestParam("taskId") Long taskId) {
        return success(taskService.buildDetailVOList(taskService.getTaskDetailListByTaskId(taskId)));
    }
    // ==================== 子表（生产任务单明细） ====================

    @GetMapping("/task-detail/page")
    @Operation(summary = "获得生产任务单明细分页")
    @Parameter(name = "taskId", description = "task ID")
    @PreAuthorize("@ss.hasPermission('mes:task:query')")
    public CommonResult<PageResult<TaskDetailRespVO>> getTaskDetailPage(PageParam pageReqVO,
                                                                        @RequestParam("taskId") Long taskId) {
        return success(taskService.getTaskDetailPage(pageReqVO, taskId));
    }

    @PostMapping("/task-detail/create")
    @Operation(summary = "创建生产任务单明细")
    @PreAuthorize("@ss.hasPermission('mes:task:create')")
    public CommonResult<Long> createTaskDetail(@Valid @RequestBody TaskDetailDO taskDetail) {
        return success(taskService.createTaskDetail(taskDetail));
    }

    @PutMapping("/task-detail/update")
    @Operation(summary = "更新生产任务单明细")
    @PreAuthorize("@ss.hasPermission('mes:task:update')")
    public CommonResult<Boolean> updateTaskDetail(@Valid @RequestBody TaskDetailDO taskDetail) {
        taskService.updateTaskDetail(taskDetail);
        return success(true);
    }

    @DeleteMapping("/task-detail/delete")
    @Parameter(name = "id", description = "编号", required = true)
    @Operation(summary = "删除生产任务单明细")
    @PreAuthorize("@ss.hasPermission('mes:task:delete')")
    public CommonResult<Boolean> deleteTaskDetail(@RequestParam("id") Long id) {
        taskService.deleteTaskDetail(id);
        return success(true);
    }

    @GetMapping("/task-detail/get")
    @Operation(summary = "获得生产任务单明细")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:task:query')")
    public CommonResult<TaskDetailDO> getTaskDetail(@RequestParam("id") Long id) {
        return success(taskService.getTaskDetail(id));
    }

    @GetMapping("/task-detail/summary")
    @Operation(summary = "获得生产任务单汇总明细")
    @Parameter(name = "taskId", description = "task ID")
    @PreAuthorize("@ss.hasPermission('mes:task:query')")
        public CommonResult<List<ViewTaskProductSummary>> getTaskDetailSummary(@RequestParam("taskId") Long taskId) {
        return success(taskService.getTaskProductSummaryList(taskId));
    }
}