package fastweb.controller;

import com.aliyun.imagerecog20190930.models.ClassifyingRubbishResponse;
import fastweb.domain.system.WrapperResult;
import fastweb.util.OssUtils;
import fastweb.util.Sample;
import io.netty.util.internal.StringUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

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

    public static class UploadRequest {
        private String file;
        private String username;

        // Getters and Setters
        public String getFile() {
            return file;
        }

        public void setFile(String file) {
            this.file = file;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }
    }

    @PostMapping("/upload_file_base64")
    public WrapperResult uploadFileBase64(@RequestBody UploadRequest uploadRequest) throws Exception {
        LocalDateTime now = LocalDateTime.now();
        String hhmmssFormat = now.format(DateTimeFormatter.ofPattern("ddHHmmss"));
        String fileName = hhmmssFormat + ".png";

        String filePath = saveBase64Image(uploadRequest.getFile(), "upload/" + fileName);
        String ossUrl = OssUtils.getFileUrl(filePath,fileName);

        String url = OssUtils.uploadFile(filePath);
        if (!StringUtil.isNullOrEmpty(url)) {
            ClassifyingRubbishResponse response = Sample.getResult(url);
            Map result = new HashMap<String, Object>();
            result.put("ossUrl",ossUrl);
            result.put("result",response);
            return WrapperResult.successWrapedResult(result);
        }
        return WrapperResult.failedWrappedResult("获取结果失败");
    }

    private String saveBase64Image(String base64Image, String filePath) throws IOException {
        // 处理 Base64 字符串，去掉前缀（如果存在）
        String imageData = base64Image.replaceFirst("data:image/.+;base64,", "");
        byte[] imageBytes = Base64.getDecoder().decode(imageData);

        // 保存图像文件
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(imageBytes);
        }

        return filePath; // 返回保存的文件路径
    }

}
