package com.ym.mec.web.controller;

import com.ym.mec.biz.dal.dao.QuestionnaireQuestionDao;
import com.ym.mec.biz.dal.dao.QuestionnaireTopicDao;
import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityDto;
import com.ym.mec.biz.dal.entity.QuestionnaireQuestion;
import com.ym.mec.biz.dal.entity.QuestionnaireTopic;
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.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.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

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

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

    @ApiOperation(value = "添加调查问卷（非活动）")
    @RequestMapping("/add")
    public Object queryPage(@RequestBody ReplacementInstrumentActivityDto replacementInstrumentActivity) {
        questionnaireUserResultService.addResult(replacementInstrumentActivity);
        return succeed();
    }

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

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

    @ApiOperation(value = "导出")
    @RequestMapping("/export")
    @PreAuthorize("@pcs.hasPermissions('questionnaireUserResult/export')")
    public void questionnaireUserResultExport(Integer topicId, HttpServletResponse response) throws Exception {
        QuestionnaireTopic topic = questionnaireTopicDao.get(topicId);
        List<QuestionnaireQuestion> questionList = questionnaireQuestionDao.findByTopicId(topicId);
        questionList.removeAll(Collections.singleton(null));
        String[] header = questionnaireUserResultService.getExportHeader(topic,questionList);
        Map<String,Object> resultMap = questionnaireUserResultService.getExportBody(topic,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();
                }
            }
        }
    }
}
