package com.zhentao.controller;

import com.alibaba.excel.EasyExcel;
import com.zhentao.vo.MatchmakerExcelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

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

/**
 * 红娘管理控制器（管理端）
 */
@RestController
@RequestMapping("/admin/matchmaker")
@CrossOrigin(origins = "*")
public class MatchmakerController {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    /**
     * 导出红娘数据为Excel
     */
    @GetMapping("/export")
    public void exportMatchmakerList(
            HttpServletResponse response,
            @RequestParam(value = "matchmakerType", required = false) Integer matchmakerType,
            @RequestParam(value = "level", required = false) Integer level,
            @RequestParam(value = "keyword", required = false) String keyword) throws IOException {
        try {
            // 构建SQL查询
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT m.matchmaker_id, m.real_name, m.phone, m.matchmaker_type, ");
            sql.append("m.level, m.success_couples, m.status, m.created_at, ");
            sql.append("c.name as city_name ");
            sql.append("FROM matchmakers m ");
            sql.append("LEFT JOIN area c ON m.city_id = c.id ");
            sql.append("WHERE 1=1 ");
            
            // 类型筛选
            if (matchmakerType != null) {
                sql.append("AND m.matchmaker_type = ").append(matchmakerType).append(" ");
            }
            
            // 等级筛选
            if (level != null) {
                sql.append("AND m.level = ").append(level).append(" ");
            }
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                String kw = keyword.trim().replace("'", "''");
                sql.append("AND (m.real_name LIKE '%").append(kw).append("%' ");
                sql.append("OR m.phone LIKE '%").append(kw).append("%') ");
            }
            
            sql.append("ORDER BY m.created_at DESC");
            
            // 执行查询
            List<Map<String, Object>> results = jdbcTemplate.queryForList(sql.toString());
            
            // 转换为Excel VO
            List<MatchmakerExcelVO> excelData = results.stream()
                    .map(MatchmakerExcelVO::fromMap)
                    .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(), MatchmakerExcelVO.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() + "\"}");
        }
    }
}
