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

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.processinginfomation.vo.*;
import com.zt.plat.module.base.dal.dataobject.processinginfomation.ProcessingInfomationDO;
import com.zt.plat.module.base.service.processinginfomation.ProcessingInfomationService;

@Tag(name = "管理后台 - 工艺信息")
@RestController
@RequestMapping("/base/processing-infomation")
@Validated
public class ProcessingInfomationController {


    @Resource
    private ProcessingInfomationService processingInfomationService;

    @PostMapping("/create")
    @Operation(summary = "创建工艺信息")
    @PreAuthorize("@ss.hasPermission('base:processing-infomation:create')")
    public CommonResult<ProcessingInfomationRespVO> createProcessingInfomation(@Valid @RequestBody ProcessingInfomationSaveReqVO createReqVO) {
        return success(processingInfomationService.createProcessingInfomation(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新工艺信息")
    @PreAuthorize("@ss.hasPermission('base:processing-infomation:update')")
    public CommonResult<Boolean> updateProcessingInfomation(@Valid @RequestBody ProcessingInfomationSaveReqVO updateReqVO) {
        processingInfomationService.updateProcessingInfomation(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工艺信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('base:processing-infomation:delete')")
    public CommonResult<Boolean> deleteProcessingInfomation(@RequestParam("id") Long id) {
        processingInfomationService.deleteProcessingInfomation(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除工艺信息")
                @PreAuthorize("@ss.hasPermission('base:processing-infomation:delete')")
    public CommonResult<Boolean> deleteProcessingInfomationList(@RequestBody BatchDeleteReqVO req) {
        processingInfomationService.deleteProcessingInfomationListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工艺信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('base:processing-infomation:query')")
    public CommonResult<ProcessingInfomationRespVO> getProcessingInfomation(@RequestParam("id") Long id) {
        ProcessingInfomationDO processingInfomation = processingInfomationService.getProcessingInfomation(id);
        return success(BeanUtils.toBean(processingInfomation, ProcessingInfomationRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得工艺信息分页")
    @PreAuthorize("@ss.hasPermission('base:processing-infomation:query')")
    public CommonResult<PageResult<ProcessingInfomationRespVO>> getProcessingInfomationPage(@Valid ProcessingInfomationPageReqVO pageReqVO) {
        PageResult<ProcessingInfomationDO> pageResult = processingInfomationService.getProcessingInfomationPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ProcessingInfomationRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出工艺信息 Excel")
    @PreAuthorize("@ss.hasPermission('base:processing-infomation:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProcessingInfomationExcel(@Valid ProcessingInfomationPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ProcessingInfomationDO> list = processingInfomationService.getProcessingInfomationPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "工艺信息.xls", "数据", ProcessingInfomationRespVO.class,
                        BeanUtils.toBean(list, ProcessingInfomationRespVO.class));
    }

    @GetMapping("/tree")
    @Operation(summary = "获得工艺信息树")
    @PreAuthorize("@ss.hasPermission('base:processing-infomation:query')")
    public CommonResult<List<ProcessingInfomationTreeRespVO>> getProcessingInfomationTree() {
        List<ProcessingInfomationDO> list = processingInfomationService.getProcessingInfomationList();
        return success(buildTree(list));
    }

    private List<ProcessingInfomationTreeRespVO> buildTree(List<ProcessingInfomationDO> list) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        Map<Long, ProcessingInfomationTreeRespVO> nodeMap = new LinkedHashMap<>();
        list.stream()
                .sorted(Comparator.comparing(ProcessingInfomationDO::getId))
                .forEach(item -> {
                    ProcessingInfomationTreeRespVO node = BeanUtils.toBean(item, ProcessingInfomationTreeRespVO.class);
                    nodeMap.put(node.getId(), node);
                });
        List<ProcessingInfomationTreeRespVO> 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;
    }

}