package cn.iocoder.yudao.module.pms.controller.admin.iotmaterial;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
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.pms.controller.admin.iotmaterial.vo.*;
import cn.iocoder.yudao.module.pms.convert.iotmaterial.IotMaterialConvert;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotmaterial.IotMaterialDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotmaterialgroup.IotMaterialGroupDO;
import cn.iocoder.yudao.module.pms.service.iotmaterial.IotMaterialService;
import cn.iocoder.yudao.module.pms.service.iotmaterialgroup.IotMaterialGroupService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
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.util.List;
import java.util.Map;

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

@Tag(name = "管理后台 - PMS 功能优化 物料")
@RestController
@RequestMapping("/rq/iot-material")
@Validated
public class IotMaterialController {

    @Resource
    private IotMaterialService iotMaterialService;

    @Resource
    private IotMaterialGroupService iotMaterialGroupService;

    @PostMapping("/create")
    @Operation(summary = "创建PMS 功能优化 物料")
    @PreAuthorize("@ss.hasPermission('rq:iot-material:create')")
    public CommonResult<Long> createIotMaterial(@Valid @RequestBody IotMaterialSaveReqVO createReqVO) {
        return success(iotMaterialService.createIotMaterial(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新PMS 功能优化 物料")
    @PreAuthorize("@ss.hasPermission('rq:iot-material:update')")
    public CommonResult<Boolean> updateIotMaterial(@Valid @RequestBody IotMaterialSaveReqVO updateReqVO) {
        iotMaterialService.updateIotMaterial(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改物料状态")
    @PreAuthorize("@ss.hasPermission('rq:iot-material:update')")
    public CommonResult<Boolean> updateMaterialStatus(@Valid @RequestBody MaterialUpdateStatusReqVO reqVO) {
        iotMaterialService.updateMaterialStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除PMS 功能优化 物料")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-material:delete')")
    public CommonResult<Boolean> deleteIotMaterial(@RequestParam("id") Long id) {
        iotMaterialService.deleteIotMaterial(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得PMS 功能优化 物料")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-material:query')")
    public CommonResult<IotMaterialRespVO> getIotMaterial(@RequestParam("id") Long id) {
        IotMaterialDO iotMaterial = iotMaterialService.getIotMaterial(id);
        return success(BeanUtils.toBean(iotMaterial, IotMaterialRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得PMS 功能优化 物料分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-material:query')")
    public CommonResult<PageResult<IotMaterialRespVO>> getIotMaterialPage(@Valid IotMaterialPageReqVO pageReqVO) {
        PageResult<IotMaterialDO> pageResult = iotMaterialService.getIotMaterialPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        // 拼接物料组
        Map<Long, IotMaterialGroupDO> materialGroupMap = iotMaterialGroupService.getMaterialGroupMap(
                convertList(pageResult.getList(), IotMaterialDO::getMaterialGroupId));
        return success(new PageResult<>(IotMaterialConvert.INSTANCE.convertList(pageResult.getList(), materialGroupMap),
                pageResult.getTotal()));
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取物料精简信息列表", description = "只包含被开启的物料，主要用于前端的下拉选项")
    public CommonResult<List<IotMaterialSimpleRespVO>> getSimpleMaterialList() {
        List<IotMaterialDO> list = iotMaterialService.getMaterialListByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 拼接数据
        Map<Long, IotMaterialGroupDO> materialGroupMap = iotMaterialGroupService.getMaterialGroupMap(
                convertList(list, IotMaterialDO::getMaterialGroupId));
        return success(IotMaterialConvert.INSTANCE.convertSimpleList(list, materialGroupMap));
    }

    @GetMapping("/list-by-bom-id")
    @Operation(summary = "根据设备分类bom节点id获取物料列表")
    @PreAuthorize("@ss.hasPermission('rq:iot-material:query')")
    public CommonResult<PageResult<IotMaterialRespVO>> getMaterialsByBomId(@Valid IotMaterialPageReqVO reqVO) {
        PageResult<IotMaterialDO> bomMaterials = iotMaterialService.getMaterialsByBomId(reqVO);
        return success(buildMaterialVOPageResult(bomMaterials));
    }

    @GetMapping("/list-by-device-bom-id")
    @Operation(summary = "根据设备bom节点id获取物料列表")
    @PreAuthorize("@ss.hasPermission('rq:iot-material:query')")
    public CommonResult<PageResult<IotMaterialRespVO>> getMaterialsByDeviceBomId(@Valid IotMaterialPageReqVO reqVO) {
        PageResult<IotMaterialDO> deviceMaterials = iotMaterialService.getMaterialsByDeviceBomId(reqVO);
        return success(buildMaterialVOPageResult(deviceMaterials));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出PMS 功能优化 物料 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-material:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotMaterialExcel(@Valid IotMaterialPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotMaterialDO> list = iotMaterialService.getIotMaterialPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "PMS 功能优化 物料.xls", "数据", IotMaterialRespVO.class,
                        BeanUtils.toBean(list, IotMaterialRespVO.class));
    }

    private PageResult<IotMaterialRespVO> buildMaterialVOPageResult(PageResult<IotMaterialDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, IotMaterialRespVO.class);
    }

}