package com.keyware.shandan.control.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keyware.shandan.common.entity.Result;
import com.keyware.shandan.common.enums.SystemTypes;
import com.keyware.shandan.control.InvalidFileHandler;
import com.keyware.shandan.system.entity.SysFile;
import com.keyware.shandan.system.entity.SysFileChunk;
import com.keyware.shandan.system.entity.SysSetting;
import com.keyware.shandan.system.service.SysFileService;
import com.keyware.shandan.system.utils.FileChunkUploadUtil;
import com.keyware.shandan.system.utils.SysSettingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sys/file/repair")
public class FileRepairController {

    private final SysFileService fileService;
    private final InvalidFileHandler invalidFileHandler;

    public FileRepairController(SysFileService fileService,
                                InvalidFileHandler invalidFileHandler) {
        this.fileService = fileService;
        this.invalidFileHandler = invalidFileHandler;
    }

    /**
     * 数据补录页面
     *
     * @return
     */
    @GetMapping("/index")
    public ModelAndView repair(ModelAndView mav) {
        mav.setViewName("sys/file/fileRepair");
        SysSetting bianmuSetting = SysSettingUtil.getSysSetting(SystemTypes.BIANMU.name());
        mav.addObject("bianmuAddress", bianmuSetting.getSysAddress());
        return mav;
    }

    @GetMapping("/list")
    public Result<Object> fileList(@RequestParam String dirId,
                                   @RequestParam(required = false, defaultValue = "false") boolean refresh) {

        return Result.of(invalidFileHandler.listByDir(dirId, refresh));
    }

    /**
     * 清理数据
     *
     * @param fileId
     * @return
     */
    @GetMapping("/clean/{fileId}")
    public Result<Object> remove(@PathVariable String fileId) {
        try {
            invalidFileHandler.clean(fileId);
        } catch (Exception e) {
            log.error("清理文件异常", e);
        }
        return Result.of(null);
    }


    @PostMapping("/upload/check")
    public Result<Object> uploadFileCheck() {
        Result<Object> result = Result.of(null, true);
        result.setCode(0);
        return result;
    }

    /**
     * 大文件分片上传
     *
     * @param file      分片文件
     * @param fileChunk 分片数据
     * @return 结果集
     */
    @PostMapping("/upload/chunk")
    public Result<Object> uploadChunk(MultipartFile file, SysFile fileInfo, SysFileChunk fileChunk) throws Exception {
        return Result.of(FileChunkUploadUtil.uploadChunk(file, fileInfo, fileChunk));

    }

    /**
     * 文件分片上传完成，需要自动生成目录结构，并保存目录文件关系
     *
     * @param file 文件信息
     * @return 结果
     */
    @PostMapping("/upload/chunk/complete")
    public Result<Object> mergerChunk(SysFile file) throws Exception {
        FileChunkUploadUtil.mergeChunk(file, sysFile -> {
            SysFile oldFile = fileService.getById(file.getId());
            if (oldFile == null) {
                oldFile = sysFile;
            }
            QueryWrapper<SysFile> query = new QueryWrapper<>();
            query.eq("MD5", oldFile.getMD5()).eq("PATH", oldFile.getPath());
            List<SysFile> files = fileService.list(query);
            files.forEach(f -> f.setPath(sysFile.getPath()));
            fileService.updateBatchById(files);
            invalidFileHandler.removeCache(file.getId());
        });
        return Result.of(true);
    }
}
