package com.ruoyi.project.business.controller.train;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadKoyoUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.business.domain.train.TtFileDatabase;
import com.ruoyi.project.business.domain.train.TtFileDirectory;
import com.ruoyi.project.business.domain.vo.train.FileDataVisibleRangeVo;
import com.ruoyi.project.business.domain.vo.train.FileDatabaseReq;
import com.ruoyi.project.business.domain.vo.train.FileDatabaseRes;
import com.ruoyi.project.business.domain.vo.train.FileDatabaseVo;
import com.ruoyi.project.business.service.train.ITtFileDatabaseService;
import com.ruoyi.project.business.service.train.ITtFileDirectoryService;
import com.ruoyi.project.config.AppConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 资料库Controller
 *
 * @author ruoyi
 * @date 2024-05-20
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/train/database")
public class TtFileDatabaseController extends BaseController {
    private static final String FILE_DELIMETER = ",";
    private final ITtFileDatabaseService ttFileDatabaseService;
    private final ITtFileDirectoryService ttFileDirectoryService;
    private final ServerConfig serverConfig;
    
    // @Value("app.dataFolder")
    // private String dataFolder;


    /**
     * 获取目录树
     */
    @GetMapping("/directory/tree")
    public AjaxResult getDirectoryTree() {
        return AjaxResult.success(ttFileDirectoryService.getDirectoryTree());
    }


    /**
     * 创建目录
     */
    @PostMapping("/directory")
    public AjaxResult add(@RequestBody TtFileDirectory fileDirectory) {
        return AjaxResult.success(ttFileDirectoryService.add(fileDirectory));
    }
    

    /**
     * 查询资料库列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FileDatabaseReq req) {
        // startPage();
        List<FileDatabaseRes> list = ttFileDatabaseService.selectTtFileDatabaseList(req);
        return getDataTable(list);
    }

    /**
     * 获取资料库详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ttFileDatabaseService.getById(id));
    }

    /**
     * 新增资料
     */
    @Log(title = "资料库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Valid FileDatabaseVo fileDatabaseVo) {
        return toAjax(ttFileDatabaseService.add(fileDatabaseVo));
    }

    /**
     * 修改资料
     */
    @Log(title = "资料库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TtFileDatabase ttFileDatabase) {
        return toAjax(ttFileDatabaseService.edit(ttFileDatabase));
    }
    
    /**
     * 修改可见范围
     */
    @Log(title = "资料库", businessType = BusinessType.UPDATE)
    @PutMapping("/visibleRange")
    public AjaxResult editVisibleRange(@RequestBody FileDataVisibleRangeVo fileDataVisibleRangeVo) {
        if (1 == fileDataVisibleRangeVo.getType()) {
            return toAjax(ttFileDatabaseService.editVisibleRange(fileDataVisibleRangeVo));
        } else if (2 == fileDataVisibleRangeVo.getType()) {
            return toAjax(ttFileDirectoryService.editVisibleRange(fileDataVisibleRangeVo));
        }
        throw new RuntimeException("type error");
    }

    /**
     * 删除资料
     */
    @Log(title = "资料库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ttFileDatabaseService.removeByIds(Arrays.asList(ids)));
    }
    /**
     * 删除资料目录
     */
    @Log(title = "资料库", businessType = BusinessType.DELETE)
    @DeleteMapping("/delDirectoryAndData/{id}")
    public AjaxResult removeDirectoryAndData(@PathVariable Long id) {
        return toAjax(ttFileDatabaseService.removeDirectoryAndData(id));
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload/{curFolderId}")
    public AjaxResult uploadFile(MultipartFile file, @PathVariable Long curFolderId) throws Exception {
        try {
            // 上传文件路径
            //String filePath = RuoYiConfig.getUploadPath();
            String filePath = ttFileDirectoryService.getDataFolder(curFolderId);

            // 上传并返回新文件名称
            //String fileName = FileUploadUtils.upload(filePath, file, false);
            //String fileName = FileUploadKoyoUtils.upload(filePath, file, "D:/KOYO_BJXT/dataPath/");
            String fileName = FileUploadKoyoUtils.upload(filePath, file, AppConfig.getDataFolder());
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    ///**
    // * 通用上传请求（多个）
    // */
    //@PostMapping("/uploads")
    //public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
    //    try {
    //        // 上传文件路径
    //        String filePath = RuoYiConfig.getUploadPath();
    //        List<String> urls = new ArrayList<String>();
    //        List<String> fileNames = new ArrayList<String>();
    //        List<String> newFileNames = new ArrayList<String>();
    //        List<String> originalFilenames = new ArrayList<String>();
    //        for (MultipartFile file : files) {
    //            // 上传并返回新文件名称
    //            String fileName = FileUploadUtils.upload(filePath, file);
    //            String url = serverConfig.getUrl() + fileName;
    //            urls.add(url);
    //            fileNames.add(fileName);
    //            newFileNames.add(FileUtils.getName(fileName));
    //            originalFilenames.add(file.getOriginalFilename());
    //        }
    //        AjaxResult ajax = AjaxResult.success();
    //        ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
    //        ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
    //        ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
    //        ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
    //        return ajax;
    //    } catch (Exception e) {
    //        return AjaxResult.error(e.getMessage());
    //    }
    //}
    
    /**
     * 获取文件类型 for dropdown
     */
    @GetMapping("/fileTypes")
    public AjaxResult getFileTypes() {
        return AjaxResult.success(ttFileDatabaseService.getFileTypes());
    }
}
