package com.zhentao.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.MarrApply;
import com.zhentao.service.MarrApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 红娘申请审核
 */
@RestController
@RequestMapping("/admin/marr-apply")
@CrossOrigin(origins = "*")
public class MarrApplyControllor {

    @Autowired
    private MarrApplyService marrApplyService;

    /**
     * 红娘申请列表（可按姓名/手机号模糊查询，按创建时间倒序）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                            @RequestParam(value = "name", required = false) String name,
                                            @RequestParam(value = "phone", required = false) String phone,
                                            @RequestParam(value = "status", required = false) Integer status) {
        try {
            Page<MarrApply> pageData = marrApplyService.pageQuery(page, pageSize, name, phone, status);
            Map<String, Object> data = new HashMap<>();
            data.put("list", pageData.getRecords());
            data.put("total", pageData.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询红娘申请失败：" + e.getMessage());
        }
    }

    /**
     * 审核：支持同意或不同意，必须填写审核原因
     */
    @PostMapping("/approve/{applyId}")
    public Result<String> approve(@PathVariable Long applyId, 
                                  @RequestParam Integer userId,
                                  @RequestParam Boolean approved,
                                  @RequestParam String reason) {
        try {
            if (reason == null || reason.trim().isEmpty()) {
                return Result.error("审核原因不能为空");
            }
            boolean success = marrApplyService.approve(applyId, userId, approved, reason.trim());
            if (success) {
                String message = approved ? "审核通过成功" : "审核不通过成功";
                return Result.success(message);
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量审核
     */
    @PostMapping("/batch-approve")
    public Result<String> batchApprove(@RequestBody Map<String, Object> params) {
        try {
            // 安全地转换 applyIds，兼容 Integer 和 Long
            @SuppressWarnings("unchecked")
            List<?> applyIdsRaw = (List<?>) params.get("applyIds");
            List<Long> applyIds = new ArrayList<>();
            if (applyIdsRaw != null) {
                for (Object id : applyIdsRaw) {
                    if (id instanceof Integer) {
                        applyIds.add(((Integer) id).longValue());
                    } else if (id instanceof Long) {
                        applyIds.add((Long) id);
                    } else if (id instanceof Number) {
                        applyIds.add(((Number) id).longValue());
                    } else {
                        applyIds.add(Long.parseLong(id.toString()));
                    }
                }
            }
            Boolean approved = (Boolean) params.get("approved");
            String reason = (String) params.get("reason");
            
            if (applyIds == null || applyIds.isEmpty()) {
                return Result.error("申请ID列表不能为空");
            }
            if (approved == null) {
                return Result.error("审核结果不能为空");
            }
            if (reason == null || reason.trim().isEmpty()) {
                return Result.error("审核原因不能为空");
            }
            
            boolean success = marrApplyService.batchApprove(applyIds, approved, reason.trim());
            if (success) {
                String message = approved ? "批量审核通过成功" : "批量审核不通过成功";
                return Result.success(message);
            } else {
                return Result.error("批量审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量审核失败：" + e.getMessage());
        }
    }

    /**
     * 删除申请
     */
    @DeleteMapping("/delete/{applyId}")
    public Result<String> delete(@PathVariable Long applyId) {
        try {
            boolean success = marrApplyService.delete(applyId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败：" + e.getMessage());
        }
    }
}
