package com.retdata.yaoyibi.web;

import com.retdata.yaoyibi.domain.CsoSysDeptSummary;
import com.retdata.yaoyibi.domain.SysImplPlanSearchDto;
import com.retdata.yaoyibi.domain.SysImplPlanSearchParams;
import com.retdata.yaoyibi.service.SysImplPlanService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.uuid.UUID;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/sys-impl-plans")
public class SysImplPlanController {

    private final SysImplPlanService sysImplPlanService;

    public SysImplPlanController(SysImplPlanService sysImplPlanService) {
        this.sysImplPlanService = sysImplPlanService;
    }

    @GetMapping
    public Page<SysImplPlanSearchDto> search(@ParameterObject SysImplPlanSearchParams searchParams,
                                             @ParameterObject Pageable pageable) {
        return sysImplPlanService.search(searchParams, pageable);
    }

    @GetMapping("/consignors")
    public List<CsoSysDeptSummary> listConsignors() {
        return sysImplPlanService.listConsignors();
    }

    @GetMapping("/consignees")
    public List<CsoSysDeptSummary> listConsignees() {
        return sysImplPlanService.listConsignees();
    }

    @GetMapping("/export")
    public String export(@ParameterObject SysImplPlanSearchParams searchParams) throws IOException {
        try (XSSFWorkbook workbook = sysImplPlanService.export(searchParams)) {
            String filename = UUID.randomUUID() + "_计划包数据.xlsx";
            Path path = Paths.get(RuoYiConfig.getDownloadPath(), filename);
            Files.createDirectories(path.getParent());
            try (OutputStream fos = Files.newOutputStream(path)) {
                workbook.write(fos);
            }
            return filename;
        }
    }

}
