package com.fs.survey;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.survey.domain.SurveyFieldConfig;
import com.fs.survey.mapper.SurveyFieldConfigMapper;
import com.fs.survey.service.ISurveyDataService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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;

/**
 * 问卷数据Controller
 *
 */
@RestController
@RequestMapping("/survey/data")
public class SurveyDataController extends BaseController {

    @Autowired
    private ISurveyDataService surveyDataService;

    @Autowired
    private SurveyFieldConfigMapper fieldConfigMapper;

    /**
     * 查询问卷数据列表
     */
    @PreAuthorize("@ss.hasPermi('survey:data:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        startPage();
        List<Map<String, Object>> list = surveyDataService.selectSurveyDataList(params);
        return getDataTable(list);
    }

    /**
     * 获取问卷数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('survey:data:query')")
    @GetMapping(value = "/{versionId}/{id}")
    public AjaxResult getInfo(@PathVariable("versionId") Long versionId, @PathVariable("id") Long id) {
        return AjaxResult.success(surveyDataService.selectSurveyDataById(versionId, id));
    }

    /**
     * 提交问卷数据
     */
    @Log(title = "提交问卷", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody Map<String, Object> data) {
        return toAjax(surveyDataService.submitSurveyData(data));
    }

    /**
     * 修改问卷数据
     */
    @PreAuthorize("@ss.hasPermi('survey:data:edit')")
    @Log(title = "问卷数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String, Object> data) {
        return toAjax(surveyDataService.updateSurveyData(data));
    }

    /**
     * 删除问卷数据
     */
    @PreAuthorize("@ss.hasPermi('survey:data:remove')")
    @Log(title = "问卷数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{versionId}/{ids}")
    public AjaxResult remove(@PathVariable Long versionId, @PathVariable Long[] ids) {
        return toAjax(surveyDataService.deleteSurveyDataByIds(versionId, ids));
    }

    /**
     * 导出问卷数据
     */
    @PreAuthorize("@ss.hasPermi('survey:data:export')")
    @Log(title = "问卷数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestParam Map<String, Object> params) throws IOException {
        Long versionId = Long.parseLong(params.get("versionId").toString());

        // 获取字段配置（isExport=1 的列）
        List<SurveyFieldConfig> fieldConfigs = fieldConfigMapper.selectFieldConfigByVersionId(versionId);
        fieldConfigs.removeIf(f -> f.getIsExport() == null || f.getIsExport() != 1);

        // 查询全量数据（不分页）
        List<Map<String, Object>> dataList = surveyDataService.selectSurveyDataList(params);

        // 构建 Excel
        SXSSFWorkbook wb = new SXSSFWorkbook(500);
        Sheet sheet = wb.createSheet("问卷数据");

        // 表头样式
        CellStyle headerStyle = wb.createCellStyle();
        Font headerFont = wb.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 写表头
        Row headerRow = sheet.createRow(0);
        int colIdx = 0;
        for (SurveyFieldConfig fc : fieldConfigs) {
            Cell cell = headerRow.createCell(colIdx++);
            cell.setCellValue(fc.getFieldLabel());
            cell.setCellStyle(headerStyle);
        }
        headerRow.createCell(colIdx++).setCellValue("提交时间");
        headerRow.createCell(colIdx).setCellValue("提交人");

        // 写数据行
        for (int i = 0; i < dataList.size(); i++) {
            Map<String, Object> row = dataList.get(i);
            Row dataRow = sheet.createRow(i + 1);
            int ci = 0;
            for (SurveyFieldConfig fc : fieldConfigs) {
                Object val = row.get(fc.getFieldKey());
                String displayVal = formatExportValue(val, fc);
                dataRow.createCell(ci++).setCellValue(displayVal);
            }
            Object submitTime = row.get("submit_time");
            dataRow.createCell(ci++).setCellValue(submitTime == null ? "" : submitTime.toString());
            Object userName = row.get("user_name");
            dataRow.createCell(ci).setCellValue(userName == null ? "" : userName.toString());
        }

        // 输出
        String fileName = URLEncoder.encode("问卷数据", "UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename*=utf-8''" + fileName + ".xlsx");
        wb.write(response.getOutputStream());
        wb.dispose();
    }

    /** 导出时将字段值转换为可读文本 */
    private String formatExportValue(Object val, SurveyFieldConfig fc) {
        if (val == null) return "";
        String strVal = val.toString();
        if (strVal.isEmpty()) return "";

        // 有选项配置的字段，转换 value -> label
        if (fc.getOptionsJson() != null && !fc.getOptionsJson().isEmpty()) {
            try {
                JSONArray options = JSONArray.parseArray(fc.getOptionsJson());
                // 尝试多选（JSON数组）
                if (strVal.startsWith("[")) {
                    JSONArray selected = JSONArray.parseArray(strVal);
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < selected.size(); i++) {
                        String sv = selected.get(i).toString();
                        String label = findLabel(options, sv);
                        if (i > 0) sb.append(", ");
                        sb.append(label);
                    }
                    return sb.toString();
                }
                return findLabel(options, strVal);
            } catch (Exception ignored) {}
        }
        return strVal;
    }

    private String findLabel(JSONArray options, String value) {
        for (int i = 0; i < options.size(); i++) {
            JSONObject opt = options.getJSONObject(i);
            if (value.equals(opt.getString("value"))) {
                return opt.getString("label");
            }
        }
        return value;
    }

    /**
     * 数据统计
     */
    @PreAuthorize("@ss.hasPermi('survey:data:statistics')")
    @GetMapping("/statistics/{versionId}")
    public AjaxResult statistics(@PathVariable Long versionId) {
        return AjaxResult.success(surveyDataService.getStatistics(versionId));
    }
}
