package cn.iocoder.yudao.module.iot.controller.admin.recipetype;

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 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.iot.controller.admin.recipetype.vo.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.recipetype.RecipeTypeDO;
import cn.iocoder.yudao.module.iot.service.recipetype.RecipeTypeService;

@Tag(name = "管理后台 - 配方类型表（基础字典）")
@RestController
@RequestMapping("/iot/recipe-type")
@Validated
public class RecipeTypeController {

    @Resource
    private RecipeTypeService recipeTypeService;

    @PostMapping("/create")
    @Operation(summary = "创建配方类型表（基础字典）")
    @PreAuthorize("@ss.hasPermission('iot:recipe-type:create')")
    public CommonResult<Long> createRecipeType(@Valid @RequestBody RecipeTypeSaveReqVO createReqVO) {
        return success(recipeTypeService.createRecipeType(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新配方类型表（基础字典）")
    @PreAuthorize("@ss.hasPermission('iot:recipe-type:update')")
    public CommonResult<Boolean> updateRecipeType(@Valid @RequestBody RecipeTypeSaveReqVO updateReqVO) {
        recipeTypeService.updateRecipeType(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除配方类型表（基础字典）")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('iot:recipe-type:delete')")
    public CommonResult<Boolean> deleteRecipeType(@RequestParam("id") Long id) {
        recipeTypeService.deleteRecipeType(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得配方类型表（基础字典）")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('iot:recipe-type:query')")
    public CommonResult<RecipeTypeRespVO> getRecipeType(@RequestParam("id") Long id) {
        RecipeTypeDO recipeType = recipeTypeService.getRecipeType(id);
        return success(BeanUtils.toBean(recipeType, RecipeTypeRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得配方类型表（基础字典）分页")
    @PreAuthorize("@ss.hasPermission('iot:recipe-type:query')")
    public CommonResult<PageResult<RecipeTypeRespVO>> getRecipeTypePage(@Valid RecipeTypePageReqVO pageReqVO) {
        PageResult<RecipeTypeDO> pageResult = recipeTypeService.getRecipeTypePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, RecipeTypeRespVO.class));
    }

    @GetMapping("/page-all")
    @Operation(summary = "获得配方类型表（不传分页参数查全部，传则分页）")
    @PreAuthorize("@ss.hasPermission('iot:recipe-type:query')")
    public CommonResult<PageResult<RecipeTypeRespVO>> getRecipeTypePageAll(
            RecipeTypePageReqVO pageReqVO,
            HttpServletRequest request) { // 注入request，判断参数是否传了

        // 核心优化：判断前端是否真的传了pageNo/pageSize，而非判断值（避免前端传1/10时误判）
        boolean hasPageNo = request.getParameter("pageNo") != null;
        boolean hasPageSize = request.getParameter("pageSize") != null;
        boolean isQueryAll = !hasPageNo && !hasPageSize;

        PageResult<RecipeTypeDO> pageResult;
        if (isQueryAll) {
            // 查全部逻辑
            pageResult = recipeTypeService.getRecipeTypeAll(pageReqVO);
        } else {
            // 传了分页参数则手动校验（替代@Valid，避免必填报错）
//            ValidatorUtil.validate(pageReqVO);
            // 复用原有分页逻辑
            pageResult = recipeTypeService.getRecipeTypePage(pageReqVO);
        }
        return success(BeanUtils.toBean(pageResult, RecipeTypeRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出配方类型表（基础字典） Excel")
    @PreAuthorize("@ss.hasPermission('iot:recipe-type:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportRecipeTypeExcel(@Valid RecipeTypePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<RecipeTypeDO> list = recipeTypeService.getRecipeTypePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "配方类型表（基础字典）.xls", "数据", RecipeTypeRespVO.class,
                        BeanUtils.toBean(list, RecipeTypeRespVO.class));
    }

}