package com.yhy.module.core.controller.admin.quota;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.yhy.module.core.controller.admin.quota.vo.QuotaCatalogItemBindSpecialtyReqVO;
import com.yhy.module.core.controller.admin.quota.vo.QuotaCatalogItemRespVO;
import com.yhy.module.core.controller.admin.quota.vo.QuotaCatalogItemSaveReqVO;
import com.yhy.module.core.controller.admin.resource.vo.ResourceCategoryFullRespVO;
import com.yhy.module.core.service.quota.QuotaCatalogItemService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 定额目录条目 Controller
 * 
 * @author yhy
 */
@Tag(name = "管理后台 - 定额目录条目")
@RestController
@RequestMapping("/core/quota/catalog-item")
@Validated
public class QuotaCatalogItemController {

    @Resource
    private QuotaCatalogItemService quotaCatalogItemService;

    @PostMapping("/create")
    @Operation(summary = "创建定额目录条目")
    @PreAuthorize("@ss.hasPermission('core:quota:create')")
    public CommonResult<Long> createQuotaCatalogItem(@Valid @RequestBody QuotaCatalogItemSaveReqVO createReqVO) {
        return success(quotaCatalogItemService.createQuotaCatalogItem(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新定额目录条目")
    @PreAuthorize("@ss.hasPermission('core:quota:update')")
    public CommonResult<Boolean> updateQuotaCatalogItem(@Valid @RequestBody QuotaCatalogItemSaveReqVO updateReqVO) {
        quotaCatalogItemService.updateQuotaCatalogItem(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除定额目录条目")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('core:quota:delete')")
    public CommonResult<Boolean> deleteQuotaCatalogItem(@RequestParam("id") Long id) {
        quotaCatalogItemService.deleteQuotaCatalogItem(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得定额专业节点")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('core:quota:query')")
    public CommonResult<QuotaCatalogItemRespVO> getQuotaCatalogItem(@RequestParam("id") Long id) {
        return success(convertToVO(quotaCatalogItemService.getQuotaCatalogItem(id)));
    }

    @GetMapping("/list")
    @Operation(summary = "获得定额专业节点列表（第一层）")
    @PreAuthorize("@ss.hasPermission('core:quota:query')")
    public CommonResult<List<QuotaCatalogItemRespVO>> getQuotaCatalogItemList() {
        return success(quotaCatalogItemService.getQuotaCatalogItemList());
    }

    @GetMapping("/tree")
    @Operation(summary = "获得定额专业树结构（第一层）")
    @PreAuthorize("@ss.hasPermission('core:quota:query')")
    public CommonResult<List<QuotaCatalogItemRespVO>> getQuotaCatalogItemTree(
            @RequestParam(value = "exclude", required = false)
            @Parameter(description = "Exclude node types (comma-separated or repeated)", example = "specialty,rate_mode")
            List<String> exclude) {
        return success(quotaCatalogItemService.getQuotaCatalogItemTree(normalizeExcludeTypes(exclude)));
    }

    @PostMapping("/swap-sort")
    @Operation(summary = "交换两个节点的排序")
    @PreAuthorize("@ss.hasPermission('core:quota:update')")
    public CommonResult<Boolean> swapSort(@Valid @RequestBody com.yhy.module.core.controller.admin.quota.vo.QuotaCatalogItemSwapSortReqVO reqVO) {
        quotaCatalogItemService.swapSort(reqVO.getNodeId1(), reqVO.getNodeId2());
        return success(true);
    }

    @PostMapping("/bind-specialty")
    @Operation(summary = "绑定工料机专业")
    @PreAuthorize("@ss.hasPermission('core:quota:update')")
    public CommonResult<Boolean> bindResourceSpecialty(@Valid @RequestBody QuotaCatalogItemBindSpecialtyReqVO reqVO) {
        quotaCatalogItemService.bindResourceSpecialty(reqVO.getCatalogItemId(), reqVO.getCategoryTreeId());
        return success(true);
    }

    @GetMapping("/{catalogItemId}/categories")
    @Operation(summary = "通过费率模式节点获取工料机类别字典（含价格代码）")
    @Parameter(name = "catalogItemId", description = "定额目录节点ID（费率模式节点或定额专业节点）", required = true, example = "2005272359865745410")
    @PreAuthorize("@ss.hasPermission('core:quota:query')")
    public CommonResult<List<ResourceCategoryFullRespVO>> getCategoriesByCatalogItem(@PathVariable("catalogItemId") Long catalogItemId) {
        return success(quotaCatalogItemService.getCategoriesByCatalogItem(catalogItemId));
    }

    // ========== 私有方法 ==========

    private QuotaCatalogItemRespVO convertToVO(com.yhy.module.core.dal.dataobject.quota.QuotaCatalogItemDO catalogItem) {
        if (catalogItem == null) {
            return null;
        }
        QuotaCatalogItemRespVO vo = new QuotaCatalogItemRespVO();
        vo.setId(catalogItem.getId());
        vo.setParentId(catalogItem.getParentId());
        vo.setCategoryTreeId(catalogItem.getCategoryTreeId());
        vo.setCode(catalogItem.getCode());
        vo.setName(catalogItem.getName());
        vo.setUnit(catalogItem.getUnit());
        vo.setPath(catalogItem.getPath());
        vo.setSortOrder(catalogItem.getSortOrder());
        vo.setAttributes(catalogItem.getAttributes());
        vo.setCreateTime(catalogItem.getCreateTime());
        vo.setUpdateTime(catalogItem.getUpdateTime());
        vo.setNodeType(catalogItem.getNodeType());
        vo.setSpecialtyLocked(catalogItem.isSpecialtyLocked());
        return vo;
    }

    private List<String> normalizeExcludeTypes(List<String> exclude) {
        if (exclude == null || exclude.isEmpty()) {
            return null;
        }
        return exclude.stream()
                .flatMap(value -> Arrays.stream(value.split(",")))
                .map(String::trim)
                .filter(StringUtils::hasText)
                .distinct()
                .collect(Collectors.toList());
    }
}
