package cn.wisenergy.web.admin.controller.app;

import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import cn.wisenergy.common.utils.exception.Result;
import cn.wisenergy.model.app.WorkDept;
import cn.wisenergy.model.dto.GetMonthlyCollectParam;
import cn.wisenergy.model.dto.ProjectStatisticsByMonth;
import cn.wisenergy.model.dto.UserWorkTimeStatisticsByProject;
import cn.wisenergy.model.dto.WorkTimeAndCostCollect;
import cn.wisenergy.service.StatisticsService;
import cn.wisenergy.service.WorkDeptService;
import cn.wisenergy.web.admin.controller.common.BaseController;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

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

/**
 * @description:
 * @author: nh
 * @create: 2021-01-19 17:13
 **/
@RestController
@RequestMapping(value = "/statistics")
@Slf4j
@Api(tags = "统计报表")
public class StatisticsController extends BaseController {
    @Autowired
    StatisticsService statisticsService;

    @Autowired
    WorkDeptService workDeptService;

    @ApiOperation(value = "获取部门员工一个月每天的工时", notes = "获取部门员工一个月每天的工时")
    @GetMapping("/getMonthlyCollect")
    public PageInfo getMonthlyCollect(GetMonthlyCollectParam param) {
        log.info("StatisticsController[]getMonthlyCollect[]input.param" + param);
        PageInfo monthlyCollect = statisticsService.getDayWorkTimeOfMonth(param);
        return monthlyCollect;
    }

    @ApiOperation(value = "获取全部部门信息或单条信息", notes = "获取全部部门信息或单条信息")
    @ApiImplicitParam(name = "deptId", value = "部门主键")
    @GetMapping("/getDeptInfo")
    public List<WorkDept> getDeptInfo(Integer deptId) {
        log.info("StatisticsController[]getDeptInfo[]input.param" + deptId);
        List<WorkDept> workDepts = workDeptService.getDeptInfo(deptId);
        return workDepts;
    }

