package com.ebts.web.controller.system;

import com.ebts.common.annotation.Log;
import com.ebts.common.core.controller.EBTSController;
import com.ebts.common.core.entity.Result;
import com.ebts.common.core.entity.model.LoginUser;
import com.ebts.common.enums.BusinessType;
import com.ebts.common.utils.poi.ExcelUtil;
import com.ebts.framework.web.service.TokenService;
import com.ebts.system.entity.SysFile;
import com.ebts.system.service.FileService;
import com.ebts.system.utils.FtpUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件信息Controller
 *
 * @author binlin
 * @date 2021-02-17
 */

@Api(value = "文件信息管理", tags = "文件信息管理")
@RestController
@RequestMapping("/system/file")
public class FileController extends EBTSController {

    @Autowired
    private FileService fileService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询文件信息列表
     */
    @PreAuthorize("@ebts.hasPermi('system:file:list')")
    @PutMapping("/list")
    public Serializable list(@Validated @RequestBody SysFile sysFile) {
        startPage(sysFile.getParams());
        Result<List<SysFile>> result = fileService.selectFileList(sysFile);
        if (result.isSuccess()) {
            return getDataTable(result.getData());
        } else {
            return result;
        }
    }

    @GetMapping("/folder")
    public Result<List<SysFile>> getFolder() {
        return fileService.selectFileFolder();
    }

    /**
     * 导出文件信息列表
     */
    @PreAuthorize("@ebts.hasPermi('system:file:export')")
    @Log(title = "文件信息", businessType = BusinessType.EXPORT)
    @PutMapping("/export")
    public Result<SysFile> export(@Validated @RequestBody SysFile sysFile) {
        Result<List<SysFile>> result = fileService.selectFileList(sysFile);
        ExcelUtil<SysFile> util = new ExcelUtil<SysFile>(SysFile.class);
        if (result.isSuccess()) {
            return util.exportExcel(result.getData(), "file");
        } else {
            return Result.error(result.getMsg());
        }
    }

    /**
     * 获取文件信息详细信息
     */
    @PreAuthorize("@ebts.hasPermi('system:file:query')")
    @GetMapping(value = "/{fileId}")
    public Result<SysFile> getInfo(@PathVariable("fileId") Long fileId) {
        return fileService.selectFileById(fileId);
    }

    /**
     * 新增文件信息
     */
    @PreAuthorize("@ebts.hasPermi('system:file:add')")
    @Log(title = "文件信息", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<Map<String, String>> add(@RequestBody SysFile sysFile) {
        if (sysFile.getFileAddr() == null || sysFile.getFileAddr().equals("")) {
            return Result.error("上传文件不能为空!");
        }
        if (sysFile.getIsPublic().equals("1") || sysFile.getIsPublic().equals("2")) {
            Map<String, String> modeMap = new HashMap<>();
            Result<SysFile> serverResult = fileService.insertFile(sysFile);
            if (serverResult.isSuccess()) {
                if (sysFile.getIsPublic().equals("1")) {
                    String fileUrl = FtpUtils.getResources() + sysFile.getFileAddr().substring(FtpUtils.getPubfiles().length()) + "/" + sysFile.getMapping();
                    modeMap.put("url", fileUrl);
                }
                String fileUri = sysFile.getFileAddr() + "/" + sysFile.getMapping();
                modeMap.put("uri", fileUri);
                return Result.ok(modeMap);
            } else {
                return Result.error(serverResult.getMsg());
            }
        } else {
            return Result.error("isPublic为空或者状态有误!");
        }
    }

    /**
     * 修改文件信息
     */
    @PreAuthorize("@ebts.hasPermi('system:file:edit')")
    @Log(title = "文件信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<Integer> edit(@RequestBody SysFile sysFile) {
        return fileService.updateFile(sysFile);
    }

    /**
     * 删除文件信息
     */
    @PreAuthorize("@ebts.hasPermi('system:file:remove')")
    @Log(title = "文件信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fileIds}")
    public Result<Integer> remove(@PathVariable Long[] fileIds) {
        if (fileIds.length == 0) {
            return Result.error("id不能为空!");
        }
        return fileService.deleteFileByIds(fileIds);
    }

    @GetMapping("/download/{fileId}")
    public Result<SysFile> download(@PathVariable Long fileId, HttpServletRequest request, HttpServletResponse response) {
        LoginUser user = tokenService.getFileUser(request);
        return fileService.downloadFile(fileId, user);
    }
}
