package com.competition.modules.biz.contest.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.competition.common.result.PageResult;
import com.competition.common.result.Result;
import com.competition.common.util.SecurityUtil;
import com.competition.modules.biz.contest.dto.CreateNoticeDto;
import com.competition.modules.biz.contest.entity.BizContestNotice;
import com.competition.modules.biz.contest.service.IContestNoticeService;
import com.competition.security.annotation.RequirePermission;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Tag(name = "赛事公告")
@RestController
@RequestMapping("/contests/notices")
@RequiredArgsConstructor
public class ContestNoticeController {

    private final IContestNoticeService noticeService;

    /**
     * 解析日期时间字符串，兼容 ISO 格式（带毫秒和 Z 时区标记）
     */
    private LocalDateTime parseDateTime(String dateTime) {
        if (!StringUtils.hasText(dateTime)) {
            return null;
        }
        // 尝试 ISO 格式（yyyy-MM-dd'T'HH:mm:ss.SSSZ 或 yyyy-MM-dd'T'HH:mm:ss'Z'）
        try {
            // 处理带 Z 的 ISO 格式
            if (dateTime.endsWith("Z")) {
                return LocalDateTime.parse(dateTime.substring(0, dateTime.length() - 1));
            }
            // 处理带毫秒的格式
            if (dateTime.contains(".") && dateTime.indexOf(".") + 4 == dateTime.length()) {
                return LocalDateTime.parse(dateTime.substring(0, dateTime.indexOf(".")));
            }
            return LocalDateTime.parse(dateTime);
        } catch (Exception e) {
            // 尝试空格分隔格式
            try {
                return LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } catch (Exception ex) {
                return null;
            }
        }
    }

    @PostMapping
    @RequirePermission("notice:create")
    @Operation(summary = "创建公告")
    public Result<BizContestNotice> create(@Valid @RequestBody CreateNoticeDto dto) {
        BizContestNotice notice = new BizContestNotice();
        notice.setContestId(dto.getContestId());
        notice.setTitle(dto.getTitle());
        notice.setContent(dto.getContent());
        notice.setNoticeType(dto.getNoticeType());
        notice.setPriority(dto.getPriority());
        if (StringUtils.hasText(dto.getPublishTime())) {
            notice.setPublishTime(parseDateTime(dto.getPublishTime()));
        }
        // 设置当前租户 ID（租户隔离）
        notice.setTenantId(SecurityUtil.getCurrentTenantId());
        noticeService.save(notice);
        return Result.success(notice);
    }

    @GetMapping("/contest/{contestId}")
    @RequirePermission("notice:read")
    @Operation(summary = "查询赛事下的公告列表")
    public Result<List<BizContestNotice>> findByContest(@PathVariable Long contestId) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        List<BizContestNotice> list = noticeService.list(
                new LambdaQueryWrapper<BizContestNotice>()
                        .eq(BizContestNotice::getContestId, contestId)
                        .eq(BizContestNotice::getTenantId, tenantId)
                        .orderByDesc(BizContestNotice::getCreateTime));
        return Result.success(list);
    }

    @GetMapping
    @RequirePermission("notice:read")
    @Operation(summary = "分页查询公告列表")
    public Result<PageResult<BizContestNotice>> findAll(
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String status) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        LambdaQueryWrapper<BizContestNotice> wrapper = new LambdaQueryWrapper<BizContestNotice>()
                .eq(BizContestNotice::getTenantId, tenantId)  // 租户隔离
                .like(StringUtils.hasText(title), BizContestNotice::getTitle, title);

        // 发布状态过滤
        if ("published".equals(status)) {
            wrapper.isNotNull(BizContestNotice::getPublishTime);
        } else if ("unpublished".equals(status)) {
            wrapper.isNull(BizContestNotice::getPublishTime);
        }

        wrapper.orderByDesc(BizContestNotice::getCreateTime);
        Page<BizContestNotice> result = noticeService.page(new Page<>(page, pageSize), wrapper);
        return Result.success(PageResult.from(result));
    }

    @GetMapping("/{id}")
    @RequirePermission("notice:read")
    @Operation(summary = "查询公告详情")
    public Result<BizContestNotice> findDetail(@PathVariable Long id) {
        return Result.success(noticeService.getById(id));
    }

    @PatchMapping("/{id}")
    @RequirePermission("notice:update")
    @Operation(summary = "更新公告")
    public Result<Void> update(@PathVariable Long id, @RequestBody CreateNoticeDto dto) {
        BizContestNotice notice = new BizContestNotice();
        notice.setId(id);
        notice.setTitle(dto.getTitle());
        notice.setContent(dto.getContent());
        notice.setNoticeType(dto.getNoticeType());
        notice.setPriority(dto.getPriority());
        if (StringUtils.hasText(dto.getPublishTime())) {
            notice.setPublishTime(parseDateTime(dto.getPublishTime()));
        }
        noticeService.updateById(notice);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @RequirePermission("notice:delete")
    @Operation(summary = "删除公告")
    public Result<Void> remove(@PathVariable Long id) {
        noticeService.removeById(id);
        return Result.success();
    }
}
