package com.zt.plat.module.base.controller.admin.materialclasses;

import org.springframework.web.bind.annotation.*;
import jakarta.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 jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import static com.zt.plat.framework.common.pojo.CommonResult.success;

import com.zt.plat.framework.excel.core.util.ExcelUtils;

import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.*;

import com.zt.plat.module.base.controller.admin.materialclasses.vo.*;
import com.zt.plat.module.base.dal.dataobject.materialclasses.MaterialClassesDO;
import com.zt.plat.module.base.service.materialclasses.MaterialClassesService;

@Tag(name = "管理后台 - 物料分类")
@RestController
@RequestMapping("/base/material-classes")
@Validated
public class MaterialClassesController {


    @Resource
    private MaterialClassesService materialClassesService;

    @PostMapping("/create")
    @Operation(summary = "创建物料分类")
    @PreAuthorize("@ss.hasPermission('base:material-infomation:create')")
    public CommonResult<MaterialClassesRespVO> createMaterialClasses(@Valid @RequestBody MaterialClassesSaveReqVO createReqVO) {
        return success(materialClassesService.createMaterialClasses(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新物料分类")
    @PreAuthorize("@ss.hasPermission('base:material-infomation:update')")
    public CommonResult<Boolean> updateMaterialClasses(@Valid @RequestBody MaterialClassesSaveReqVO updateReqVO) {
        materialClassesService.updateMaterialClasses(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除物料分类")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('base:material-infomation:delete')")
    public CommonResult<Boolean> deleteMaterialClasses(@RequestParam("id") Long id) {
        materialClassesService.deleteMaterialClasses(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除物料分类")
                @PreAuthorize("@ss.hasPermission('base:material-infomation:delete')")
    public CommonResult<Boolean> deleteMaterialClassesList(@RequestBody BatchDeleteReqVO req) {
        materialClassesService.deleteMaterialClassesListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得物料分类")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('base:material-infomation:query')")
    public CommonResult<MaterialClassesRespVO> getMaterialClasses(@RequestParam("id") Long id) {
        MaterialClassesDO materialClasses = materialClassesService.getMaterialClasses(id);
        return success(BeanUtils.toBean(materialClasses, MaterialClassesRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得物料分类分页")
    @PreAuthorize("@ss.hasPermission('base:material-infomation:query')")
    public CommonResult<PageResult<MaterialClassesRespVO>> getMaterialClassesPage(@Valid MaterialClassesPageReqVO pageReqVO) {
        PageResult<MaterialClassesDO> pageResult = materialClassesService.getMaterialClassesPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, MaterialClassesRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出物料分类 Excel")
    @PreAuthorize("@ss.hasPermission('base:material-infomation:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMaterialClassesExcel(@Valid MaterialClassesPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MaterialClassesDO> list = materialClassesService.getMaterialClassesPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "物料分类.xls", "数据", MaterialClassesRespVO.class,
                        BeanUtils.toBean(list, MaterialClassesRespVO.class));
    }

    @GetMapping("/tree")
    @Operation(summary = "获得物料分类树")
    @PreAuthorize("@ss.hasPermission('base:material-infomation:query')")
    public CommonResult<List<MaterialClassesTreeRespVO>> getMaterialClassesTree() {
        List<MaterialClassesDO> list = materialClassesService.getMaterialClassesList();
        return success(buildTree(list));
    }

    private List<MaterialClassesTreeRespVO> buildTree(List<MaterialClassesDO> list) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        Map<Long, MaterialClassesTreeRespVO> nodeMap = new LinkedHashMap<>();
        list.stream()
                .sorted(Comparator.comparing(MaterialClassesDO::getId))
                .forEach(item -> {
                    MaterialClassesTreeRespVO node = BeanUtils.toBean(item, MaterialClassesTreeRespVO.class);
                    nodeMap.put(node.getId(), node);
                });
        List<MaterialClassesTreeRespVO> roots = new ArrayList<>();
        nodeMap.values().forEach(node -> {
            Long parentId = node.getParentId();
            if (parentId == null || parentId == 0 || !nodeMap.containsKey(parentId)) {
                roots.add(node);
            } else {
                nodeMap.get(parentId).getChildren().add(node);
            }
        });
        return roots;
    }

}