package com.ruoyi.platform.controller.dataset;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.platform.domain.Dataset;
import com.ruoyi.platform.domain.DatasetVersion;
import com.ruoyi.platform.service.DatasetService;
import com.ruoyi.platform.service.DatasetVersionService;
import com.ruoyi.platform.vo.DatasetVo;
import com.ruoyi.system.api.model.LoginUser;
import io.swagger.annotations.Api;
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.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Map;

/**
 * (Dataset)表控制层
 *
 * @author Xidaray
 * @since 2023-11-28 11:46:50
 */
@RestController
@RequestMapping("dataset")
@Api(value = "数据集管理")
public class DatasetController {
    /**
     * 服务对象
     */
    @Resource
    private DatasetService datasetService;

    @Resource
    private DatasetVersionService datasetVersionService;

    /**
     * 分页查询
     *
     * @param dataset 筛选条件
     * @param page 页数
     * @param size 大小
//     * @param availableRange 可用范围：1表示公开，0表示私有
     * @return 查询结果
     */
    @GetMapping
    @ApiOperation("数据集广场公开数据集分页查询,根据data_type筛选，1公开0私有")
    public AjaxResult queryByPage(Dataset dataset, @RequestParam("page") int page,
                                  @RequestParam("size") int size,
                                  @RequestParam(value = "available_range") int availableRange ,
                                  @RequestParam(value = "data_type", required = false) String dataType,
                                  @RequestParam(value = "data_tag", required = false) String dataTag) {

        if (dataType != null) { // 仅当dataType有值时设置
            dataset.setDataType(dataType);
        }
        if (dataTag != null) {
            dataset.setDataTag(dataTag);
        }
        dataset.setAvailableRange(availableRange);
        PageRequest pageRequest = PageRequest.of(page, size);
        return AjaxResult.success(this.datasetService.queryByPage(dataset, pageRequest));
    }


    @GetMapping("/personalDatasets")
    @ApiOperation("分页查询当前用户的个人数据集，根据data_type筛选,1公开0私有")
    public AjaxResult queryByPagePersonal(Dataset dataset, @RequestParam("page") int page,
                                          @RequestParam("size") int size,
                                          @RequestParam(value = "data_type", required = false) String dataType,
                                          @RequestParam(value = "data_tag", required = false) String dataTag) {
        // 获取当前用户的认证信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置筛选条件
        dataset.setCreateBy(loginUser.getUsername());
        dataset.setAvailableRange(0);
        if (dataType != null) { // 仅当dataType有值时设置
            dataset.setDataType(dataType);
        }
        if (dataTag != null) {
            dataset.setDataTag(dataTag);
        }
        PageRequest pageRequest = PageRequest.of(page, size);
        return AjaxResult.success(this.datasetService.queryByPage(dataset, pageRequest));
    }



    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @ApiOperation("根据数据集id查询数据集")
    public AjaxResult queryById(@PathVariable("id") Integer id) {
        return AjaxResult.success(this.datasetService.queryById(id));
    }

    @GetMapping("/versions/{datasetId}")
    @ApiOperation(value = "获取数据集的所有版本", notes = "根据数据集ID获取该数据集的所有版本信息。")
    public AjaxResult getDatasetVersions(@PathVariable("datasetId") Integer datasetId) throws Exception {
        return AjaxResult.success(this.datasetService.getDatasetVersions(datasetId));
    }


    /**
     * 新增数据
     *
     * @param dataset 实体
     * @return 新增结果
     */
    @PostMapping
    @ApiOperation("添加数据集")
    public AjaxResult add(@RequestBody Dataset dataset) throws Exception {
        return AjaxResult.success(this.datasetService.insert(dataset));

    }

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

    }

    /**
     * 编辑数据
     *
     * @param dataset 实体
     * @return 编辑结果
     */
    @PutMapping
    @ApiOperation("编辑数据集")
    public AjaxResult edit(@RequestBody Dataset dataset) {
        return AjaxResult.success(this.datasetService.update(dataset));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping({"{id}"})
    @ApiOperation("根据id删除数据集")
    public AjaxResult deleteById(@PathVariable("id") Integer id) throws Exception {
        return AjaxResult.success(this.datasetService.removeById(id));
    }

    /**
     * 下载数据集
     *
     * @param dataset_version_id  ps:这里的id是dataset_version表的主键
     * @return 单条数据
     */
    
    @GetMapping("/download/{dataset_version_id}")
    @ApiOperation(value = "下载单个数据集文件", notes = "根据数据集版本表id下载单个数据集文件")
    public ResponseEntity<InputStreamResource> downloadDataset(@PathVariable("dataset_version_id") Integer dataset_version_id) throws Exception {
        return datasetService.downloadDataset(dataset_version_id);
    }

    /**
     * 数据集打包下载
     *
     * @param datasetId 数据集id
     * @param version  数据集版本
     * @return 单条数据
     */
    @GetMapping("/downloadAllFiles")
    @ApiOperation(value = "下载同一版本下所有数据集，并打包", notes = "根据数据集ID和版本下载所有数据集文件，并打包。")
    public ResponseEntity<InputStreamResource> downloadAllDatasetFiles(@RequestParam("dataset_id") Integer datasetId, @RequestParam("version") String version) throws Exception {
        return datasetService.downloadAllDatasetFiles(datasetId, version);
    }

    /**
     * 上传数据集
     *
     * @param files 上传的数据集文件
     * @param uuid 上传唯一标识，构建url
     * @return 上传结果
     */
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @PostMapping("/upload")
    @ApiOperation(value = "上传数据集", notes = "根据数据集版本表id上传数据集文件，并将信息存入数据库。")
    public AjaxResult uploadDataset(@RequestParam("file") MultipartFile[] files, @RequestParam("uuid") String uuid) throws Exception {
        return AjaxResult.success(this.datasetService.uploadDataset(files,uuid));
    }



    @PostMapping("/exportDataset")
    @ApiOperation(value = "导出数据集", notes = "将流水线产物导出到数据集。")
    public AjaxResult exportDataset(@RequestBody Map map) throws Exception {
        String path = (String) map.get("path");
        String uuid = (String) map.get("uuid");
        return AjaxResult.success(datasetService.exportDataset(path, uuid));
    }




    /**
     * 从流水线上传数据集，不会给二进制文件，这边只存路径
     * @return 上传结果
     */
    @PostMapping("/upload_pipeline")
    @ApiOperation(value = "从流水线上传数据集", notes = "并将信息存入数据库。")
    public AjaxResult uploadDatasetPipeline(@RequestBody(required =false) DatasetVersion datasetVersion) throws Exception {
        return AjaxResult.success(this.datasetService.uploadDatasetPipeline(datasetVersion));
    }


}

