import _ from "lodash";
import fs from "fs";
import { imageSize } from 'image-size';

import Request from "@/lib/request/Request.ts";
import { getUploadToken, getUploadService, uploadImages, calculateCrc32Hex, sendFile } from "@/api/controllers/upload.ts";
import { tokenSplit } from "@/api/controllers/core.ts";
import util from "@/lib/util.ts";
export default {
  prefix: "/v1/upload",

  post: {
    "/images": async (request: Request) => {
      request
      //   .validate("body.model", v => _.isUndefined(v) || _.isString(v))
      //   .validate("body.prompt", _.isString)
      //   .validate("body.negative_prompt", v => _.isUndefined(v) || _.isString(v))
      //   .validate("body.width", v => _.isUndefined(v) || _.isFinite(v))
      //   .validate("body.height", v => _.isUndefined(v) || _.isFinite(v))
      //   .validate("body.sample_strength", v => _.isUndefined(v) || _.isFinite(v))
      //   .validate("body.response_format", v => _.isUndefined(v) || _.isString(v))
        .validate("headers.authorization", _.isString);
      const imageFile = request.files['image']||null;
      // console.log(imageFile); 
      // refresh_token切分
      const tokens = tokenSplit(request.headers.authorization);
      // 随机挑选一个refresh_token
      const token = _.sample(tokens);
      // const {
      //   model,
      //   prompt,
      //   negative_prompt: negativePrompt,
      //   width,
      //   height,
      //   sample_strength: sampleStrength,
      //   response_format,
      // } = request.body;
      // const responseFormat = _.defaultTo(response_format, "url");
      //获取oss授权信息
      const uploadInfo = await getUploadToken(token);
      let file_size = 0;
      let fileBuffer = null;
      if (imageFile) {
        file_size = imageFile.size;
        // console.log("imageFile.filepath", imageFile.filepath);
        fileBuffer = await fs.promises.readFile(imageFile.filepath);
      }
      if (file_size <= 0){
        return {
          error: {
            message: "请上传图片",
            type: "invalid_request_error",
            param: null,
            code: "invalid_image_size",
          },
        }
      }
      let crc32 = "";
      let dimensions = null;
      if(fileBuffer){
        dimensions = imageSize(fileBuffer);
        if ((dimensions.width*dimensions.height) < (100*100)){
          return {
            error: {
              message: "图片尺寸小于100x100",
              type: "invalid_request_error",
              param: null,
              code: "invalid_image_size",
            },
          }
        }
        crc32 = calculateCrc32Hex(fileBuffer);
        // console.log("crc32", crc32);
      }
      //预上传请求
      let upres = await getUploadService(
        uploadInfo.access_key_id,
        uploadInfo.secret_access_key,
        uploadInfo.session_token,
        uploadInfo.space_name,
        uploadInfo.upload_domain,
        // te.accessKeyId,
        // te.secretAccessKey,      
        // te.sessionToken,        
        // "tb4s082cfz",        
        // "imagex.bytedanceapi.com",        
        file_size,
      );
      //发送图片
      if(upres && upres.ResponseMetadata){
        let resData = upres.ResponseMetadata;
        // console.log("upres", resData);
        if(resData.Error){
          return {
            error: {
              message: resData.Error.Message,
              type: "图片服务返回错误",
              param: null,
              code: "invalid_request_error",
            },
          }
        }        
      }
      let Result = upres.Result;
      // console.log("Result", Result);
      let UploadHost = Result.UploadAddress.UploadHosts[0];
      let StoreUri = Result.UploadAddress.StoreInfos[0].StoreUri;
      let UploadID = Result.UploadAddress.StoreInfos[0].UploadID;
      let Auth = Result.UploadAddress.StoreInfos[0].Auth;
      let url = `https://${UploadHost}/upload/v1/${StoreUri}`;
      // content-crc32: b7a66685
      // console.log("url", url);
      // console.log("UploadID", UploadID);
      // console.log("Auth", Auth);
      let fres = await sendFile(url, crc32, Auth, fileBuffer);
      // console.log("fres", fres);
      if(!fres || fres.message != "Success"){
        return {
          error: {
            message: fres?(fres.message||'upload 请求失败'):'upload 请求失败',
            type: "图片上传失败",
            param: null,
            code: fres?(fres.code||505):505,
          },
        }
      }
      //上传结束
      return {
        created: util.unixTimestamp(),
        data:{
          imgURI:StoreUri,
          fileSize:file_size,
          width:dimensions.width,
          height:dimensions.height,
        },
      };
    },
  },
};
