package com.zhentao.controller;

import com.alibaba.excel.EasyExcel;
import com.zhentao.common.Result;
import com.zhentao.entity.Activity;
import com.zhentao.entity.ActivityRegistration;
import com.zhentao.mapper.ActivityMapper;
import com.zhentao.service.ActivityRegistrationService;
import com.zhentao.vo.ActivityRegistrationExcelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 活动报名管理控制器
 */
@RestController
@RequestMapping("/admin/activity/registration")
@CrossOrigin(origins = "*")
public class ActivityRegistrationController {
    
    @Autowired
    private ActivityRegistrationService activityRegistrationService;
    
    @Autowired
    private ActivityMapper activityMapper;
    
    /**
     * 获取报名列表（分页）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getRegistrationList(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "activityId", required = false) Integer activityId,
            @RequestParam(value = "checkInStatus", required = false) Integer checkInStatus,
            @RequestParam(value = "paymentStatus", required = false) Integer paymentStatus,
            @RequestParam(value = "keyword", required = false) String keyword) {
        try {
            Map<String, Object> data = activityRegistrationService.getRegistrationList(
                    page, pageSize, activityId, checkInStatus, paymentStatus, keyword);
            
            // 如果有活动ID，获取活动名称
            if (activityId != null) {
                Activity activity = activityMapper.selectById(activityId);
                if (activity != null) {
                    data.put("activityName", activity.getName());
                }
            }
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取报名列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取报名统计数据
     * 报名总数：签到状态为已报名(status=1)的记录数
     * 已签到：签到状态为已签到(status=3)的记录数（从已报名中筛选）
     * 未签到：签到状态为已报名(status=1)但未签到(status≠3)的记录数
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getRegistrationStats(
            @RequestParam(value = "activityId", required = true) Integer activityId) {
        try {
            Map<String, Object> stats = activityRegistrationService.getRegistrationStats(activityId);
            return Result.success(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出报名数据为Excel
     */
    @GetMapping("/export")
    public void exportRegistrationList(
            HttpServletResponse response,
            @RequestParam(value = "activityId", required = false) Integer activityId,
            @RequestParam(value = "checkInStatus", required = false) Integer checkInStatus,
            @RequestParam(value = "paymentStatus", required = false) Integer paymentStatus,
            @RequestParam(value = "keyword", required = false) String keyword) throws IOException {
        try {
            // 查询所有符合条件的记录
            List<ActivityRegistration> registrations = activityRegistrationService.getAllRegistrations(
                    activityId, checkInStatus, paymentStatus, keyword);
            
            // 转换为Excel VO
            List<ActivityRegistrationExcelVO> excelData = registrations.stream()
                    .map(ActivityRegistrationExcelVO::fromEntity)
                    .collect(Collectors.toList());
            
            // 设置响应头
            String fileName = "活动报名列表_" + System.currentTimeMillis() + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
            
            // 写入Excel
            EasyExcel.write(response.getOutputStream(), ActivityRegistrationExcelVO.class)
                    .sheet("报名列表")
                    .doWrite(excelData);
            
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
        }
    }
}

