package com.jsc.oscm.controller;

import com.jsc.oscm.entity.DataPackage;
import com.jsc.oscm.entity.DataPackageLog;
import com.jsc.oscm.service.DataPackageService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
public class DataPackageController {
    @javax.annotation.Resource
    private DataPackageService dataPackageService;

    @GetMapping("/data-package/list")
    public ResponseEntity<Page<DataPackage>> getPackageList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
        return ResponseEntity.ok(dataPackageService.getPackageList(pageable));
    }

    @GetMapping("/data-package/log/list")
    public ResponseEntity<Page<DataPackageLog>> getLogList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "operationTime"));
        return ResponseEntity.ok(dataPackageService.getLogList(pageable));
    }

    @PostMapping("/open/data-package/add/package")
    public ResponseEntity<Void> addPackage(@RequestBody DataPackage dataPackage) {
        dataPackageService.addPackage(dataPackage);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/data-package/download/{id}")
    public ResponseEntity<String> getDownloadUrl(@PathVariable Integer id, HttpServletRequest request) {
        DataPackage dataPackage = dataPackageService.getPackageById(id);
        if (dataPackage == null) {
            return ResponseEntity.notFound().build();
        }

        // 记录下载日志（关键操作）
        dataPackageService.addLog(dataPackage.getPackageName(), "下载", request);

        // 直接返回Nginx文件URL
        return ResponseEntity.ok(dataPackage.getDownloadUrl());
    }
}