package com.microservices.file.controller;

import com.microservices.common.core.domain.R;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.security.annotation.InnerAuth;
import com.microservices.file.service.ISysFileInfoService;
import com.microservices.system.api.domain.SysFile;
import com.microservices.system.api.domain.SysFileInfo;
import com.microservices.system.api.utils.StandardMultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Base64;
import java.util.Map;

/**
 * 文件请求处理
 *
 * @author microservices
 */
@RestController
@ApiIgnore
public class SysFileController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileInfoService sysFileInfoService;

    /**
     * 文件上传请求
     */
    @InnerAuth
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file,
                             @RequestParam("type") String type,
                             @RequestParam("hierarchy") String hierarchy) {
        try {
            // 上传并返回访问地址
            SysFileInfo fileInfo = sysFileInfoService.upload(file, type, hierarchy);
            SysFile sysFile = new SysFile();
            sysFile.setName(fileInfo.getFilePath());
            sysFile.setUrl(fileInfo.getDownloadUrl());
            sysFile.setFileIdentifier(fileInfo.getFileIdentifier());
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    @InnerAuth
    @PostMapping("/upload/base64")
    public R<SysFileInfo> uploadBase64(@RequestBody Map<String, Object> params,
                                   @RequestParam("type") String type,
                                   @RequestParam("hierarchy") String hierarchy) {
        try {
            // 1. 提取参数
            String base64Data = (String) params.get("base64Data");
            String fileName = (String) params.get("fileName");
            String contentType = (String) params.get("contentType");

            // 2. 参数校验
            if (StringUtils.isEmpty(base64Data)) {
                return R.fail("base64Data不能为空");
            }

            // 3. Base64解码
            byte[] fileBytes;
            try {
                fileBytes = Base64.getDecoder().decode(base64Data);
            } catch (IllegalArgumentException e) {
                log.error("Base64解码失败", e);
                return R.fail("图片数据格式错误");
            }

            if (fileBytes.length == 0) {
                return R.fail("解码后文件为空");
            }

            // 4. 构造MultipartFile
            String originalFilename = StringUtils.isEmpty(fileName)
                    ? "base64_image_" + System.currentTimeMillis() + ".png"
                    : fileName;

            MultipartFile multipartFile = new StandardMultipartFile(
                    fileBytes,
                    "file",           // 字段名，与原接口一致
                    originalFilename,
                    contentType
            );

            // 5. 复用原有上传逻辑
            SysFileInfo fileInfo = sysFileInfoService.upload(multipartFile, type, hierarchy);

            return R.ok(fileInfo);

        } catch (Exception e) {
            log.error("Base64上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}