package com.dk.mdm.controller;

import com.alibaba.fastjson.JSONObject;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.util.AuthUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${upload-path}")
    private String uploadPath;

    @Autowired
    private AuthUtils authUtils;

    /**
     * @desc : 上传文件
     * @author : 洪旭东
     * @date : 2023-06-26 14:09
     */
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @PostMapping("upload")
    public ResponseResultVO<?> upload(@RequestPart("file") MultipartFile file, @RequestParam("folder") String folder,@RequestParam(required=false) String uuid) {
        if (file.isEmpty()) {
            return ResponseResultUtil.error(ErrorCodeEnum.FILE_UPLOAD_FAIL.getCode(), ErrorCodeEnum.FILE_UPLOAD_FAIL.getMessage());
        }

        //生产文件名称
        String fileName = file.getOriginalFilename();
        String uuidName = Optional.ofNullable(uuid).orElse(UUID.randomUUID().toString()) + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
        String filePath = this.createDirByPath(folder) + uuidName;
        File dest = new File(filePath);

        try {
            file.transferTo(dest);
            //组装参数后返回
            JSONObject json = new JSONObject();
            json.put("path", filePath.replace(uploadPath, ""));
            json.put("name", fileName);
            json.put("type", getFileType(fileName));
            json.put("createTime", LocalDateTime.now());
            return ResponseResultUtil.success(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResultUtil.error(ErrorCodeEnum.FILE_UPLOAD_FAIL.getCode(), ErrorCodeEnum.FILE_UPLOAD_FAIL.getMessage());
    }

    /**
     * @desc : 获取文件类型
     * @author : 周兴
     * @date : 2024-03-27 14:09
     */
    private String getFileType(String fileName) {
        if (fileName.indexOf(".") >= 0) {
            String appCode = authUtils.getStaff().getAppCode();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            fileType = fileType.toLowerCase();

            if ("mp4".equals(fileType) || "avi".equals(fileType) || "mov".equals(fileType)) {
                return "video";
            }
            // 小程序
            if (Constant.AppCode.WEIXIN.getCode().equals(appCode)) {
                if ("xls".equals(fileType) || "xlsx".equals(fileType)) {
                    return "file";
                }
                if ("pdf".equals(fileType)) {
                    return "file";
                }
                if ("jpg".equals(fileType) || "jepg".equals(fileType) || "png".equals(fileType)) {
                    return "image";
                }
            } else {
                if ("xls".equals(fileType) || "xlsx".equals(fileType)) {
                    return "excel";
                }
                if ("pdf".equals(fileType)) {
                    return "pdf";
                }
                if ("jpg".equals(fileType) || "jepg".equals(fileType) || "png".equals(fileType)) {
                    return "img";
                }
            }
        }
        return "";
    }

    /**
     * @desc : 根据类型创建目录文件夹
     * @author : 洪旭东
     * @date : 2023-06-26 14:10
     */
    private String createDirByPath(String folder) {
        //斜线
        final String diagonal = "/";

        String path = folder + diagonal;
        StringBuilder base = new StringBuilder(uploadPath);
        File baseDir = new File(uploadPath);
        if (!baseDir.exists()) {
            baseDir.mkdir();
        }
        //按路径新建文件夹
        for (String s : path.split(diagonal)) {
            base.append(diagonal).append(s);
            File dir = new File(base.toString());
            if (!dir.exists()) {
                dir.mkdir();
            }
        }
        return base + diagonal;
    }
}
