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

import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.PlanTypeEnum;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.vo.TicketManagementRespVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.dvsubject.DvSubjectDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.subjectplan.SubjectPlanDO;
import cn.iocoder.yudao.module.mes.service.subjectplan.SubjectPlanService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
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.planmaintenance.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.planmaintenance.PlanMaintenanceDO;
import cn.iocoder.yudao.module.mes.service.planmaintenance.PlanMaintenanceService;

@Tag(name = "管理后台 - 方案维护")
@RestController
@RequestMapping("/mes/plan-maintenance")
@Validated
public class PlanMaintenanceController {

    @Resource
    private PlanMaintenanceService planMaintenanceService;

    @Resource
    private SubjectPlanService subjectPlanService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建方案维护")
    @PreAuthorize("@ss.hasPermission('mes:plan-maintenance:create')")
    public CommonResult<Long> createPlanMaintenance(@Valid @RequestBody PlanMaintenanceSaveReqVO createReqVO) {
        return success(planMaintenanceService.createPlanMaintenance(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新方案维护")
    @PreAuthorize("@ss.hasPermission('mes:plan-maintenance:update')")
    public CommonResult<Boolean> updatePlanMaintenance(@Valid @RequestBody PlanMaintenanceSaveReqVO updateReqVO) {
        planMaintenanceService.updatePlanMaintenance(updateReqVO);
        return success(true);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得方案维护")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:plan-maintenance:query')")
    public CommonResult<PlanMaintenanceRespVO> getPlanMaintenance(@RequestParam("id") Long id) {
        PlanMaintenanceDO planMaintenance = planMaintenanceService.getPlanMaintenance(id);
        return success(BeanUtils.toBean(planMaintenance, PlanMaintenanceRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得方案维护分页")
    @PreAuthorize("@ss.hasPermission('mes:plan-maintenance:query')")
    public CommonResult<PageResult<PlanMaintenanceRespVO>> getPlanMaintenancePage(@Valid PlanMaintenancePageReqVO pageReqVO) {
        PageResult<PlanMaintenanceDO> pageResult = planMaintenanceService.getPlanMaintenancePage(pageReqVO);
        PageResult<PlanMaintenanceRespVO> planMaintenanceRespVOPageResult = BeanUtils.toBean(pageResult, PlanMaintenanceRespVO.class);

        return success(buildPageCreatorName(planMaintenanceRespVOPageResult));
    }

    @GetMapping("/list")
    @Operation(summary = "获得方案维护列表")
    @PreAuthorize("@ss.hasPermission('mes:plan-maintenance:query')")
    public CommonResult<List<PlanMaintenanceDO>> getPlanMaintenanceList() {
        List<PlanMaintenanceDO> planMaintenanceList = planMaintenanceService.getPlanMaintenanceList();
        return success(planMaintenanceList);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出方案维护 Excel")
    @PreAuthorize("@ss.hasPermission('mes:plan-maintenance:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportPlanMaintenanceExcel(@Valid PlanMaintenancePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PlanMaintenanceDO> list = planMaintenanceService.getPlanMaintenancePage(pageReqVO).getList();

        List<PlanMaintenanceRespVO> planMaintenanceRespVOS = BeanUtils.toBean(list, PlanMaintenanceRespVO.class);
        for (PlanMaintenanceRespVO planMaintenanceRespVO : planMaintenanceRespVOS) {
            if(planMaintenanceRespVO.getCreator()!=null){
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(planMaintenanceRespVO.getCreator()));
                planMaintenanceRespVO.setCreatorName( "(" + user.getUsername()+ ")" + user.getNickname());
            }
            if (planMaintenanceRespVO.getPlanType()!=null){
                String planName = PlanTypeEnum.getDescriptionByCode(planMaintenanceRespVO.getPlanType());
                planMaintenanceRespVO.setPlanName(planName);
            }
        }

        // 导出 Excel
        ExcelUtils.write(response, "方案维护.xls", "数据", PlanMaintenanceRespVO.class,planMaintenanceRespVOS);
    }


    @GetMapping("/getSubjectList")
    @Operation(summary = "查询项目集合列表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:plan-maintenance:query')")
    public CommonResult<List<DvSubjectDO>> getSubjectList(@RequestParam("id") Long id) {
        List<DvSubjectDO> subjectPlanDOList = planMaintenanceService.getSubjectList(id);
        return success(subjectPlanDOList);
    }


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

}