package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.Matchmaker;
import com.zhentao.entity.MatchmakerSuccessCaseUpload;
import com.zhentao.mapper.MatchmakerMapper;
import com.zhentao.service.MatchmakerSuccessCaseUploadService;
import com.zhentao.vo.MatchmakerSuccessCaseUploadVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 红娘成功案例审核控制器
 */
@RestController
@RequestMapping("/admin/success-case-upload")
@CrossOrigin(origins = "*")
public class MatchmakerSuccessCaseUploadController {

    @Autowired
    private MatchmakerSuccessCaseUploadService successCaseUploadService;

    @Autowired
    private MatchmakerMapper matchmakerMapper;

    /**
     * 案例列表（分页查询）
     * 支持按男方姓名、女方姓名模糊查询，按审核状态筛选
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "maleRealName", required = false) String maleRealName,
            @RequestParam(value = "femaleRealName", required = false) String femaleRealName,
            @RequestParam(value = "auditStatus", required = false) Integer auditStatus) {
        try {
            Page<MatchmakerSuccessCaseUpload> pageInfo = new Page<>(page, pageSize);
            QueryWrapper<MatchmakerSuccessCaseUpload> queryWrapper = new QueryWrapper<>();

            // 男方姓名模糊查询
            if (maleRealName != null && !maleRealName.trim().isEmpty()) {
                queryWrapper.like("male_real_name", maleRealName.trim());
            }

            // 女方姓名模糊查询
            if (femaleRealName != null && !femaleRealName.trim().isEmpty()) {
                queryWrapper.like("female_real_name", femaleRealName.trim());
            }

            // 审核状态筛选
            if (auditStatus != null) {
                queryWrapper.eq("audit_status", auditStatus);
            }

            // 按创建时间倒序
            queryWrapper.orderByDesc("created_at");

            Page<MatchmakerSuccessCaseUpload> result = successCaseUploadService.page(pageInfo, queryWrapper);

            // 转换为VO列表
            List<MatchmakerSuccessCaseUploadVO> voList = new ArrayList<>();
            for (MatchmakerSuccessCaseUpload upload : result.getRecords()) {
                MatchmakerSuccessCaseUploadVO vo = convertToVO(upload);
                voList.add(vo);
            }

            Map<String, Object> data = new HashMap<>();
            data.put("list", voList);
            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("/{id}")
    public Result<MatchmakerSuccessCaseUploadVO> detail(@PathVariable Long id) {
        try {
            MatchmakerSuccessCaseUpload upload = successCaseUploadService.getById(id);
            if (upload == null) {
                return Result.error("案例不存在");
            }
            
            MatchmakerSuccessCaseUploadVO vo = convertToVO(upload);
            return Result.success(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取案例详情失败：" + e.getMessage());
        }
    }

    /**
     * 审核通过
     * 审核通过时，根据points_reward字段的值给对应红娘增加积分
     * 支持可选的auditRemark参数
     */
    @PostMapping("/approve/{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> approve(@PathVariable Long id, @RequestBody(required = false) Map<String, String> request) {
        try {
            MatchmakerSuccessCaseUpload upload = successCaseUploadService.getById(id);
            if (upload == null) {
                return Result.error("案例不存在");
            }

            // 根据matchmakerId查找红娘并增加积分
            if (upload.getMatchmakerId() != null) {
                // 获取积分奖励值，如果为null或小于等于0则不增加积分
                Integer pointsReward = upload.getPointsReward();
                if (pointsReward != null && pointsReward > 0) {
                    Matchmaker matchmaker = matchmakerMapper.selectById(upload.getMatchmakerId());
                    if (matchmaker != null) {
                        // 获取当前积分，如果为null则默认为0
                        Integer currentPoints = matchmaker.getPoints() != null ? matchmaker.getPoints() : 0;
                        // 积分加上pointsReward的值
                        matchmaker.setPoints(currentPoints + pointsReward);
                        // 更新红娘积分
                        matchmakerMapper.updateById(matchmaker);
                    } else {
                        return Result.error("红娘信息不存在");
                    }
                }
            }

            upload.setAuditStatus(1); // 审核通过
            // 如果提供了auditRemark，则设置
            if (request != null && request.containsKey("auditRemark")) {
                String auditRemark = request.get("auditRemark");
                if (auditRemark != null && !auditRemark.trim().isEmpty()) {
                    upload.setAuditRemark(auditRemark.trim());
                }
            }
            upload.setAuditedAt(new Date());
            upload.setUpdatedAt(new Date());

            boolean success = successCaseUploadService.updateById(upload);
            if (success) {
                Integer pointsReward = upload.getPointsReward();
                if (pointsReward != null && pointsReward > 0) {
                    return Result.success("审核通过成功，已为红娘增加" + pointsReward + "积分");
                } else {
                    return Result.success("审核通过成功");
                }
            } else {
                return Result.error("审核通过失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审核通过失败：" + e.getMessage());
        }
    }

    /**
     * 审核不通过
     */
    @PostMapping("/reject/{id}")
    public Result<String> reject(@PathVariable Long id, @RequestBody Map<String, String> request) {
        try {
            MatchmakerSuccessCaseUpload upload = successCaseUploadService.getById(id);
            if (upload == null) {
                return Result.error("案例不存在");
            }

            String auditRemark = request.get("auditRemark");
            if (auditRemark == null || auditRemark.trim().isEmpty()) {
                return Result.error("审核备注不能为空");
            }

            upload.setAuditStatus(2); // 审核失败
            upload.setAuditRemark(auditRemark.trim());
            upload.setAuditedAt(new Date());
            upload.setUpdatedAt(new Date());

            boolean success = successCaseUploadService.updateById(upload);
            if (success) {
                return Result.success("审核不通过操作成功");
            } else {
                return Result.error("审核不通过操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审核不通过操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 转换为VO对象
     */
    private MatchmakerSuccessCaseUploadVO convertToVO(MatchmakerSuccessCaseUpload upload) {
        MatchmakerSuccessCaseUploadVO vo = new MatchmakerSuccessCaseUploadVO();
        BeanUtils.copyProperties(upload, vo);
        
        // 计算审核耗时（审核时间 - 上传时间）
        vo.setAuditDuration(calculateAuditDuration(upload.getAuditedAt(), upload.getCreatedAt()));
        
        return vo;
    }
    
    /**
     * 计算审核耗时（审核时间 - 上传时间）
     */
    private String calculateAuditDuration(Date auditedAt, Date createdAt) {
        if (auditedAt == null || createdAt == null) {
            return "-";
        }
        
        try {
            Instant auditInstant = auditedAt.toInstant();
            Instant createInstant = createdAt.toInstant();
            Duration duration = Duration.between(createInstant, auditInstant);
            
            return formatDuration(duration);
        } catch (Exception e) {
            return "-";
        }
    }
    
    /**
     * 格式化时间差为可读字符串
     */
    private String formatDuration(Duration duration) {
        long totalSeconds = duration.getSeconds();
        if (totalSeconds < 0) {
            return "-";
        }
        
        long days = totalSeconds / 86400;
        long hours = (totalSeconds % 86400) / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;
        
        StringBuilder sb = new StringBuilder();
        if (days > 0) {
            sb.append(days).append("天");
        }
        if (hours > 0) {
            sb.append(hours).append("小时");
        }
        if (minutes > 0) {
            sb.append(minutes).append("分钟");
        }
        if (seconds > 0 && days == 0 && hours == 0) {
            sb.append(seconds).append("秒");
        }
        
        return sb.length() > 0 ? sb.toString() : "0秒";
    }
}

