package com.zjty.automatedtesting.controller;

import com.google.common.collect.ImmutableMap;
import com.zjty.automatedtesting.pojo.report.ReportVo;
import com.zjty.automatedtesting.service.ReportService;
import com.zjty.automatedtesting.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Slf4j
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@RequestMapping("/report")
@RestController
@Api(tags = "测试报告")
@CrossOrigin
public class ReportController {

    @Autowired
    ReportService reportService;

    @ApiOperation(value = "获取全部测试报告.")
    @GetMapping(value = "/get")
    public ResponseEntity<List<ReportVo>> get() {
        return ResponseEntity.ok(reportService.findAll());
    }

    @ApiOperation(value = "按分页获取测试报告.页码从0开始.")
    @GetMapping(value = "/get/page/{page}")
    public ResponseEntity<List<ReportVo>> get(@PathVariable Integer page) {
        return ResponseEntity.ok(reportService.findByPage(page));
    }

    @ApiOperation(value = "获取单个测试报告.")
    @GetMapping(value = "/get/{id}")
    public ResponseEntity<ReportVo> getById(@PathVariable Integer id) {
        return ResponseEntity.ok(reportService.findById(id));
    }

    @ApiOperation(value = "删除测试报告.")
    @DeleteMapping(value = "/delete/{id}")
    public ResponseEntity<Map<String, String>> delete(@PathVariable Integer id) {
        reportService.delete(id);
        return ResponseEntity.ok(ImmutableMap.of("message", "success"));
    }

    @ApiOperation(value = "下载测试报告.")
    @GetMapping(value = "/download/{id}")
    public ResponseEntity<Map<String, String>> download(@PathVariable Integer id, HttpServletResponse response) {
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            String filename = "report-" + id.toString() + ".html";
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            OutputStream os = response.getOutputStream();
            String reportHtmlContent = FileUtil.getRepotHtmlContent(reportService.findById(id));
            FileUtil.output(reportHtmlContent, os);
        } catch (Exception e) {
            log.error("error:" + e);
            return ResponseEntity.ok(ImmutableMap.of("message", "error:" + e.getMessage()));
        }
        return ResponseEntity.ok(null);
    }
}
