package com.gci.boot.modules.statis.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.vo.Result;
import com.gci.boot.modules.statis.service.ProjectStatisService;
import com.gci.boot.modules.statis.vo.ProjectStatisVo;
import com.gci.boot.modules.statis.vo.StatisParamVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Api(tags="项目成本统计")
@Slf4j
@RestController
@RequestMapping("/statis/project")
public class ProjectStatisController {

    @Autowired
    private ProjectStatisService projectStatisService;

    @AddSysLog(value = "项目成本统计-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StatisParamVO vo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page<ProjectStatisVo> page = new Page<>(pageNo, pageSize);
        IPage<ProjectStatisVo> pageList = projectStatisService.page(page,vo);
        return Result.ok(pageList);
    }

    /**
     *  simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大时要 重复多次写入
     * @param response
     */
    @AddSysLog(value = "项目成本统计-导出")
    @GetMapping("/export")
    public Result<?> export(StatisParamVO vo, HttpServletResponse response){
        try (OutputStream output = response.getOutputStream()){

            String fileName = "项目成本统计.xlsx";
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);

            List<ProjectStatisVo> list = projectStatisService.getAll(vo);
            EasyExcel.write(output, ProjectStatisVo.class).sheet("项目成本统计").doWrite(list);

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return Result.error("导出错误！");
        }
        return Result.ok();
    }
}
