package com.tykj.dev.device.finalcheck.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.finalcheck.entity.domain.FinalDetail;
import com.tykj.dev.device.finalcheck.entity.domain.FinalReport;
import com.tykj.dev.device.finalcheck.entity.dto.TimeParam;
import com.tykj.dev.device.finalcheck.entity.vo.*;
import com.tykj.dev.device.finalcheck.service.FinalCheckService;
import com.tykj.dev.misc.base.ResultObj;
import com.tykj.dev.misc.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tykj.dev.misc.utils.TimestampUtil.localDateToDate;

/**
 * finalCheckController.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2020/9/24 at 6:24 下午
 */
@Slf4j
@AutoDocument
@RestController
@RequestMapping("/check/final")
@Api(tags = "决算模块", description = "决算模块", position = 2)
public class FinalCheckController {

    @Autowired
    private FinalCheckService fcService;

    @PostMapping("/reports/list")
    @ApiOperation(value = "查询所有决算报告(不附带详情数据)")
    public Page<FinalReportVo> findAllReports(
            @RequestBody FinalReportSelectVo finalReportSelectVo) {
        return fcService.findAllWithoutDetail(finalReportSelectVo);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询决算报告(附带详情数据)")
    public ResponseEntity<ResultObj<FinalReportVo>> findReportById(@PathVariable Integer id) {
        return ResultUtil.success(fcService.findReportById(id));
    }

    @PostMapping("/reports")
    @ApiOperation(value = "生成决算报告")
    public ResponseEntity<ResultObj<FinalReportVo>> generateReport(@RequestBody TimeParam time) {
        FinalReportVo finalReportVo = fcService.generateReport(time.getStartTime(),
                time.getEndTime(),time.getSendFileList());
        return ResultUtil.success(finalReportVo);
    }

    @PostMapping("/excel/{id}")
    @ApiOperation(value = "根据id导出对应的excel数据")
    public ResponseEntity<byte[]> exportExcel(
            @PathVariable Integer id,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        FinalReportVo reportVo = fcService.findReportById(id);


        TemplateExportParams params = new TemplateExportParams();
        Map<String, Object> map = new HashMap<>(16);
        map.put("name", reportVo.getName());
        map.put("unitName", reportVo.getUnitName());
        map.put("startTime", localDateToDate(reportVo.getStartTime()));
        map.put("endTime", localDateToDate(reportVo.getEndTime()));
        map.put("reportTime", localDateToDate(reportVo.getReportTime().toLocalDate()));

        List<Map<String, String>> listMap = new ArrayList<>();
        for (int i = 0; i < reportVo.getDetails().size(); i++) {
            Map<String, String> lm = new HashMap<>(16);
            FinalDetailVo detail = reportVo.getDetails().get(i);
            lm.put("order", i + 1 + "");
            lm.put("model", detail.getModel());
            lm.put("type", detail.getType() + "");
            lm.put("vertical", detail.getVertical() + "");
            lm.put("horizontal", detail.getHorizontal() + "");
            lm.put("commission", detail.getCommission() + "");
            lm.put("other", detail.getOther() + "");
            lm.put("total", detail.getTotal() + "");
            lm.put("hosting", detail.getHosting() + "");
            lm.put("received", detail.getReceived() + "");
            lm.put("sending", detail.getSending() + "");
            lm.put("scrapped", detail.getScrapped() + "");
            listMap.add(lm);
        }

        int defaultSize = 15;
        if (listMap.size() <= defaultSize) {
            for (int i = 0; i < defaultSize - listMap.size(); i++) {
                Map<String, String> lm = new HashMap<>(16);
                lm.put("order", " ");
                lm.put("model", " ");
                lm.put("type", " ");
                lm.put("vertical", " ");
                lm.put("horizontal", " ");
                lm.put("commission", " ");
                lm.put("other", " ");
                lm.put("total", " ");
                lm.put("hosting", " ");
                lm.put("received", " ");
                lm.put("sending", " ");
                lm.put("scrapped", " ");
                listMap.add(lm);
            }
        }

        map.put("list", listMap);
        params.setTemplateUrl("excelTemplate/finalCheck.xlsx");

        Workbook book = ExcelExportUtil.exportExcel(params, map);

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        book.write(outByteStream);

        HttpHeaders header = new HttpHeaders();
        header.setContentDispositionFormData("attachment", "Report.xls");

        return ResponseEntity.ok()
                .headers(header)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(outByteStream.toByteArray());
    }

    @PostMapping("/reports/addRemake")
    @ApiOperation(value = "根据备注添加")
    public ResponseEntity addRemake(@RequestBody FinalRemakeVo finalRemakeVo) {
        FinalDetail finalDetail = fcService.addRemake(finalRemakeVo);
        return ResponseEntity.ok(finalDetail);
    }

    @PostMapping("/reports/uploadFile")
    @ApiOperation(value = "上传单据")
    public ResponseEntity uploadFile(@RequestBody FileVo fileVo) {
        FinalReport finalReport = fcService.uploadFile(fileVo);
        return ResponseEntity.ok(finalReport);
    }

}
