package com.ruoyi.platform.controller.dataset;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.platform.domain.Dataset;
import com.ruoyi.platform.service.NewDatasetService;
import com.ruoyi.platform.utils.DVCUtils;
import com.ruoyi.platform.vo.LabelDatasetVersionVo;
import com.ruoyi.platform.vo.NewDatasetVo;
import com.ruoyi.platform.vo.QueryModelMetricsVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("newdataset")
//@Api(value = "新数据集管理")
public class NewDatasetFromGitController {
    /**
     * 服务对象
     */
    @Resource
    private NewDatasetService newDatasetService;

    @Resource
    private DVCUtils dvcUtils;

    /**
     * 新增数据集与版本新
     *
     * @param datasetVo 实体
     * @return 新增结果
     */
    @PostMapping("/addDatasetAndVersion")
    @ApiOperation("添加数据集和版本")
    public AjaxResult addDatasetAndVersion(@RequestBody NewDatasetVo datasetVo) throws Exception {
        return AjaxResult.success(this.newDatasetService.newCreateDataset(datasetVo));

    }


    /**
     * 新增数据集与版本新
     *
     * @param datasetVo 实体
     * @return 新增结果
     */
    @PostMapping("/addVersion")
    @ApiOperation("添加版本")
    public AjaxResult addVersion(@RequestBody NewDatasetVo datasetVo) throws Exception {
        return AjaxResult.success(this.newDatasetService.newCreateVersion(datasetVo));

    }

    /**
     * 新增数据集与版本新
     *
     * @param datasetVo 实体
     * @return 新增结果
     */
    @PostMapping("/addVersionFromLabelStudio")
    @ApiOperation("从labelsudio添加版本")
    public AjaxResult addVersionFromLabelStudio(@RequestBody LabelDatasetVersionVo datasetVo) throws Exception {
        return AjaxResult.success(this.newDatasetService.newCreateVersionFromLabelStudio(datasetVo));

    }

    @GetMapping("/queryDatasets")
    @ApiOperation("数据集广场公开数据集分页查询,根据data_type,data_tag筛选，true公开false私有")
    public AjaxResult queryDatasets(@RequestParam(value = "page", required = false) @Nullable Integer page,
                                    @RequestParam(value = "size", required = false) @Nullable Integer size,
                                    @RequestParam(value = "is_public", required = false) @Nullable Boolean isPublic,
                                    @RequestParam(value = "data_type", required = false) String dataType,
                                    @RequestParam(value = "data_tag", required = false) String dataTag,
                                    @RequestParam(value = "name", required = false) String name) throws Exception {
        page = Optional.ofNullable(page).orElse(0); // 默认 page 为 0
        size = Optional.ofNullable(size).orElse(10000); // 默认 size 为 10000
        isPublic = Optional.ofNullable(isPublic).orElse(false);
        PageRequest pageRequest = PageRequest.of(page, size);
        Dataset dataset = new Dataset();
        dataset.setDataTag(dataTag);
        dataset.setDataType(dataType);
        dataset.setName(name);
        if (isPublic) {
            return AjaxResult.success(this.newDatasetService.newPubilcQueryByPage(dataset, pageRequest));
        } else {
            return AjaxResult.success(this.newDatasetService.newPersonalQueryByPage(dataset, pageRequest));
        }
    }

    @GetMapping("/getVersionList")
    @ApiOperation(value = "获取分支列表")
    public AjaxResult getVersionList(@RequestParam("identifier") String repo, @RequestParam("owner") String owner) throws Exception {
        return AjaxResult.success(this.newDatasetService.getVersionList(repo, owner));
    }

    @GetMapping("/getDatasetDetail")
    @ApiOperation(value = "获取数据集详情")
    public AjaxResult getDatasetVersions(@RequestParam("name") String name,
                                         @RequestParam("id") Integer id,
                                         @RequestParam(value = "owner", required = false) String owner,
                                         @RequestParam(value = "identifier", required = false) String identifier,
                                         @RequestParam(value = "version", required = false) String version,
                                         @RequestParam(value = "is_public") Boolean isPublic) throws Exception {
        return AjaxResult.success(this.newDatasetService.getNewDatasetDesc(id, name, identifier, owner, version, isPublic));
    }

    @DeleteMapping("/deleteDataset")
    @ApiOperation(value = "删除数据集")
    public AjaxResult deleteDataset(@RequestParam("id") Integer id, @RequestParam("identifier") String identifier, @RequestParam("owner") String owner, @RequestParam("is_public") Boolean isPublic) throws Exception {
        this.newDatasetService.deleteDatasetNew(id, identifier, owner, isPublic);
        return AjaxResult.success();
    }

    @DeleteMapping("/deleteDatasetVersion")
    @ApiOperation(value = "删除数据集版本")
    public AjaxResult deleteDatasetVersion(@RequestParam("id") Integer id, @RequestParam("identifier") String repo, @RequestParam("owner") String owner, @RequestParam("version") String version,
                                           @RequestParam("relative_paths") String relativePaths) throws Exception {
        // 查询版本，如果是最后一个版本，则不能删除
        List<Map<String, Object>> versionList = this.newDatasetService.getVersionList(repo, owner);
        if (versionList.size() == 1) {
            return AjaxResult.error("当前数据集只有一个版本，不能删除该版本");
        }
        this.newDatasetService.deleteDatasetVersionNew(id, repo, owner, version, relativePaths);
        return AjaxResult.success();
    }


    /**
     * 上传数据集
     *
     * @param files 上传的数据集文件
     * @param uuid  上传唯一标识，构建url
     * @return 上传结果
     */
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @PostMapping("/upload")
    @ApiOperation(value = "上传数据集")
    public AjaxResult uploadDataset(@RequestParam("file") MultipartFile[] files, @RequestParam("uuid") String uuid) throws Exception {
        return AjaxResult.success(this.newDatasetService.uploadDatasetlocal(files, uuid));
    }

    /**
     * 数据集打包下载
     *
     * @param version 数据集版本
     * @return 单条数据
     */
    @GetMapping("/downloadAllFiles")
    @ApiOperation(value = "下载同一版本下所有数据集，并打包")
    public ResponseEntity<InputStreamResource> downloadAllDatasetFiles(@RequestParam("name") String name, @RequestParam("identifier") String identifier, @RequestParam("id") Integer id, @RequestParam("version") String version, @RequestParam("is_public") Boolean isPublic) throws Exception {
        return newDatasetService.downloadAllDatasetFilesNew(name, identifier, id, version, isPublic);
    }

    /**
     * 下载数据集
     *
     * @param url ps:路径
     * @return 单条数据
     */

    @GetMapping("/downloadSingleFile")
    @ApiOperation(value = "下载单个数据集文件", notes = "根据数据集版本表id下载单个数据集文件")
    public ResponseEntity<InputStreamResource> downloadDataset(@RequestParam("url") String url) throws Exception {
        return newDatasetService.downloadDatasetlocal(url);
    }

    @PostMapping("/getVersionsCompare")
    @ApiOperation(value = "获取数据集版本对比")
    public AjaxResult getVersionsCompare(@RequestBody QueryModelMetricsVo querydatasetVo) throws Exception {
        return AjaxResult.success(this.newDatasetService.getVersionsCompare(querydatasetVo));
    }

    @DeleteMapping("/deleteFile")
    @ApiOperation(value = "删除文件")
    public AjaxResult deleteFile(@RequestParam("url") String url, @RequestParam("fileName") String fileName) {
        Path file = Paths.get(url, System.getProperty("file.separator"), fileName);
        dvcUtils.deletePath(file);
        return AjaxResult.success("删除成功");
    }
}
