package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.DynamicReport;
import com.zhentao.mapper.DynamicReportMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/admin/report")
@CrossOrigin(origins = "*")
public class DynamicReportController {

    @Autowired
    private DynamicReportMapper reportMapper;

    /** 举报列表 */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long dynamicId) {
        Page<DynamicReport> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<DynamicReport> qw = new LambdaQueryWrapper<>();
        if (status != null) qw.eq(DynamicReport::getStatus, status);
        if (dynamicId != null) qw.eq(DynamicReport::getDynamicId, dynamicId);
        qw.orderByDesc(DynamicReport::getCreatedAt);
        Page<DynamicReport> res = reportMapper.selectPage(p, qw);

        // 批量查询举报人昵称和被举报人昵称
        try {
            java.util.Set<Long> reporterIds = new java.util.HashSet<>();
            java.util.Set<Integer> dynamicIds = new java.util.HashSet<>();
            for (DynamicReport r : res.getRecords()) {
                if (r.getReporterId() != null) reporterIds.add(r.getReporterId());
                if (r.getDynamicId() != null) dynamicIds.add(r.getDynamicId().intValue());
            }
            
            // 查询举报人昵称
            if (!reporterIds.isEmpty()) {
                java.util.List<java.util.Map<String, Object>> rows = reportMapper.findNicknamesByUserIds(new java.util.ArrayList<>(reporterIds));
                java.util.Map<Long, String> id2name = new java.util.HashMap<>();
                for (java.util.Map<String, Object> row : rows) {
                    Object uid = row.get("user_id");
                    Object nick = row.get("nickname");
                    if (uid != null && nick != null) {
                        id2name.put(Long.parseLong(uid.toString()), nick.toString());
                    }
                }
                for (DynamicReport r : res.getRecords()) {
                    r.setReporterName(id2name.get(r.getReporterId()));
                }
            }
            
            // 查询被举报人昵称（动态作者）
            if (!dynamicIds.isEmpty()) {
                System.out.println("查询被举报人，动态ID列表: " + dynamicIds);
                java.util.List<java.util.Map<String,Object>> rows = reportMapper.findAuthorNickByDynamicIds(new java.util.ArrayList<>(dynamicIds));
                System.out.println("查询结果数量: " + (rows != null ? rows.size() : 0));
                java.util.Map<Integer, String> d2author = new java.util.HashMap<>();
                for (java.util.Map<String, Object> row : rows) {
                    Object did = row.get("dynamic_id");
                    Object nick = row.get("nickname");
                    System.out.println("动态ID: " + did + ", 昵称: " + nick);
                    if (did != null && nick != null) {
                        d2author.put(Integer.parseInt(did.toString()), nick.toString());
                    }
                }
                for (DynamicReport r : res.getRecords()) {
                    if (r.getDynamicId() != null) {
                        String authorName = d2author.get(r.getDynamicId().intValue());
                        System.out.println("设置举报ID=" + r.getReportId() + ", 动态ID=" + r.getDynamicId() + " 的被举报人为: " + authorName);
                        r.setReportedName(authorName);
                    }
                }
            }
        } catch (Exception ex) {
            System.err.println("批量查询昵称异常:" + ex.getMessage());
            ex.printStackTrace();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("list", res.getRecords());
        data.put("total", res.getTotal());
        data.put("page", page);
        data.put("pageSize", pageSize);
        return Result.success(data);
    }

    /** 举报详情 */
    @GetMapping("/detail/{reportId}")
    public Result<DynamicReport> detail(@PathVariable Long reportId) {
        DynamicReport r = reportMapper.selectById(reportId);
        if (r == null) return Result.error("举报不存在");
        return Result.success(r);
    }

    /** 处理举报 */
    @PostMapping("/handle/{reportId}")
    public Result<String> handle(@PathVariable Long reportId, @RequestBody Map<String, Object> body) {
        DynamicReport r = reportMapper.selectById(reportId);
        if (r == null) return Result.error("举报不存在");
        Integer status = (Integer) body.get("status");
        String handleResult = (String) body.getOrDefault("handleResult", "");
        if (status == null) return Result.error("状态不能为空");
        r.setStatus(status);
        r.setHandleResult(handleResult);
        r.setHandleTime(LocalDateTime.now());
        // 简化：处理人ID固定为1，可接入登录态后替换
        r.setHandlerId(1L);
        reportMapper.updateById(r);
        return Result.success("处理成功");
    }
}


