package com.ruoyi.school.paper.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.school.paper.domain.bo.DbBannerBo;
import com.ruoyi.school.paper.domain.vo.DbBannerVo;
import com.ruoyi.school.paper.service.IDbBannerService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 轮播图
 *
 * @author ruoyi
 * @date 2023.07.24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/school-paper/banner")
public class DbBannerController extends BaseController {

    private final IDbBannerService iDbBannerService;
    @Value("${document.uploadPath}")
    private String uploadPath;

    /**
     * 查询轮播图列表
     */
    @GetMapping("/list")
    public TableDataInfo<DbBannerVo> list(DbBannerBo bo, PageQuery pageQuery) {
        return iDbBannerService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出轮播图列表
     */
    @Log(title = "轮播图", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(DbBannerBo bo, HttpServletResponse response) {
        List<DbBannerVo> list = iDbBannerService.queryList(bo);
        ExcelUtil.exportExcel(list, "轮播图", DbBannerVo.class, response);
    }

    /**
     * 获取轮播图详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<DbBannerVo> getInfo(@NotNull(message = "主键不能为空")
                                 @PathVariable Long id) {
        return R.ok(iDbBannerService.queryById(id));
    }

    /**
     * 新增轮播图
     */
    @Log(title = "轮播图", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DbBannerBo bo) {
        return toAjax(iDbBannerService.insertByBo(bo));
    }

    /**
     * 修改轮播图
     */
    @Log(title = "轮播图", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DbBannerBo bo) {
        return toAjax(iDbBannerService.updateByBo(bo));
    }

    /**
     * 删除轮播图
     *
     * @param ids 主键串
     */
    @Log(title = "轮播图", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iDbBannerService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public R upload(@RequestPart("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String uploadPath = "C:\\Users\\Administrator\\Pictures\\";
            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String OriginalFilename = file.getOriginalFilename();//获取原文件名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
            //重新随机生成名字
            String filename = UUID.randomUUID().toString() + suffixName;
            File localFile = new File(uploadPath + filename);
            String url = "https://farming.nyinhong.com/pic/" + filename;
            try {
                file.transferTo(localFile); //把上传的文件保存至本地
                /**
                 * 这里应该把filename保存到数据库,供前端访问时使用
                 */
                Map<String, Object> map = new HashMap<>();
                map.put("url", url);
                map.put("originalFilename", OriginalFilename);
                return R.ok(map);//上传成功，返回保存的文件地址
            } catch (IOException e) {
                e.printStackTrace();
                return R.fail("上传失败");
            }
        } else {
            return R.fail("文件为空");
        }
    }
}
