package com.retdata.yaoyibi.web;

import com.retdata.yaoyibi.domain.CsoSysDeptSearchDto;
import com.retdata.yaoyibi.domain.CsoSysDeptSearchParams;
import com.retdata.yaoyibi.domain.CsoSysDeptSummary;
import com.retdata.yaoyibi.service.CsoSysDeptService;
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("/cso-sys-depts")
public class CsoSysDeptController {

    private final CsoSysDeptService csoSysDeptService;

    public CsoSysDeptController(CsoSysDeptService csoSysDeptService) {
        this.csoSysDeptService = csoSysDeptService;
    }

    @RequestMapping
    public Page<CsoSysDeptSearchDto> search(@ParameterObject CsoSysDeptSearchParams searchParams,
                                            @ParameterObject Pageable pageable) {
        return csoSysDeptService.search(searchParams, pageable);
    }

    @GetMapping("/export")
    public String export(@ParameterObject CsoSysDeptSearchParams searchParams) throws IOException {
        try (XSSFWorkbook workbook = csoSysDeptService.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;
        }
    }

    @GetMapping("/all")
    public List<CsoSysDeptSummary> listAllDeptSummary() {
        return csoSysDeptService.listAllDeptSummary();
    }

}
