package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.Dynamic;
import com.zhentao.mapper.DynamicMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 动态管理控制器
 */
@RestController
@RequestMapping("/admin/dynamic")
@CrossOrigin(origins = "*")
public class DynamicController {
    
    @Autowired
    private DynamicMapper dynamicMapper;
    
    /**
     * 动态列表（分页）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(required = false, defaultValue = "false") Boolean reportedOnly) {
        
        try {
            Page<Dynamic> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<Dynamic> queryWrapper = new LambdaQueryWrapper<>();

            // 审核状态筛选（使用Lambda字段，避免列名不匹配）
            if (auditStatus != null) {
                queryWrapper.eq(Dynamic::getAuditStatus, auditStatus);
            }

            // 按创建时间倒序（使用Lambda字段）
            queryWrapper.orderByDesc(Dynamic::getCreateTime);

            Page<Dynamic> result = dynamicMapper.selectPage(pageInfo, queryWrapper);

            // 标记是否被举报（容错：当举报表不存在或查询异常时降级为未举报，避免500）
            for (Dynamic d : result.getRecords()) {
                boolean exists = false;
                try {
                    exists = dynamicMapper.existsReportByDynamicId(d.getDynamicId());
                } catch (Exception ex) {
                    // 降级处理，保留接口正常返回
                    System.err.println("existsReportByDynamicId 查询异常: " + ex.getMessage());
                }
                d.setIsReported(exists);
            }

            // 批量查询用户昵称并回填
            try {
                Set<Integer> userIds = result.getRecords().stream()
                        .map(Dynamic::getUserId)
                        .filter(java.util.Objects::nonNull)
                        .collect(Collectors.toSet());
                if (!userIds.isEmpty()) {
                    java.util.List<java.util.Map<String, Object>> rows = dynamicMapper.findNicknamesByUserIds(new java.util.ArrayList<>(userIds));
                    Map<Integer, String> idToName = new 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) {
                            idToName.put(Integer.parseInt(uid.toString()), nick.toString());
                        }
                    }
                    for (Dynamic d : result.getRecords()) {
                        d.setUserNickname(idToName.get(d.getUserId()));
                    }
                }
            } catch (Exception ex) {
                System.err.println("批量查询用户昵称异常: " + ex.getMessage());
            }

            // 若仅查看被举报的动态，则进行内存过滤（保持改动最小化）
            if (Boolean.TRUE.equals(reportedOnly)) {
                java.util.List<Dynamic> filtered = new java.util.ArrayList<>();
                for (Dynamic d : result.getRecords()) {
                    if (Boolean.TRUE.equals(d.getIsReported())) {
                        filtered.add(d);
                    }
                }
                result.setRecords(filtered);
                result.setTotal(filtered.size());
            }

            // 组装封面图：优先按 JSON 数组解析，失败再按逗号分隔
            for (Dynamic d : result.getRecords()) {
                try {
                    String raw = d.getMediaUrls();
                    if (raw == null || raw.trim().isEmpty()) {
                        continue;
                    }
                    String first = null;
                    String urls = raw.trim();
                    if (urls.startsWith("[") && urls.endsWith("]")) {
                        ObjectMapper mapper = new ObjectMapper();
                        java.util.List<String> list = mapper.readValue(urls, new TypeReference<java.util.List<String>>(){});
                        if (list != null && !list.isEmpty()) {
                            first = list.get(0);
                        }
                    } else {
                        String[] arr = urls.split(",");
                        if (arr.length > 0) {
                            first = arr[0].trim();
                            // 去除可能包裹的引号
                            if ((first.startsWith("\"") && first.endsWith("\"")) || (first.startsWith("'") && first.endsWith("'"))) {
                                first = first.substring(1, first.length() - 1);
                            }
                        }
                    }
                    if (first != null && !first.isEmpty()) {
                        d.setCoverUrl(first);
                    }
                } catch (Exception ignore) {}
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 动态详情
     */
    @GetMapping("/detail/{dynamicId}")
    public Result<Dynamic> detail(@PathVariable Integer dynamicId) {
        try {
            Dynamic dynamic = dynamicMapper.selectById(dynamicId);
            if (dynamic == null) {
                return Result.error("动态不存在");
            }
            return Result.success(dynamic);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 审核动态
     */
    @PostMapping("/audit/{dynamicId}")
    public Result<String> audit(@PathVariable Integer dynamicId, @RequestBody Map<String, Object> params) {
        try {
            Dynamic dynamic = dynamicMapper.selectById(dynamicId);
            if (dynamic == null) {
                return Result.error("动态不存在");
            }
            
            Integer auditStatus = (Integer) params.get("auditStatus");
            if (auditStatus == null) {
                return Result.error("审核状态不能为空");
            }
            
            dynamic.setAuditStatus(auditStatus);
            dynamicMapper.updateById(dynamic);
            
            return Result.success("审核成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除动态
     */
    @DeleteMapping("/delete/{dynamicId}")
    public Result<String> delete(@PathVariable Integer dynamicId) {
        try {
            int rows = dynamicMapper.deleteById(dynamicId);
            if (rows > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("动态不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败：" + e.getMessage());
        }
    }
}

