package com.persagy.dmp.file.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.persagy.dmp.common.constant.CommonConstant;
import com.persagy.dmp.common.constant.ResponseCode;
import com.persagy.dmp.common.constant.ValidEnum;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.common.lang.PsDateTime;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.common.utils.ResultHelper;
import com.persagy.dmp.file.model.FileInfo;
import com.persagy.dmp.file.model.FileInfoCreator;
import com.persagy.dmp.file.model.FileRequestData;
import com.persagy.dmp.file.model.UploadMes;
import com.persagy.dmp.file.service.IFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 文件管理Controller
 * @author Charlie Yu
 */
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    private final IFileService fileService;

    @PostMapping("/insert")
    public CommonResult<FileInfo> insert(@RequestBody FileInfo fileInfo) {
        if(StrUtil.isBlank(fileInfo.getFileName()) ||
                StrUtil.isBlank(fileInfo.getGroupCode())) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        fileInfo.setCreationTime(new PsDateTime());
        fileInfo.setValid(ValidEnum.TRUE.getType());
        fileInfo = fileService.insertFile(fileInfo);
        return ResultHelper.single(fileInfo);
    }

    @PostMapping("/update")
    public CommonResult<FileInfo> update(@RequestBody FileInfo fileInfo) {
        if(StrUtil.isBlank(fileInfo.getId()) ||
                StrUtil.isBlank(fileInfo.getFileName()) ||
                StrUtil.isBlank(fileInfo.getGroupCode())) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        fileInfo.setModifiedTime(new PsDateTime());
        fileInfo = fileService.updateFile(fileInfo);
        return ResultHelper.single(fileInfo);
    }

    @PostMapping("/delete")
    public CommonResult<String> delete(@RequestBody String id) {
        if(StrUtil.isBlank(id)) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        FileInfo fileInfo = fileService.load(id);
        if(fileInfo == null) {
            throw new BusinessException("找不到对应的文件信息");
        }
        fileService.deleteFile(fileInfo);
        return ResultHelper.success();
    }

    @PostMapping("/deleteByFileMd5s")
    public CommonResult<String> deleteByFileMd5s(@RequestBody Set<String> fileMd5s) {
        if(CollUtil.isEmpty(fileMd5s)) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        List<FileInfo> fileInfos = fileService.queryByFileMd5s(fileMd5s);
        if (CollUtil.isEmpty(fileInfos)){
            return ResultHelper.success();
        }
        fileService.deleteFileByFileMd5s(fileInfos);
        return ResultHelper.success();
    }

    @PostMapping("/load")
    public CommonResult<FileInfo> load(@RequestBody String id) {
        if(StrUtil.isBlank(id)) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        FileInfo fileInfo = fileService.load(id);
        if(fileInfo == null) {
            throw new BusinessException("找不到对应的文件信息");
        }
        return ResultHelper.single(fileInfo);
    }

    @PostMapping("/queryByBusiness")
    public CommonResult<List<FileInfo>> queryByBusiness(@RequestBody String businessId) {
        if(StrUtil.isBlank(businessId)) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        List<FileInfo> voList = fileService.queryByBusinessId(businessId);
        return ResultHelper.multi(voList);
    }

    @PostMapping("/queryByFileMd5")
    public CommonResult<List<FileInfo>> queryByFileMd5(@RequestBody String fileMd5) {
        if(StrUtil.isBlank(fileMd5)) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        List<FileInfo> voList = fileService.queryByFileMd5s(CollUtil.newHashSet(fileMd5));
        return ResultHelper.multi(voList);
    }

    /***
     * Description: 根据文件key批量获取预下载的URL
     * @param requestData : 请求参数
     * @return : com.persagy.dmp.common.model.response.CommonResult<com.persagy.dmp.file.model.FileInfo>
     * @author : lijie
     * Update By lijie 2021/10/9 20:12
     */
    @PostMapping("/queryFetchUrlsByFileIds")
    public CommonResult<Map<String,String>> queryFetchUrlsByFileIds(@RequestBody FileRequestData requestData) {
        return ResultHelper.single(fileService.queryFetchUrlsByFileIds(requestData.getFileIds()));
    }

    /***
     * Description: 初始化断点上传文件
     * @param requestData : 请求参数
     * @return : com.persagy.dmp.common.model.response.CommonResult<com.persagy.dmp.file.model.FileInfo>
     * @author : lijie
     * Update By lijie 2021/10/9 20:12
     */
    @PostMapping("/initChunkUpload")
    public CommonResult<UploadMes> initChunkUpload(@RequestBody FileRequestData requestData) {
        // 1.兼容一下groupCode
        fillGroupCode(requestData);
        // 2.判断必填项
        if(StrUtil.isBlank(requestData.getFileName())
                || StrUtil.isBlank(requestData.getFileMd5())
                || StrUtil.isBlank(requestData.getGroupCode())
                || null==requestData.getChunkCount()
                || requestData.getChunkCount()<=0) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        return ResultHelper.single(fileService.initChunkUpload(requestData));
    }

    /***
     * Description: 初始化大文件上传
     * @param requestData : 请求参数
     * @return : com.persagy.dmp.common.model.response.CommonResult<com.persagy.dmp.file.model.FileInfo>
     * @author : lijie
     * Update By lijie 2021/10/9 20:12
     */
    @PostMapping("/composeFile")
    public CommonResult<FileInfo> composeFile(@RequestBody FileRequestData requestData) {
        //基础参数校验
        // 1.兼容一下groupCode
        fillGroupCode(requestData);
        // 2.判断必填项
        if(StrUtil.isBlank(requestData.getFileName())
                || StrUtil.isBlank(requestData.getFileMd5())
                || StrUtil.isBlank(requestData.getGroupCode())
                || StrUtil.isBlank(requestData.getFileBucket())) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        FileInfoCreator.checkBucketNameValid(requestData.getFileBucket());
        return ResultHelper.single(fileService.composeFile(requestData));
    }
    /***
     * Description: 初始化单个文件上传
     * @param requestData : 请求参数
     * @return : com.persagy.dmp.common.model.response.CommonResult<com.persagy.dmp.file.model.FileInfo>
     * @author : lijie
     * Update By lijie 2021/10/9 20:12
     */
    @PostMapping("/initSingleUpload")
    public CommonResult<UploadMes> initSingleUpload(@RequestBody FileRequestData requestData) {
        //基础参数校验
        // 1.兼容一下groupCode
        fillGroupCode(requestData);
        // 2.判断必填项
        if(StrUtil.isBlank(requestData.getFileName())
                || StrUtil.isBlank(requestData.getFileMd5())
                || StrUtil.isBlank(requestData.getGroupCode())
                || StrUtil.isBlank(requestData.getFileBucket())
                || null==requestData.getFileSize()) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        return ResultHelper.single(fileService.initSingleUpload(requestData));
    }
    /***
     * Description: 初始化文件下载
     * @param requestData : 请求参数
     * @return : com.persagy.dmp.common.model.response.CommonResult<com.persagy.dmp.file.model.FileInfo>
     * @author : lijie
     * Update By lijie 2021/10/9 20:12
     */
    @PostMapping("/initFileDownload")
    public CommonResult<FileInfo> initFileDownload(@RequestBody FileRequestData requestData) {
        //基础参数校验
        if(StrUtil.isBlank(requestData.getFileId())) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        return ResultHelper.single(fileService.initFileDownload(requestData));
    }
    /***
     * Description: 填充一下集团编码
     * @param requestData : 请求参数
     * @author : lijie
     * Update By lijie 2021/10/21 20:14
     */
    private void fillGroupCode(FileRequestData requestData) {
        if (StrUtil.isNotBlank(requestData.getGroupCode())){
            return;
        }
        requestData.setGroupCode(AppContext.getContext().getGroupCode());
        if (StrUtil.isBlank(requestData.getGroupCode())){
            // 如果为空则将集团编码设置为0
            requestData.setGroupCode(CommonConstant.DEFAULT_ID);
        }
    }

}
