package com.youlai.boot.system.controller;

import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.system.model.entity.Record;
import com.youlai.boot.system.service.RecordService;
import com.youlai.boot.system.service.impl.FTPService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.youlai.boot.system.model.form.RecordForm;
import com.youlai.boot.system.model.query.RecordQuery;
import com.youlai.boot.system.model.vo.RecordVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static com.youlai.boot.common.util.SystemUtil.downloadFile;

/**
 * 部署记录前端控制层
 *
 * @author kangyu
 * @since 2024-10-08 14:14
 */
@Tag(name = "部署记录接口")
@RestController
@RequestMapping("/api/v1/deploy")
@RequiredArgsConstructor

public class RecordController  {

    private static final Logger log = LoggerFactory.getLogger(RecordController.class);

    private final RecordService recordService;




    @Operation(summary = "部署记录分页列表")
    @GetMapping("/page")
    @Log( value = "查看上传记录列表",module = LogModuleEnum.UPLOAD)
    public PageResult<RecordVO> getRecordPage(RecordQuery queryParams , HttpServletRequest request) {
        IPage<RecordVO> result = recordService.getRecordPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "新增部署记录")
    @PostMapping
    @Log( value = "新增部署记录",module = LogModuleEnum.UPLOAD)
    public Result<Void> saveRecord(@RequestBody @Valid RecordForm formData ) {
        boolean result = recordService.saveRecord(formData);
        return Result.judge(result);
    }

    @Operation(summary = "获取部署记录表单数据")
    @GetMapping("/{id}/form")
    public Result<RecordForm> getRecordForm(
        @Parameter(description = "部署记录ID") @PathVariable Long id
    ) {
        RecordForm formData = recordService.getRecordFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改部署记录")
    @PutMapping(value = "/{id}")
    @Log( value = "修改部署记录",module = LogModuleEnum.UPLOAD)
    public Result<Void> updateRecord(
            @Parameter(description = "部署记录ID") @PathVariable Long id,
            @RequestBody @Validated RecordForm formData
    ) {
        boolean result = recordService.updateRecord(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除部署记录")
    @DeleteMapping("/{ids}")
    @Log( value = "删除部署记录",module = LogModuleEnum.UPLOAD)
    public Result<Void> deleteRecords(
        @Parameter(description = "部署记录ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = recordService.deleteRecords(ids);
        return Result.judge(result);
    }

    @Operation(summary = "启动jar文件")
    @GetMapping("/jar/start/{id}")
    @Log( value = "启动jar文件",module = LogModuleEnum.UPLOAD)
    public Result<Void> startRecord(@PathVariable Long id){
        boolean result = recordService.startJarFile(id);
        return Result.judge(result);
    }

    @Operation(summary = "停止jar文件")
    @GetMapping("/jar/stop/{id}")
    @Log( value = "停止jar文件",module = LogModuleEnum.UPLOAD)
    public Result<Void> stopRecord(@PathVariable Long id){
        boolean result = recordService.stopJarFile(id);
        return Result.judge(result);
    }

//    @PostMapping("/upload")
//    @Log( value = "上传文件",module = LogModuleEnum.UPLOAD)
//    public Result<String> handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("pageType") String pageType,@RequestParam("dirId") int dirId) {
//
//        if (file.isEmpty()) {
//            return Result.failed("文件不能为空！");
//        }
//        log.info("接收到文件 {}",file.getName());
//
//        String result = recordService.saveFile(file,pageType,dirId);
//
//        return Result.success(result);
//
//    }

    @PostMapping("/upload")
    public Result addDemandFile(@RequestParam("file") MultipartFile file,@RequestParam("pageType") String pageType) {

        if (file.isEmpty()) {
            return Result.failed("文件不能为空！");
        }
        String absPath = recordService.saveFile(file, pageType);

        return Result.success(absPath);
    }

    @GetMapping("/log/{id}")
    @Log( value = "下载日志",module = LogModuleEnum.UPLOAD)
    public void getLog(@PathVariable Long id, HttpServletResponse response){
        Record record = recordService.getById(id);

        downloadFile(record.getLog(),response);
    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable Long id, HttpServletResponse response)  {
        Record record = recordService.getById(id);
        String path = record.getPath();
        downloadFile(path, response);
    }



}
