package org.nl.system.controller.tools;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nl.common.base.TableDataInfo;
import org.nl.common.domain.query.PageQuery;
import org.nl.common.exception.BadRequestException;
import org.nl.common.utils.FileUtil;
import org.nl.common.logging.annotation.Log;
import org.nl.system.service.tools.IToolLocalStorageService;
import org.nl.system.service.tools.dao.ToolLocalStorage;
import org.nl.system.service.tools.dto.ToolLocalStorageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Set;

/**
 * <p>
 * 本地存储表 前端控制器
 * </p>
 *
 * @author generator
 * @since 2022-12-20
 */
@RestController
@Api(tags = "工具：本地存储管理")
@RequestMapping("/api/localStorage")
public class ToolLocalStorageController {
    @Autowired
    private IToolLocalStorageService localStorageService;

    @ApiOperation("查询文件")
    @GetMapping
//    @SaCheckPermission("storage:list")
    public ResponseEntity<Object> query(ToolLocalStorageQuery criteria, PageQuery pageable) {
        return new ResponseEntity<>(TableDataInfo.build(localStorageService.queryAll(criteria, pageable)), HttpStatus.OK);
    }

    @ApiOperation("上传文件")
    @PostMapping
    @SaIgnore
//    @SaCheckPermission("storage:add")
    public ResponseEntity<Object> create(@RequestParam String name, @RequestParam("file") MultipartFile file) {
        return new ResponseEntity<>(localStorageService.create(name, file), HttpStatus.CREATED);
    }

    @PostMapping("/pictures")
    @ApiOperation("上传图片")
    public ResponseEntity<Object> upload(@RequestParam MultipartFile file) {
        // 判断文件是否为图片
        String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
        if (!FileUtil.IMAGE.equals(FileUtil.getFileType(suffix))) {
            throw new BadRequestException("只能上传图片");
        }
        return new ResponseEntity<>(localStorageService.create(null, file), HttpStatus.OK);
    }

    @Log("修改文件")
    @ApiOperation("修改文件")
    @PutMapping
    @SaCheckPermission("storage:edit")
    public ResponseEntity<Object> update(@Validated @RequestBody ToolLocalStorage resources) {
        localStorageService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除文件")
    @DeleteMapping
    @ApiOperation("多选删除")
    public ResponseEntity<Object> delete(@RequestBody Set<String> ids) {
        localStorageService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}

