package com.citygis.web.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.citygis.common.config.CitygisConfig;
import com.citygis.common.core.controller.BaseController;
import com.citygis.common.core.domain.AjaxResult;
import com.citygis.common.core.page.TableDataInfo;
import com.citygis.web.domain.TabFileInfo;
import com.citygis.web.service.ITabFileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author citygis
 * @since 2025-01-02
 */
@Api(tags = "接入标准")
@RestController
@RequestMapping("/web/tab-file-info")
public class TabFileInfoController extends BaseController {

    @Resource
    ITabFileInfoService iTabFileInfoService;


    @ApiOperation("接入标准列表")
    @GetMapping("getTabFileInfoList")
    public TableDataInfo getTabFileInfoList(TabFileInfo tabFileInfo){
        startPage();
        return getDataTable(iTabFileInfoService.getTabFileInfoList(tabFileInfo));
    }

    @ApiOperation("修改接入标准")
    @PutMapping("updateTabFileInfoById")
    public AjaxResult updateTabFileInfoById(@RequestBody TabFileInfo tabFileInfo){
        return iTabFileInfoService.updateTabFileInfoById(tabFileInfo);
    }

    @ApiOperation("逻辑删除接入标准")
    @PutMapping("falseDeleteTabFileInfoById/{fileId}")
    public AjaxResult  falseDeleteTabFileInfoById(@PathVariable Integer fileId){
        return iTabFileInfoService.falseDeleteTabFileInfoById(fileId);
    }

    @ApiOperation("上传接入标准")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, TabFileInfo fileInfo) throws Exception {
        return iTabFileInfoService.insertTabFileInfo(file, fileInfo);
    }

    @ApiOperation("下载接入标准")
    @GetMapping("/download/{fileId}")
    public void downloadFile(@PathVariable String fileId, HttpServletResponse response) throws Exception {
        OutputStream os;//新建一个输出流对象
        String uploadPath = CitygisConfig.getUploadPath();
        String filePath = uploadPath + iTabFileInfoService.getFilePathById(fileId).replace("/upload", "");
        try {
            if (StrUtil.isNotEmpty(filePath)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filePath, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath);//通过文件的路径读取文件字节流
                os = response.getOutputStream();//通过response的输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

}

