package com.test.bijihoudaun.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ObjectUtil;
import com.test.bijihoudaun.common.response.R;
import com.test.bijihoudaun.entity.Grouping;
import com.test.bijihoudaun.service.GroupingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "分组接口")
@RestController
@RequestMapping("/api/groupings")
public class GroupingController {

    @Autowired
    private GroupingService groupingService;

    @Operation(summary = "创建分组")
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping
    public R<Grouping> createGrouping(@RequestBody Grouping grouping) {
        if (ObjectUtil.isNull(grouping.getParentId())) {
            grouping.setParentId(0L);
        }
        Grouping created = groupingService.createGrouping(grouping);
        return R.success(created);
    }

    @Operation(summary = "获取全部分组")
    @Parameters({
            @Parameter(name = "parentId", description = "0是一级，其他的是看它的父级id", required = false)
    })
    @GetMapping
    public R<List<Grouping>> getAllGroupings(@RequestParam(required = false) String parentId) {
        Long l= null;
        if (StrUtil.isNotEmpty(parentId)) {
             l = Long.parseLong(parentId);
        }
        List<Grouping> groupings = groupingService.getAllGroupings(l);
        return R.success(groupings);
    }

    @Operation(summary = "更新分组名称")
    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/{id}")
    public R<Grouping> updateGrouping(
            @PathVariable Long id,
            @RequestBody Grouping grouping) {
        grouping.setId(id);
        Grouping updated = groupingService.updateGrouping(grouping);
        return R.success(updated);
    }

    @Operation(summary = "删除分组")
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{id}")
    public R<Void> deleteGrouping(@PathVariable Long id) {
        groupingService.deleteGrouping(id);
        return R.success();
    }
}
