package com.zhentao.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhentao.dto.SuccessCaseUploadDTO;
import com.zhentao.entity.MatchmakerSuccessCaseUpload;
import com.zhentao.service.MatchmakerSuccessCaseUploadService;
import com.zhentao.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成功案例上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/success-case-upload")
public class SuccessCaseUploadController {

    @Autowired
    private MatchmakerSuccessCaseUploadService successCaseUploadService;

    @Autowired
    private com.zhentao.mapper.MatchmakerSuccessCaseUploadMapper successCaseUploadMapper;

    @Autowired
    private MinioUtil minioUtil;

    @Value("${minio.proofBucketName:Proof-of-success}")
    private String proofBucketName;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 上传成功凭证图片
     * @param file 图片文件
     * @return 图片URL
     */
    @PostMapping("/upload-image")
    public ResponseEntity<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (file.isEmpty()) {
                result.put("code", 400);
                result.put("message", "请选择要上传的图片");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                result.put("code", 400);
                result.put("message", "只能上传图片文件");
                return ResponseEntity.badRequest().body(result);
            }

            // 上传到MinIO的Proof-of-success桶
            String imageUrl = minioUtil.uploadFileToProofBucket(
                    file.getBytes(),
                    file.getOriginalFilename(),
                    contentType
            );

            result.put("code", 200);
            result.put("message", "上传成功");
            result.put("data", imageUrl);
            log.info("成功凭证图片上传成功: {}", imageUrl);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("图片上传失败", e);
            result.put("code", 500);
            result.put("message", "图片上传失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 提交成功案例
     * @param dto 成功案例数据
     * @return 提交结果
     */
    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitSuccessCase(@RequestBody SuccessCaseUploadDTO dto) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 参数校验
            if (dto.getMatchmakerId() == null) {
                result.put("code", 400);
                result.put("message", "红娘ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            if (dto.getMaleUserId() == null) {
                result.put("code", 400);
                result.put("message", "请选择男方用户");
                return ResponseEntity.badRequest().body(result);
            }
            if (dto.getFemaleUserId() == null) {
                result.put("code", 400);
                result.put("message", "请选择女方用户");
                return ResponseEntity.badRequest().body(result);
            }
            if (dto.getMaleUserId().equals(dto.getFemaleUserId())) {
                result.put("code", 400);
                result.put("message", "男方和女方不能是同一人");
                return ResponseEntity.badRequest().body(result);
            }
            if (dto.getMaleRealName() == null || dto.getMaleRealName().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "请填写男方真实姓名");
                return ResponseEntity.badRequest().body(result);
            }
            if (dto.getFemaleRealName() == null || dto.getFemaleRealName().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "请填写女方真实姓名");
                return ResponseEntity.badRequest().body(result);
            }
            if (dto.getProofImages() == null || dto.getProofImages().isEmpty()) {
                result.put("code", 400);
                result.put("message", "请上传至少一张成功凭证图片");
                return ResponseEntity.badRequest().body(result);
            }
            if (dto.getCaseType() == null || (dto.getCaseType() != 1 && dto.getCaseType() != 2)) {
                result.put("code", 400);
                result.put("message", "请选择案例类型（订婚或结婚）");
                return ResponseEntity.badRequest().body(result);
            }

            // 构建实体
            MatchmakerSuccessCaseUpload upload = new MatchmakerSuccessCaseUpload();
            upload.setMatchmakerId(dto.getMatchmakerId());
            upload.setMaleUserId(dto.getMaleUserId());
            upload.setFemaleUserId(dto.getFemaleUserId());
            upload.setMaleRealName(dto.getMaleRealName().trim());
            upload.setFemaleRealName(dto.getFemaleRealName().trim());
            
            // 将图片列表转为JSON字符串
            upload.setProofImages(objectMapper.writeValueAsString(dto.getProofImages()));
            upload.setCaseType(dto.getCaseType());
            
            // 解析日期
            if (dto.getCaseDate() != null && !dto.getCaseDate().isEmpty()) {
                upload.setCaseDate(LocalDate.parse(dto.getCaseDate(), DateTimeFormatter.ISO_LOCAL_DATE));
            }

