import { BusinessError } from '@ohos.base'
import http from '@ohos.net.http'
import { FormData, File, FileUpload } from "@ohos/commons-fileupload"
import fs from '@ohos.file.fs';
import ProcessRequest from '../util/request/ProcessRequest';
import web_webview from '@ohos.web.webview';
import { AxiosResponse } from '@ohos/axios';

const TAG = "openHarmonyBridge upload"


// 从webview那边穿过来的 用于上传完成后调接口的值
interface BridgeParams {
  token?: string,
  operationMediaId?: string,
  processId?: string,
  seqNo?: string,
  methodName?: string,
  apiUrlPath?: string //上传完成后调的接口 不包含baseurl
  method?: string
  stationIP?: string
  messageKey?: string //web端会进行window.addEventListener('messageKey' 然后把url整体传回去， 为了后续定义传回去对象的json {fullUrl: ''}
}

// 上传文件后，返回一个图片的url，然后再调用其他接口上传url和一些值, 如果有其他接口需要key，在这里添加，然后在下面赋值就行了
interface APIParamsModel extends BridgeParams {
  filePath?: string, //工序的多媒体采集需要用到的key
  file?: string,
  fileName?: string,
}

interface ResultModel {
  code?: string
  data?: FileDataModel
  msg?: string
}

interface FileDataModel {
  fileUrl?: string
}


class UploadUtil {
  //private baseUrl: string = JGRequestBaseUrl
  //private fileUrl: string = "http://10.88.11.201:9000" //上传完成后可以查看的
  private fileUrl: string = "http://192.168.1.3:20001" //江山
  private uploadPath: string = "/api/v1/base/upload"
  controller: web_webview.WebviewController | null = null
  ports: web_webview.WebMessagePort[] = [];

  private constructor() {
  }

  public uploadParams: BridgeParams = {}
  // public token: string = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOnsiaWQiOjEwMDAwLCJ1c2VyTmFtZSI6ImFkbWluIiwiZGVwdElkIjoxLCJzdGF0aW9uSWQiOjAsImF2YXRhciI6Ii9qZ2ZpbGUvLzIwMjQvNS8yNy8yNzQzMjkzOTU4Mzg4NTIuanBnIiwib3JnSWQiOjF9LCJkZXZpY2UiOiJiYWNrIiwiZWZmIjoxNzI0MTIyNTQwMTQwLCJyblN0ciI6IkRkakc3akFSNEtkZ1h5VWV5emhROFVib1ZlOTJUVVo4In0.yVzW8YkjiqLf9T4oUsJUPUifqPFANWX78pov8aGRsFQ"
  private static instance: UploadUtil; //单例实例

  public static getInstance(): UploadUtil {
    if (!UploadUtil.instance) {
      UploadUtil.instance = new UploadUtil();
    }
    return UploadUtil.instance;
  }

  public configUploadParam(p: string) {
    let model: BridgeParams = JSON.parse(p)
    this.uploadParams = model
  }

  startUploadBase64(uri: string, callBack: () => void) {
    try {
      let base64Test =  fs.readTextSync(uri)
      console.log(TAG, "baes64",base64Test)

      let base64Data: APIParamsModel = {
        file: base64Test,
        fileName: 'test.jpg',
      }
      ProcessRequest.request({
        method:  "post",
        url: "/api/v1/base/uploadBase64",
        data: base64Data
      }).then( async (res: AxiosResponse) => {

        let result: FileDataModel = JSON.parse(JSON.stringify(res))


        // 上传完成后调其他接口
        if (result.fileUrl) {
          let data: APIParamsModel = {
            filePath: result.fileUrl,
            operationMediaId: this.uploadParams?.operationMediaId ,
            processId: this.uploadParams?.processId ,
            seqNo: this.uploadParams?.seqNo ,
          }

          await ProcessRequest.request({
            method: this.uploadParams?.method ,
            url: this.uploadParams.apiUrlPath,
            data: data
          })
        }

        // 这个是 给webview发送post messages 通知的
        if (this.uploadParams.messageKey) {
          uploadInstance.ports = uploadInstance.controller!.createWebMessagePorts();
          uploadInstance.controller!.postMessage(JSON.stringify({
            fullUrl: this.fileUrl + result.fileUrl ?? "",
            messageKey: this.uploadParams.messageKey ?? ""
          }), [uploadInstance.ports[0]], '*');
        }

        callBack()
      }).catch(() => {
        callBack()
      })


    }
    catch (e) {
      callBack()
      console.log(TAG, 'mk-logger', 'photoPlugin-str', JSON.stringify(e))
    }
  }