    @ApiOperation(value = "获取负责项目工时汇总", notes = "获取负责项目工时汇总")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户主键"),
            @ApiImplicitParam(name = "startTime", value = "开始时间")
    })
    @GetMapping("/getCurrentMonthWorkTimeCollect")
    public Result<List<WorkTimeAndCostCollect>> getWorkTimeCollect(Integer userId, String startTime) {
        log.info("WorkUserController[]getCurrentMonthWorkTimeCollect[]input.param" + userId, startTime);
        if (userId == null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        List<WorkTimeAndCostCollect> currentMonthWorkTimeCollect = statisticsService.getCurrentMonthWorkTimeCollect(userId, startTime);
        return getResult(currentMonthWorkTimeCollect);
    }

    @ApiOperation(value = "获取本月工时统计和审核统计", notes = "获取本月", httpMethod = "GET")
    @ApiImplicitParam(name = "userId", value = "用户主键", dataType = "int", required = true)
    @GetMapping("/getMonthlyWorkingHours")
    public Result<Map<String, Object>> getMonthlyWorkingHours(Integer userId) {
        log.info("WorkOrderController[]getMonthlyWorkingHours[]input.param" + userId);
        if (userId == null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        Map<String, Object> monthlyStatistics = statisticsService.getMonthlyStatistics(userId);
        return getResult(monthlyStatistics);
    }

    @ApiOperation(value = "导出部门员工一个月每天的工时", notes = "导出部门员工一个月每天的工时")
    @GetMapping("/exportWorkTime")
    public void export(GetMonthlyCollectParam param, HttpServletResponse response)  {
        log.info("StatisticsController[]export[]input.param" + param);
        HSSFWorkbook sheets = new HSSFWorkbook();
        try {
        // 获取excel
        sheets = statisticsService.exportWorkTimeExcel(param);

        // 获取excel中的第2行第2列中的部门名称
        String deptName = sheets.getSheet("Sheet1").getRow(1).getCell(1).getStringCellValue();
        // 文件名
        String fileName = deptName + "-" + param.getYear() + "年" + param.getMonth() + "月工时汇总";


            this.downExcel(response,sheets,fileName);
        }finally {
            try {
                sheets.close();
            } catch (IOException e) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.SERVER_ERROR);
            }
        }

    }

    @ApiOperation(value = "获取人员工时统计报表", notes = "获取人员工时统计报表")
    @GetMapping("/getUserWorkTimeStatisticsReport")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户主键"),
            @ApiImplicitParam(name = "deptId", value = "部门主键"),
            @ApiImplicitParam(name = "startDate", value = "开始统计时间"),
            @ApiImplicitParam(name = "endDate", value = "结束统计时间")
    })
    public Result<List<UserWorkTimeStatisticsByProject>> getUserWorkTimeStatisticsReport(Integer userId, Integer deptId, String startDate, String endDate) {
        log.info("StatisticsController[]getUserWorkTimeStatisticsReport[]input.param{}" + userId, deptId, startDate, endDate);
        List<UserWorkTimeStatisticsByProject> userWorkTimeStatisticsByProjects = statisticsService.getUserWorkTimeStatisticsReport(userId, deptId, startDate, endDate);
        return getResult(userWorkTimeStatisticsByProjects);
    }

    @ApiOperation(value = "获取项目统计报表", notes = "获取项目统计报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户主键"),
            @ApiImplicitParam(name = "deptId", value = "部门主键"),
            @ApiImplicitParam(name = "year", value = "统计年"),
            @ApiImplicitParam(name = "projectId", value = "项目主键")
    })
    @GetMapping("/getProjectStatistics")
    public Result<List<ProjectStatisticsByMonth>> getProjectStatistics(Integer userId, Integer deptId, Integer year, Integer projectId) {
        log.info("StatisticsController[]getProjectStatistics[]input.param" + userId + deptId + year, projectId);
        List<ProjectStatisticsByMonth> projectStatisticsByMonths = statisticsService.getProjectStatistics(userId, deptId, year, projectId);
        return getResult(projectStatisticsByMonths);
    }

    @ApiOperation(value = "导出人员工时统计", notes = "导出人员工时统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户主键"),
            @ApiImplicitParam(name = "deptId", value = "部门主键"),
            @ApiImplicitParam(name = "startDate", value = "开始统计时间"),
            @ApiImplicitParam(name = "endDate", value = "结束统计时间")
    })
    @GetMapping("/exportUserStatistics")
    public void exportUserStatistics(Integer userId, Integer deptId, String startDate, String endDate,HttpServletResponse response) {
        log.info("StatisticsController[]exportUserStatistics[]input.param" + userId + deptId + startDate + endDate);
        HSSFWorkbook sheets = new HSSFWorkbook();
        try{
            // 获取excel
            sheets = statisticsService.exportUserStatistics(userId, deptId, startDate, endDate);
            String fileName = "人员工时统计";
            this.downExcel(response,sheets,fileName);
        }finally {
            try {
                sheets.close();
            } catch (IOException e) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.SERVER_ERROR);
            }
        }

    }


    @ApiOperation(value = "导出项目统计明细", notes = "导出项目明细表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户主键"),
            @ApiImplicitParam(name = "year", value = "统计年"),
            @ApiImplicitParam(name = "projectIds", value = "项目主键,以逗号隔开")
    })
    @GetMapping("/exportProjectStatistics")
    public void exportProjectStatistics(Integer userId, Integer year, String projectIds, HttpServletResponse response) {
        log.info("StatisticsController[]exportUserStatistics[]input.param" + userId + year + projectIds);
        HSSFWorkbook sheets = new HSSFWorkbook();
        // 获取excel
        try {
            sheets = statisticsService.exportProjectStatistics(userId, year, projectIds);
            String fileName = "项目工时统计明细";
            downExcel(response, sheets, fileName);
        }finally {
            try {
                sheets.close();
            } catch (IOException e) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.SERVER_ERROR);
            }
        }
    }

    // 导出Excel
    public void downExcel(HttpServletResponse response, HSSFWorkbook sheets, String fileName) {
        //响应类型为application/octet- stream情况下使用了这个头信息的话，那就意味着不想直接显示内容
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        //attachment为以附件方式下载
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(
                    fileName + ".xls",
                    "utf-8"));

            response.setHeader("Cache-Control", "No-cache");
            response.flushBuffer();
            ServletOutputStream outputStream = response.getOutputStream();
            sheets.write(outputStream);
            outputStream.flush();
            outputStream.close();
            sheets.close();
        } catch (Exception e) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.SERVER_ERROR);
        }
    }

}