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

import cn.iocoder.yudao.module.mes.controller.admin.planmaintenance.vo.PlanMaintenanceRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.PlanTypeEnum;
import cn.iocoder.yudao.module.mes.dal.dataobject.planmaintenance.PlanMaintenanceDO;
import cn.iocoder.yudao.module.mes.service.planmaintenance.PlanMaintenanceService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import jodd.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.mes.controller.admin.taskmanagement.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.taskmanagement.TaskManagementDO;
import cn.iocoder.yudao.module.mes.service.taskmanagement.TaskManagementService;

@Tag(name = "管理后台 - 任务管理")
@RestController
@RequestMapping("/mes/task-management")
@Validated
public class TaskManagementController {

    @Resource
    private TaskManagementService taskManagementService;
    @Resource
    private PlanMaintenanceService planMaintenanceService;
    @Resource
    private AdminUserApi adminUserApi;


    @PostMapping("/create")
    @Operation(summary = "创建任务管理")
    @PreAuthorize("@ss.hasPermission('mes:task-management:create')")
    public CommonResult<Long> createTaskManagement(@Valid @RequestBody TaskManagementSaveReqVO createReqVO) {
        return success(taskManagementService.createTaskManagement(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新任务管理")
    @PreAuthorize("@ss.hasPermission('mes:task-management:update')")
    public CommonResult<Boolean> updateTaskManagement(@Valid @RequestBody TaskManagementSaveReqVO updateReqVO) {
        taskManagementService.updateTaskManagement(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除任务管理")
    @Parameter(name = "ids", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:task-management:delete')")
    public CommonResult<Boolean> deleteTaskManagement(@RequestParam("ids") String ids) {
        // 将逗号分隔的字符串转换为Long类型的List
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim) // 去除可能存在的空格
                .map(Long::valueOf)
                .collect(Collectors.toList());
        taskManagementService.deleteTaskManagement(idList);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得任务管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:task-management:query')")
    public CommonResult<TaskManagementRespVO> getTaskManagement(@RequestParam("id") Long id) {
        TaskManagementDO taskManagement = taskManagementService.getTaskManagement(id);
        return success(BeanUtils.toBean(taskManagement, TaskManagementRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得任务管理分页")
    @PreAuthorize("@ss.hasPermission('mes:task-management:query')")
    public CommonResult<PageResult<TaskManagementRespVO>> getTaskManagementPage(@Valid TaskManagementPageReqVO pageReqVO) {
        PageResult<TaskManagementDO> pageResult = taskManagementService.getTaskManagementPage(pageReqVO);

        PageResult<TaskManagementRespVO> taskManagementRespVOPageResult = BeanUtils.toBean(pageResult, TaskManagementRespVO.class);
        buildPageCreatorName(taskManagementRespVOPageResult);
        return success(taskManagementRespVOPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出任务管理 Excel")
    @PreAuthorize("@ss.hasPermission('mes:task-management:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTaskManagementExcel(@Valid TaskManagementPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TaskManagementDO> list = taskManagementService.getTaskManagementPage(pageReqVO).getList();
        List<TaskManagementRespVO> taskManagementRespVOList = BeanUtils.toBean(list, TaskManagementRespVO.class);

        for (TaskManagementRespVO planMaintenanceRespVO : taskManagementRespVOList) {
            if (planMaintenanceRespVO.getCreator()!=null){
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(planMaintenanceRespVO.getCreator()));
                planMaintenanceRespVO.setCreatorName( "(" + user.getUsername()+ ")" + user.getNickname());
            }
            if (planMaintenanceRespVO.getProjectForm()!=null){
                PlanMaintenanceDO planMaintenance = planMaintenanceService.getPlanMaintenance(planMaintenanceRespVO.getProjectForm());
                planMaintenanceRespVO.setProjectFormName(planMaintenance.getPlanName());
            }

            if (planMaintenanceRespVO.getTaskType()!=null){
                String planName = PlanTypeEnum.getDescriptionByCode(planMaintenanceRespVO.getTaskType());
                planMaintenanceRespVO.setTypeName(planName);
            }

            //操作人
//            if (StringUtils.isNotBlank(planMaintenanceRespVO.getOperableUsers())){
//                List<Long> idList = Arrays.stream(planMaintenanceRespVO.getOperableUsers().split(","))
//                        .map(String::trim)
//                        .map(Long::valueOf)
//                        .collect(Collectors.toList());
//
//                StringBuilder userInfoBuilder = new StringBuilder();
//                for (int i = 0; i < idList.size(); i++) {
//                    Long id = idList.get(i);
//                    AdminUserRespDTO user = adminUserApi.getUser(id);
//                    if (user != null) {
//                        // 格式：(用户名)昵称
//                        userInfoBuilder.append("(")
//                                .append(user.getUsername())
//                                .append(")")
//                                .append(user.getNickname());
//
//                        // 如果不是最后一个，添加分隔符
//                        if (i < idList.size() - 1) {
//                            userInfoBuilder.append(", ");
//                        }
//                    }
//                }
//
//                if (userInfoBuilder.length() > 0) {
//                    planMaintenanceRespVO.setCreatorName(userInfoBuilder.toString());
//                }
//            }


        }
        // 导出 Excel
        ExcelUtils.write(response, "设备类型.xls", "数据", TaskManagementRespVO.class,taskManagementRespVOList);
    }


    @PostMapping("/createTicket")
    @Operation(summary = "创建工单管理")
    @PreAuthorize("@ss.hasPermission('mes:task-management:create')")
    public CommonResult<Boolean> createTicket(@RequestParam("id") Long id) {
        taskManagementService.createTicket(id);
        return success(true);
    }

    @PutMapping("/update-enabled")
    @Operation(summary = "更新任务管理启用状态")
    @PreAuthorize("@ss.hasPermission('mes:task-management:update')")
    public CommonResult<Boolean> updateTaskManagementEnabled(@Valid @RequestBody TaskManagementUpdateEnabledReqVO updateEnabledReqVO) {
        taskManagementService.updateTaskManagementEnabled(updateEnabledReqVO);
        return success(true);
    }



    private PageResult<TaskManagementRespVO> buildPageCreatorName(PageResult<TaskManagementRespVO> planMaintenanceRespVOPageResult) {
        for (TaskManagementRespVO planMaintenanceRespVO : planMaintenanceRespVOPageResult.getList()) {
            if (planMaintenanceRespVO.getCreator()!=null){
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(planMaintenanceRespVO.getCreator()));
                if (user!=null){
                    planMaintenanceRespVO.setCreatorName( "(" + user.getUsername()+ ")" + user.getNickname());
                }
            }
        }
        return planMaintenanceRespVOPageResult;
    }

}