package tech.easyflow.admin.controller.datacenter;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
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 org.springframework.web.multipart.MultipartFile;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.datacenter.excel.model.DatacenterExcelDeriveRequest;
import tech.easyflow.datacenter.excel.model.DatacenterExcelExportRequest;
import tech.easyflow.datacenter.excel.model.DatacenterExcelMergeRequest;
import tech.easyflow.datacenter.excel.model.DatacenterExcelSplitRequest;
import tech.easyflow.datacenter.excel.service.DatacenterExcelImportService;
import tech.easyflow.datacenter.meta.entity.DatacenterImportJob;

import java.io.File;
import java.io.FileInputStream;
import javax.annotation.Resource;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/api/v1/datacenterExcel")
public class DatacenterExcelController {

    @Resource
    private DatacenterExcelImportService excelImportService;

    @PostMapping("/import")
    @SaCheckPermission("/api/v1/datacenterSource/save")
    public Result<DatacenterImportJob> importWorkbook(MultipartFile file) throws Exception {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        return Result.ok(excelImportService.importWorkbook(file, account));
    }

    @PostMapping("/split")
    @SaCheckPermission("/api/v1/datacenterSource/save")
    public Result<DatacenterImportJob> split(@RequestBody DatacenterExcelSplitRequest request) {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        return Result.ok(excelImportService.splitWorkbook(request, account));
    }

    @PostMapping("/merge")
    @SaCheckPermission("/api/v1/datacenterSource/save")
    public Result<DatacenterImportJob> merge(@RequestBody DatacenterExcelMergeRequest request) {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        return Result.ok(excelImportService.mergeWorkbook(request, account));
    }

    @PostMapping("/derive")
    @SaCheckPermission("/api/v1/datacenterSource/save")
    public Result<DatacenterImportJob> derive(@RequestBody DatacenterExcelDeriveRequest request) {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        return Result.ok(excelImportService.deriveWorkbook(request, account));
    }

    @PostMapping("/export")
    @SaCheckPermission("/api/v1/datacenterSource/query")
    public Result<DatacenterImportJob> export(@RequestBody DatacenterExcelExportRequest request) throws Exception {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        return Result.ok(excelImportService.exportWorkbook(request, account));
    }

    @GetMapping("/importJob/detail")
    @SaCheckPermission("/api/v1/datacenterSource/query")
    public Result<DatacenterImportJob> jobDetail(BigInteger jobId) {
        return Result.ok(excelImportService.getImportJobDetail(jobId));
    }

    @GetMapping("/job/detail")
    @SaCheckPermission("/api/v1/datacenterSource/query")
    public Result<DatacenterImportJob> newJobDetail(BigInteger jobId) {
        return Result.ok(excelImportService.getImportJobDetail(jobId));
    }

    @GetMapping("/job/list")
    @SaCheckPermission("/api/v1/datacenterSource/query")
    public Result<List<DatacenterImportJob>> jobList(BigInteger sourceId, BigInteger tableId) {
        return Result.ok(excelImportService.listJobs(sourceId, tableId));
    }

    @GetMapping("/download")
    @SaCheckPermission("/api/v1/datacenterSource/query")
    public void download(BigInteger jobId, HttpServletResponse response) throws Exception {
        DatacenterImportJob job = excelImportService.getImportJobDetail(jobId);
        if (job.getStoragePath() == null || job.getStoragePath().isBlank()) {
            throw new IllegalStateException("导出文件不存在");
        }
        File file = new File(job.getStoragePath());
        if (!file.exists()) {
            throw new IllegalStateException("导出文件不存在");
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(job.getFileName(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        try (FileInputStream inputStream = new FileInputStream(file)) {
            inputStream.transferTo(response.getOutputStream());
            response.flushBuffer();
        }
    }
}
