import { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from "@ohos/axios"
import promptAction from '@ohos.promptAction'

// 是否在控制台打印某项log
const pConfig = true
const pHeaders = true
const pUrl = true
const pParams = true
const pBody = true
const pResponse = true
const pData = true
const pError = true

const TAG = "openHarmonyBridge" //webview和vue沟通的名称

// @CustomDialog
// struct CustomDialogExample {
//   controller: CustomDialogController
//   build() {
//     Column() {
//       Text('我是内容')
//         .fontSize(20)
//         .margin({ top: 10, bottom: 10 })
//     }
//   }
// }

const printRequest = (config: InternalAxiosRequestConfig) => {
  if (pConfig) {
    console.debug(TAG, "printRequest config", JSON.stringify(config))
  }

  if (pHeaders) {
    console.debug(TAG, "printRequest headers", JSON.stringify(config.headers))
  }

  if (pUrl) {
    console.debug(TAG, "printRequest url", `Method:${config.method} ${config.baseURL}${config.url}`)
  }

  if (pBody) {
    console.debug(TAG, "printRequest 请求参数data", JSON.stringify(config.data))
  }

  if (pParams) {
    console.debug(TAG, "printRequest 请求参数params", JSON.stringify(config.params))
  }

}

const printResponse = (response: AxiosResponse) => {
  if (pResponse) {
    console.debug(TAG, 'printResponse response: ', JSON.stringify(response))
  }
  if (pData) {
    console.debug(TAG, "printResponse data", JSON.stringify(response.data))
  }
}

const printError = (error: AxiosError) => {
  if (pError) {
    console.debug(TAG, "printError error", error.message)
  }
  promptAction.showToast({
    message: error.message ?? "请求出错",
    duration: 1500,
    bottom: 100
  })
}


// 处理返回数据
const handleRes = (response: AxiosResponse): [boolean, string] => {
  let isSuccess = true
  let msg = ""

  if (response.status === 200) { //判断返回状态是否为200
    if (String(response.data?.code) === "200") { //判断数据的code是否为200，有可能是500的服务器错误
      isSuccess = true
      msg = `请求数据成功`
    }
    else {
      isSuccess = false
      // msg = `${response.data?.code}: ${response.data?.msg ?? "服务器错误"}`
      msg = `${response.data?.msg ?? "服务器错误"}`
    }
  }
  else {
    isSuccess = false
    msg = `状态码非200 status: ${response.status}}`
  }

  if (!isSuccess) {
    promptAction.showToast({
      message: msg,
      duration: 1500,
      bottom: 100
    })

    // const dialogController: CustomDialogController = new CustomDialogController({
    //   builder: CustomDialogExample({}),
    // })
    // dialogController.open()
  }

  return [isSuccess, msg]
}


export { printRequest, printResponse, printError, handleRes }