package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import vn.azteam.tpf.service.ReportInOutMaterialService;
import vn.azteam.tpf.service.UserService;
import vn.azteam.tpf.service.dto.*;
import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;
import vn.azteam.tpf.web.rest.util.PaginationUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * REST controller for managing TBLimits.
 */
@RestController
@RequestMapping("/api")
public class ReportsInOutMaterialResource {

    private final Logger log = LoggerFactory.getLogger(ReportsInOutMaterialResource.class);

    private static final String ENTITY_NAME = "reports";
    private final String DATE_PARAM_FORMAT = "dd-MM-yyyy";

    private final ReportInOutMaterialService reportInOutMaterialService;

    private final UserService userService;

    public ReportsInOutMaterialResource(
        ReportInOutMaterialService reportInOutMaterialService,
        UserService userService) {
        this.reportInOutMaterialService = reportInOutMaterialService;
        this.userService = userService;
    }


    @GetMapping("/report/in-out-material/download")
    @Timed
    public void downloadReportInOutMaterials(@RequestParam("suppliesTypeId") Long suppliesTypeId,
                                             @RequestParam("startDate") @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date startDate,
                                             @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date endDate,
                                             HttpServletResponse response) throws IOException {

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        DateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentDateTime = dateFormatter.format(new Date());
        String headerValue = "attachment; filename=Báo-cáo-nhập-xuất-tồn-vật-tư-" + currentDateTime + ".xlsx";
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, headerValue);

        UserDTO currentUser = getCurrentUser();
        reportInOutMaterialService.downloadReportInOutMaterials(currentUser.getCustomerId(), suppliesTypeId, startDate, endDate, response);
    }

    @GetMapping("/report/in-out-material/view")
    @Timed
    public ResponseEntity<List<TBBlockDetailsReportDTO>> viewReportInOutMaterials(@RequestParam("suppliesTypeId") Long suppliesTypeId,
                                                                                  @RequestParam("startDate") @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date startDate,
                                                                                  @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date endDate,
                                                                                  Pageable pageable) {

        UserDTO currentUser = getCurrentUser();
        Page<TBBlockDetailsReportDTO> page = reportInOutMaterialService.reportInOutMaterials(currentUser.getCustomerId(), suppliesTypeId, startDate, endDate, pageable);

        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/report/in-out-material/view");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    @GetMapping("/report/finish-goods/download")
    @Timed
    public void downloadReportFinishedGoodsWarehouse(@RequestParam("cropId") Long cropId,
                                                     @RequestParam("startDate") @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date startDate,
                                                     @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date endDate,
                                                     HttpServletResponse response) throws IOException {

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        DateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentDateTime = dateFormatter.format(new Date());
        String headerValue = "attachment; filename=Báo-cáo-kho-thành-phẩm-" + currentDateTime + ".xlsx";
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, headerValue);

        UserDTO currentUser = getCurrentUser();
        reportInOutMaterialService.downloadReportFinishedGoodsWarehouse(currentUser.getCustomerId(), cropId, startDate, endDate, response);
    }

    @GetMapping("/report/finish-goods/view")
    @Timed
    public ResponseEntity<List<TBProductBlockDetailsReportDTO>> viewReportFinishedGoodsWarehouse(@RequestParam("cropId") Long cropId,
                                                                                                 @RequestParam("startDate") @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date startDate,
                                                                                                 @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date endDate,
                                                                                                 Pageable pageable) {

        UserDTO currentUser = getCurrentUser();
        Page<TBProductBlockDetailsReportDTO> page = reportInOutMaterialService.reportFinishedGoodsWarehouse(currentUser.getCustomerId(), cropId, startDate, endDate, pageable);

        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/report/finish-goods/view");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }


    @GetMapping("/report/farm-result/download")
    @Timed
    public void downloadReportFarmResult(@RequestParam("cropId") Long cropId,
                                         @RequestParam("startDate") @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date startDate,
                                         @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date endDate,
                                         HttpServletResponse response) throws IOException {

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        DateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentDateTime = dateFormatter.format(new Date());
        String headerValue = "attachment; filename=Báo-cáo-kết-quả-canh-tác-" + currentDateTime + ".xlsx";
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, headerValue);

        UserDTO currentUser = getCurrentUser();
        reportInOutMaterialService.downloadReportFarmResult(currentUser.getCustomerId(), cropId, startDate, endDate, response);
    }

    @GetMapping("/report/farm-result/view")
    @Timed
    public ResponseEntity<List<TBFarmResultReportDTO>> viewReportFarmResult(@RequestParam("cropId") Long cropId,
                                                                                     @RequestParam("startDate") @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date startDate,
                                                                                     @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = DATE_PARAM_FORMAT) Date endDate,
                                                                                     Pageable pageable) {

        UserDTO currentUser = getCurrentUser();
        Page<TBFarmResultReportDTO> page = reportInOutMaterialService.reportFarmResult(currentUser.getCustomerId(), cropId, startDate, endDate, pageable);

        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/report/farm-result/view");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    private UserDTO getCurrentUser() {
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() == null) {
            throw new BadRequestAlertException("1002", ENTITY_NAME, "1022");
        }
        return currentUser;
    }
}
