package com.nbport.zgwl.contractlog.controller;

import com.nbport.zgwl.common.PageResult;
import com.nbport.zgwl.common.R;
import com.nbport.zgwl.contractlog.dto.ContractLogDto;
import com.nbport.zgwl.contractlog.dto.ContractLogQueryDto;
import com.nbport.zgwl.contractlog.service.ContractLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/contract/log")
public class ContractLogController {

    private final ContractLogService contractLogService;

    @PostMapping("/list")
    public R<PageResult<ContractLogDto>> queryList(@RequestBody ContractLogQueryDto queryDto) {
        return R.success(contractLogService.queryPage(queryDto));
    }

    @PostMapping("/all")
    public R<List<ContractLogDto>> queryAll(@RequestBody ContractLogQueryDto queryDto) {
        return R.success(contractLogService.queryList(queryDto));
    }

    @PostMapping("/export/excel")
    public ResponseEntity<byte[]> exportExcel(@RequestBody ContractLogQueryDto queryDto) {
        byte[] fileBytes = contractLogService.exportExcel(queryDto);
        String fileName = "合同日志_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, StandardCharsets.UTF_8))
                .body(fileBytes);
    }
}
