package com.ym.mec.web.controller;

import com.ym.mec.biz.dal.dao.QuestionnaireQuestionDao;
import com.ym.mec.biz.dal.entity.QuestionnaireQuestion;
import com.ym.mec.biz.dal.page.QuestionnaireUserResultQueryInfo;
import com.ym.mec.biz.service.QuestionnaireUserResultService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.QueryInfo;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.excel.POIUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.json.JSONObject;
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.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("questionnaireUserResult")
@Api(tags = "问题答案")
@RestController
public class QuestionnaireUserResultController extends BaseController {

    @Autowired
    private QuestionnaireUserResultService questionnaireUserResultService;
    @Autowired
    private QuestionnaireQuestionDao questionnaireQuestionDao;

    @ApiOperation(value = "分页查询")
    @GetMapping("/queryPage")
    @PreAuthorize("@pcs.hasPermissions('questionnaireUserResult/queryPage')")
    public Object queryPage(QuestionnaireUserResultQueryInfo queryInfo) {
        return succeed(questionnaireUserResultService.queryDetailPage(queryInfo));
    }

    @ApiOperation(value = "导出")
    @RequestMapping("/export")
    @PreAuthorize("@pcs.hasPermissions('questionnaireUserResult/export')")
    public void questionnaireUserResultExport(Integer cooperationId, HttpServletResponse response) throws Exception {
        List<QuestionnaireQuestion> questionList = questionnaireQuestionDao.queryQuestionList(cooperationId);
        questionList.removeAll(Collections.singleton(null));
        if(questionList != null && questionList.size() > 0){
            List<String> column = new ArrayList<>();
            column.add("活动编号");
            column.add("学员编号");
            column.add("学员姓名");
            column.add("手机号");
            List<String> collect = questionList.stream().map(e -> e.getContent()).collect(Collectors.toList());
            column.addAll(collect);
            String[] header = column.toArray(new String[column.size()]);
            Map<String,Object> resultMap = questionnaireUserResultService.questionnaireUserResultExport(cooperationId,questionList);
            List<Map<String,Object>> jsonObjectList = (List<Map<String,Object>>)resultMap.get("jsonObjectList");
            if(jsonObjectList.size() == 0){
                throw new BizException("暂无可导出数据");
            }
            OutputStream outputStream = response.getOutputStream();
            HSSFWorkbook workbook = null;
            try {
                Set<String> body1 = (Set<String>)resultMap.get("body");
                String[] body = body1.toArray(new String[body1.size()]);
                workbook = POIUtil.exportExcel(header, body, jsonObjectList);
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=replacement-" + DateUtil.getDate(new Date()) + ".xls");
                response.flushBuffer();
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
                outputStream.flush();
                workbook.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        workbook.close();
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            throw new BizException("暂无可导出数据");
        }
    }
}
