package com.lesingle.modules.pub.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lesingle.common.enums.CommonStatus;
import com.lesingle.common.exception.BusinessException;
import com.lesingle.common.result.Result;
import com.lesingle.modules.ugc.entity.UgcTag;
import com.lesingle.modules.ugc.mapper.UgcTagMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "标签管理")
@RestController
@RequestMapping("/tags")
@RequiredArgsConstructor
public class TagManagementController {

    private final UgcTagMapper ugcTagMapper;

    @GetMapping
    @Operation(summary = "标签列表（管理端）")
    public Result<List<UgcTag>> list() {
        return Result.success(ugcTagMapper.selectList(
                new LambdaQueryWrapper<UgcTag>().orderByAsc(UgcTag::getSort)));
    }

    @PostMapping
    @Operation(summary = "创建标签")
    public Result<UgcTag> create(@RequestBody Map<String, Object> body) {
        UgcTag tag = new UgcTag();
        tag.setName((String) body.get("name"));
        tag.setCategory((String) body.get("category"));
        tag.setColor((String) body.get("color"));
        tag.setSort(body.get("sort") != null ? ((Number) body.get("sort")).intValue() : 0);
        tag.setStatus(CommonStatus.ENABLED.getValue());
        tag.setUsageCount(0);
        tag.setCreateTime(LocalDateTime.now());
        tag.setModifyTime(LocalDateTime.now());
        ugcTagMapper.insert(tag);
        return Result.success(tag);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新标签")
    public Result<Void> update(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        UgcTag tag = ugcTagMapper.selectById(id);
        if (tag == null) {
            throw new BusinessException(404, "标签不存在");
        }
        if (body.containsKey("name")) tag.setName((String) body.get("name"));
        if (body.containsKey("category")) tag.setCategory((String) body.get("category"));
        if (body.containsKey("color")) tag.setColor((String) body.get("color"));
        if (body.containsKey("sort")) tag.setSort(((Number) body.get("sort")).intValue());
        tag.setModifyTime(LocalDateTime.now());
        ugcTagMapper.updateById(tag);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除标签")
    public Result<Void> delete(@PathVariable Long id) {
        ugcTagMapper.deleteById(id);
        return Result.success();
    }

    @PostMapping("/batch-sort")
    @Operation(summary = "批量排序")
    public Result<Void> batchSort(@RequestBody List<Map<String, Object>> items) {
        for (Map<String, Object> item : items) {
            Long id = ((Number) item.get("id")).longValue();
            Integer sort = ((Number) item.get("sort")).intValue();
            ugcTagMapper.update(null, new LambdaUpdateWrapper<UgcTag>()
                    .eq(UgcTag::getId, id)
                    .set(UgcTag::getSort, sort)
                    .set(UgcTag::getModifyTime, LocalDateTime.now()));
        }
        return Result.success();
    }

    @PatchMapping("/{id}/status")
    @Operation(summary = "切换标签状态")
    public Result<Void> toggleStatus(@PathVariable Long id) {
        UgcTag tag = ugcTagMapper.selectById(id);
        if (tag == null) {
            throw new BusinessException(404, "标签不存在");
        }
        String newStatus = CommonStatus.ENABLED.getValue().equals(tag.getStatus()) ? CommonStatus.DISABLED.getValue() : CommonStatus.ENABLED.getValue();
        tag.setStatus(newStatus);
        tag.setModifyTime(LocalDateTime.now());
        ugcTagMapper.updateById(tag);
        return Result.success();
    }

    @GetMapping("/categories")
    @Operation(summary = "获取标签分类")
    public Result<List<String>> getCategories() {
        List<UgcTag> tags = ugcTagMapper.selectList(
                new LambdaQueryWrapper<UgcTag>().isNotNull(UgcTag::getCategory).groupBy(UgcTag::getCategory));
        List<String> categories = tags.stream()
                .map(UgcTag::getCategory)
                .distinct()
                .collect(Collectors.toList());
        return Result.success(categories);
    }
}
