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

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.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
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.criticalcomponent.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.criticalcomponent.CriticalComponentDO;
import cn.iocoder.yudao.module.mes.service.criticalcomponent.CriticalComponentService;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.Parameter;

@Tag(name = "管理后台 - 设备关键件")
@RestController
@RequestMapping("/mes/critical-component")
@Validated
public class CriticalComponentController {

    @Resource
    private CriticalComponentService criticalComponentService;

    @PostMapping("/create")
    @Operation(summary = "创建设备关键件")
    @PreAuthorize("@ss.hasPermission('mes:critical-component:create')")
    public CommonResult<Long> createCriticalComponent(@Valid @RequestBody CriticalComponentSaveReqVO createReqVO) {
        return success(criticalComponentService.createCriticalComponent(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备关键件")
    @PreAuthorize("@ss.hasPermission('mes:critical-component:update')")
    public CommonResult<Boolean> updateCriticalComponent(@Valid @RequestBody CriticalComponentSaveReqVO updateReqVO) {
        criticalComponentService.updateCriticalComponent(updateReqVO);
        return success(true);
    }

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

    @GetMapping("/get")
    @Operation(summary = "获得设备关键件")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:critical-component:query')")
    public CommonResult<CriticalComponentRespVO> getCriticalComponent(@RequestParam("id") Long id) {
        CriticalComponentDO criticalComponent = criticalComponentService.getCriticalComponent(id);
        return success(BeanUtils.toBean(criticalComponent, CriticalComponentRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备关键件分页")
    @PreAuthorize("@ss.hasPermission('mes:critical-component:query')")
    public CommonResult<PageResult<CriticalComponentRespVO>> getCriticalComponentPage(@Valid CriticalComponentPageReqVO pageReqVO) {
        PageResult<CriticalComponentDO> pageResult = criticalComponentService.getCriticalComponentPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, CriticalComponentRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得设备关键件列表")
    @PreAuthorize("@ss.hasPermission('mes:critical-component:query')")
    public CommonResult<List<CriticalComponentDO>> getCriticalComponentList() {
        List<CriticalComponentDO> criticalComponentList= criticalComponentService.getCriticalComponentList();
        return success(criticalComponentList);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备关键件 Excel")
    @PreAuthorize("@ss.hasPermission('mes:critical-component:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportCriticalComponentExcel(@Valid CriticalComponentPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CriticalComponentDO> list = criticalComponentService.getCriticalComponentPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备关键件.xls", "数据", CriticalComponentRespVO.class,
                        BeanUtils.toBean(list, CriticalComponentRespVO.class));
    }

    @GetMapping("/export-device-component")
    @Operation(summary = "根据设备Id导出设备关键件 Excel")
    @PreAuthorize("@ss.hasPermission('mes:critical-component:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceComponent(@RequestParam(name = "id") Long id,
                                             HttpServletResponse response) throws IOException {

        List<CriticalComponentExcelVO> list = criticalComponentService.exportDeviceComponent(id);

        // 设置响应头
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("设备关键件.xls", "UTF-8"));
        response.setHeader("Content-Encoding", "identity");
        String fileName = String.format("设备关键件_%s.xls", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        // 导出 Excel
        ExcelUtils.write(response, fileName, "数据", CriticalComponentExcelVO.class,list);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获取设备关键件导入模板")
    @PreAuthorize("@ss.hasPermission('mes:critical-component:import')")
    @ApiAccessLog(operateType = EXPORT)
    public void getImportTemplate(HttpServletResponse response) throws IOException {
        // 准备模板数据
        List<CriticalComponentImportExcelVO> list = new ArrayList<>();
        list.add(CriticalComponentImportExcelVO.builder()
                .code("TEST001")
                .name("电机")
                .description("主驱动电机")
                .remark("西门子品牌")
                .build());
        list.add(CriticalComponentImportExcelVO.builder()
                .code("TEST002")
                .name("传感器")
                .description("温度传感器")
                .remark("欧姆龙品牌")
                .build());
        // 输出
        ExcelUtils.write(response, "设备关键件导入模板.xls", "数据", CriticalComponentImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入设备关键件")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('mes:critical-component:import')")
    public CommonResult<CriticalComponentImportRespVO> importExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        // 1. 读取 Excel 数据
        List<CriticalComponentImportExcelVO> list = ExcelUtils.read(file, CriticalComponentImportExcelVO.class);
        // 2. 调用 Service 并返回结果
        return success(criticalComponentService.importCriticalComponentList(list, updateSupport));
    }

}