  startUpload(uri: string, callBack: () => void) {


    //   开始上传
    try {
      // 2.2 根据uri同步打开文件
      const file = fs.openSync(uri)
      // 2.3 同步获取文件的详细信息
      const stat = fs.statSync(file.fd)
      // 2.4 创建缓冲区存储读取的文件流
      const buffer = new ArrayBuffer(stat.size)
      // 2.5 开始同步读取文件流到缓冲区
      fs.readSync(file.fd, buffer)
      // 2.6 关闭文件流
      fs.closeSync(file)

      // 3. 转成base64编码的字符串
      // const helper = new util.Base64Helper()
      // const str = helper.encodeToStringSync(new Uint8Array(buffer))
      // console.log('mk-logger', 'photoPlugin-str', buffer.byteLength, JSON.stringify(buffer))

      let toUpFile = new File()
      toUpFile.fileName = "test.jpg"
      toUpFile.fileData = buffer

      let fileUpload = new FileUpload({
        //baseUrl: this.baseUrl,
        readTimeout: 60000,
        connectTimeout: 60000,
      })

      const formData = new FormData();
      // formData.append("key", 1); //可以添加基本类型的值，目前支持string、number
      // formData.append("fileName", "test.jpg"); //也可以添加File类型的对象
      formData.append('file', toUpFile)
      console.log(TAG,"================toUpFile", toUpFile)
      console.log(TAG,"================formData", formData)
      fileUpload.post(this.uploadPath, formData, {
        header: {
          'Content-Type': 'multipart/form-data',
          // "Authorization": this.token
          'Authorization': this.uploadParams?.token ?? "",
        },
      }).then(async (res: http.HttpResponse) => {

        let result: ResultModel = JSON.parse(res.result as string)
        console.log(TAG, "ddddddd success", JSON.stringify(result?.data ?? ""));


        // 上传完成后调其他接口
        if (this.uploadParams.apiUrlPath) {
          let data: APIParamsModel = {
            filePath: result.data?.fileUrl ?? "",
            operationMediaId: this.uploadParams?.operationMediaId ?? "",
            processId: this.uploadParams?.processId ?? "",
            seqNo: this.uploadParams?.seqNo ?? "",
          }

          await ProcessRequest.request({
            method: this.uploadParams?.method ?? "post",
            url: this.uploadParams?.apiUrlPath,
            data: data
          })
        }

        // 这个是 给webview发送post messages 通知的
        if (this.uploadParams.messageKey) {
          uploadInstance.ports = uploadInstance.controller!.createWebMessagePorts();
          uploadInstance.controller!.postMessage(JSON.stringify({
            fullUrl: this.fileUrl + result.data?.fileUrl ?? "",
            messageKey: this.uploadParams.messageKey ?? ""
          }), [uploadInstance.ports[0]], '*');
        }

        callBack()

        //上传完成后浏览器可以产看的图片地址  http://10.88.11.201:9000
      }).catch((err: BusinessError) => {
        callBack()
        console.error(TAG, "ddddddd    fail", JSON.stringify(err));
      })
    }
    catch (e) {
      callBack()
      console.log(TAG, 'mk-logger', 'photoPlugin-str', JSON.stringify(e))
    }
  }
}

let uploadInstance = UploadUtil.getInstance();

export default uploadInstance;