            // 保存
            boolean success = successCaseUploadService.submitSuccessCase(upload);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "提交成功，请等待审核");
                result.put("data", upload.getId());
                log.info("成功案例提交成功: id={}, matchmakerId={}", upload.getId(), upload.getMatchmakerId());
            } else {
                result.put("code", 500);
                result.put("message", "提交失败，请稍后重试");
            }
            
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("提交成功案例失败", e);
            result.put("code", 500);
            result.put("message", "提交失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取红娘的成功案例列表
     * @param matchmakerId 红娘ID
     * @return 成功案例列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getSuccessCaseList(
            @RequestParam Integer matchmakerId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        try {
            var page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<MatchmakerSuccessCaseUpload>(pageNum, pageSize);
            var queryWrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MatchmakerSuccessCaseUpload>();
            queryWrapper.eq(MatchmakerSuccessCaseUpload::getMatchmakerId, matchmakerId)
                    .orderByDesc(MatchmakerSuccessCaseUpload::getCreatedAt);
            
            var pageResult = successCaseUploadService.page(page, queryWrapper);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", pageResult);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("查询成功案例列表失败", e);
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取审核记录列表（用于消息通知页面）
     * @param matchmakerId 红娘ID
     * @param auditStatus 审核状态筛选（可选）：0-待审核 1-审核通过 2-审核失败 3-核实中
     * @return 审核记录列表
     */
    @GetMapping("/audit-records")
    public ResponseEntity<Map<String, Object>> getAuditRecords(
            @RequestParam Integer matchmakerId,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        try {
            var page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<MatchmakerSuccessCaseUpload>(pageNum, pageSize);
            var queryWrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MatchmakerSuccessCaseUpload>();
            queryWrapper.eq(MatchmakerSuccessCaseUpload::getMatchmakerId, matchmakerId);
            
            // 如果指定了审核状态，则筛选
            if (auditStatus != null) {
                queryWrapper.eq(MatchmakerSuccessCaseUpload::getAuditStatus, auditStatus);
            }
            
            // 按创建时间降序
            queryWrapper.orderByDesc(MatchmakerSuccessCaseUpload::getCreatedAt);
            
            var pageResult = successCaseUploadService.page(page, queryWrapper);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", pageResult);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("查询审核记录列表失败", e);
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取审核记录详情（包含男女双方用户信息）
     * @param id 记录ID
     * @return 记录详情
     */
    @GetMapping("/audit-records/{id}")
    public ResponseEntity<Map<String, Object>> getAuditRecordDetail(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            MatchmakerSuccessCaseUpload record = successCaseUploadService.getById(id);
            if (record == null) {
                result.put("code", 404);
                result.put("message", "记录不存在");
                return ResponseEntity.ok(result);
            }
            
            // 构建返回数据，包含案例信息和用户信息
            Map<String, Object> data = new HashMap<>();
            data.put("id", record.getId());
            data.put("matchmakerId", record.getMatchmakerId());
            data.put("maleUserId", record.getMaleUserId());
            data.put("femaleUserId", record.getFemaleUserId());
            data.put("maleRealName", record.getMaleRealName());
            data.put("femaleRealName", record.getFemaleRealName());
            data.put("proofImages", record.getProofImages());
            data.put("caseType", record.getCaseType());
            data.put("caseDate", record.getCaseDate());
            data.put("auditStatus", record.getAuditStatus());
            data.put("auditRemark", record.getAuditRemark());
            data.put("pointsReward", record.getPointsReward());
            data.put("cashReward", record.getCashReward());
            data.put("rewardStatus", record.getRewardStatus());
            data.put("createdAt", record.getCreatedAt());
            data.put("auditedAt", record.getAuditedAt());
            data.put("isRead", record.getIsRead());
            
            // 查询男方用户信息
            if (record.getMaleUserId() != null) {
                Map<String, Object> maleUserInfo = successCaseUploadMapper.getUserBasicInfo(record.getMaleUserId());
                if (maleUserInfo != null) {
                    data.put("maleUserInfo", maleUserInfo);
                }
            }
            
            // 查询女方用户信息
            if (record.getFemaleUserId() != null) {
                Map<String, Object> femaleUserInfo = successCaseUploadMapper.getUserBasicInfo(record.getFemaleUserId());
                if (femaleUserInfo != null) {
                    data.put("femaleUserInfo", femaleUserInfo);
                }
            }
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", data);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("查询审核记录详情失败", e);
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 标记审核记录为已读
     * @param id 记录ID
     * @return 操作结果
     */
    @PostMapping("/audit-records/{id}/read")
    public ResponseEntity<Map<String, Object>> markAsRead(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            MatchmakerSuccessCaseUpload record = successCaseUploadService.getById(id);
            if (record == null) {
                result.put("code", 404);
                result.put("message", "记录不存在");
                return ResponseEntity.ok(result);
            }
            
            // 标记为已读
            record.setIsRead(1);
            boolean success = successCaseUploadService.updateById(record);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "标记成功");
            } else {
                result.put("code", 500);
                result.put("message", "标记失败");
            }
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("标记已读失败", e);
            result.put("code", 500);
            result.put("message", "操作失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取未读审核记录数量
     * @param matchmakerId 红娘ID
     * @return 未读数量
     */
    @GetMapping("/audit-records/unread-count")
    public ResponseEntity<Map<String, Object>> getUnreadCount(@RequestParam Integer matchmakerId) {
        Map<String, Object> result = new HashMap<>();
        try {
            var queryWrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MatchmakerSuccessCaseUpload>();
            queryWrapper.eq(MatchmakerSuccessCaseUpload::getMatchmakerId, matchmakerId)
                    .and(w -> w.isNull(MatchmakerSuccessCaseUpload::getIsRead)
                            .or()
                            .eq(MatchmakerSuccessCaseUpload::getIsRead, 0))
                    // 只统计已审核完成的（审核通过或审核失败）
                    .in(MatchmakerSuccessCaseUpload::getAuditStatus, 1, 2);
            
            long count = successCaseUploadService.count(queryWrapper);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", count);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("查询未读数量失败", e);
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
