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

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
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.iotcommonbommaterial.vo.IotCommonBomMaterialPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotcommonbommaterial.vo.IotCommonBomMaterialRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotcommonbommaterial.vo.IotCommonBomMaterialSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotmaterial.vo.IotMaterialPageReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotcommonbommaterial.IotCommonBomMaterialDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotmaterial.IotMaterialDO;
import cn.iocoder.yudao.module.pms.service.iotcommonbommaterial.IotCommonBomMaterialService;
import cn.iocoder.yudao.module.pms.service.iotmaterial.IotMaterialService;
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.Collections;
import java.util.HashMap;
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;
import static cn.iocoder.yudao.framework.common.util.collection.MapUtils.findAndThen;

@Tag(name = "管理后台 - PMS 设备分类公共BOM挂载物料关联")
@RestController
@RequestMapping("/pms/iot-common-bom-material")
@Validated
public class IotCommonBomMaterialController {

    @Resource
    private IotCommonBomMaterialService iotCommonBomMaterialService;

    @Resource
    private IotMaterialService iotMaterialService;

    @PostMapping("/create")
    @Operation(summary = "创建PMS 设备分类公共BOM挂载物料关联")
    @PreAuthorize("@ss.hasPermission('pms:iot-common-bom-material:create')")
    public CommonResult<Long> createIotCommonBomMaterial(@Valid @RequestBody IotCommonBomMaterialSaveReqVO createReqVO) {
        return success(iotCommonBomMaterialService.createIotCommonBomMaterial(createReqVO));
    }

    @PostMapping("/addMaterials")
    @Operation(summary = "批量 创建PMS 设备分类公共BOM挂载物料关联")
    @PreAuthorize("@ss.hasPermission('pms:iot-common-bom-material:create')")
    public CommonResult<Long> addMaterials(@Valid @RequestBody List<IotCommonBomMaterialSaveReqVO> materials) {
        return success(iotCommonBomMaterialService.addMaterials(materials));
    }

    @PutMapping("/update")
    @Operation(summary = "更新PMS 设备分类公共BOM挂载物料关联")
    @PreAuthorize("@ss.hasPermission('pms:iot-common-bom-material:update')")
    public CommonResult<Boolean> updateIotCommonBomMaterial(@Valid @RequestBody IotCommonBomMaterialSaveReqVO updateReqVO) {
        iotCommonBomMaterialService.updateIotCommonBomMaterial(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除PMS 设备分类公共BOM挂载物料关联")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('pms:iot-common-bom-material:delete')")
    public CommonResult<Boolean> deleteIotCommonBomMaterial(@RequestParam("id") Long id) {
        iotCommonBomMaterialService.deleteIotCommonBomMaterial(id);
        return success(true);
    }

    @DeleteMapping("/deleteBomMaterial")
    @Operation(summary = "删除PMS 设备分类公共BOM挂载物料关联")
    @Parameter(name = "bomNodeId", description = "BOM节点id", required = true)
    @Parameter(name = "code", description = "物料编码", required = true)
    @PreAuthorize("@ss.hasPermission('pms:iot-common-bom-material:delete')")
    public CommonResult<Boolean> deleteBomMaterial(@RequestParam("bomNodeId") Long bomNodeId, @RequestParam("code") String code) {
        iotCommonBomMaterialService.deleteBomMaterial(bomNodeId, code);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得PMS 设备分类公共BOM挂载物料关联")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pms:iot-common-bom-material:query')")
    public CommonResult<IotCommonBomMaterialRespVO> getIotCommonBomMaterial(@RequestParam("id") Long id) {
        IotCommonBomMaterialDO iotCommonBomMaterial = iotCommonBomMaterialService.getIotCommonBomMaterial(id);
        return success(BeanUtils.toBean(iotCommonBomMaterial, IotCommonBomMaterialRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得PMS 设备分类公共BOM挂载物料关联分页")
    @PreAuthorize("@ss.hasPermission('pms:iot-common-bom-material:query')")
    public CommonResult<PageResult<IotCommonBomMaterialRespVO>> getIotCommonBomMaterialPage(@Valid IotCommonBomMaterialPageReqVO pageReqVO) {
        PageResult<IotCommonBomMaterialDO> pageResult = iotCommonBomMaterialService.getIotCommonBomMaterialPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        // return success(BeanUtils.toBean(pageResult, IotCommonBomMaterialRespVO.class));
        return success(new PageResult<>(buildBomMaterials(pageResult.getList()), pageResult.getTotal()));
    }

    /**
     * 组装 物料 单位
     * @param bomMaterials
     * @return
     */
    private List<IotCommonBomMaterialRespVO> buildBomMaterials(List<IotCommonBomMaterialDO> bomMaterials) {
        if (CollUtil.isEmpty(bomMaterials)) {
            return Collections.emptyList();
        }
        // 查询所有物料的单位
        IotMaterialPageReqVO reqVO = new IotMaterialPageReqVO();
        reqVO.setCodes(convertList(bomMaterials, IotCommonBomMaterialDO::getCode));
        List<IotMaterialDO> materials = iotMaterialService.getIotMaterials(reqVO);
        Map<String, String> materialUnitPair = new HashMap<>();
        if (CollUtil.isNotEmpty(materials)) {
            materials.forEach(material -> {
                materialUnitPair.put(material.getCode(), material.getUnit());
            });
        }
        // 2. 拼接数据
        return BeanUtils.toBean(bomMaterials, IotCommonBomMaterialRespVO.class, (materialVO) -> {
            // 2.1 拼接部门信息
            findAndThen(materialUnitPair, materialVO.getCode(), material -> materialVO.setUnit(material));
        });
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出PMS 设备分类公共BOM挂载物料关联 Excel")
    @PreAuthorize("@ss.hasPermission('pms:iot-common-bom-material:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotCommonBomMaterialExcel(@Valid IotCommonBomMaterialPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotCommonBomMaterialDO> list = iotCommonBomMaterialService.getIotCommonBomMaterialPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "PMS 设备分类公共BOM挂载物料关联.xls", "数据", IotCommonBomMaterialRespVO.class,
                        BeanUtils.toBean(list, IotCommonBomMaterialRespVO.class));
    }

}