/**
 * PK Mini 模块专用 GoEasy 实例
 *
 * 使用前请确保在 src/config/pk-mini.js 中将 GOEASY_ENABLED 设为 true
 */
import GoEasy from 'goeasy'
import { pkIMloginStore } from '@/stores/pk-mini/notice.js'
import { PK_MINI_CONFIG, isGoEasyEnabled } from '@/config/pk-mini.js'

// PK Mini 模块专用 GoEasy 实例
let pkGoEasyInstance = null

// 获取或创建 PK GoEasy 实例
export function getPkGoEasy() {
  if (!isGoEasyEnabled()) {
    console.warn('[PK GoEasy] GoEasy 未启用，请在 src/config/pk-mini.js 中设置 GOEASY_ENABLED: true')
    return null
  }

  if (!pkGoEasyInstance) {
    console.log("GoEasy", GoEasy)
    pkGoEasyInstance = GoEasy.getInstance({
      host: PK_MINI_CONFIG.GOEASY.HOST,
      appkey: PK_MINI_CONFIG.GOEASY.APP_KEY,
      modules: ['im']
    })
  }
  return pkGoEasyInstance
}

// 初始化 PK GoEasy (在 PkMiniWorkbench 挂载时调用)
export function initPkGoEasy() {
  if (!isGoEasyEnabled()) {
    console.warn('[PK GoEasy] GoEasy 未启用')
    return null
  }
  return getPkGoEasy()
}

// 链接 IM (登录 IM)
export function goEasyLink(data) {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  const counter = pkIMloginStore()
  return new Promise((resolve, reject) => {
    goeasy.connect({
      id: data.id,
      data: { avatar: data.avatar, nickname: data.nickname },
      otp: data.key,
      onSuccess: function () {
        console.log('PK IM 连接成功')
        counter.setIMstate(true)
        data.onSuccess?.()
        resolve(true)
      },
      onFailed: function (error) {
        console.log('PK IM 连接失败，错误码：' + error.code + '，错误信息：' + error.content)
        data.onFailed?.(error)
        reject(error)
      },
      onProgress: function (attempts) {
        console.log('PK IM 正在重连中...')
        data.onProgress?.(attempts)
      }
    })
  })
}

// 断开 IM
export function goEasyDisConnect() {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  return new Promise((resolve, reject) => {
    goeasy.disconnect({
      onSuccess: function () {
        resolve(true)
      },
      onFailed: function (error) {
        console.log('断开失败, code:' + error.code + ',error:' + error.content)
        reject(error)
      }
    })
  })
}

// 获取会话列表
export function goEasyGetConversations() {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  const im = goeasy.im
  return new Promise((resolve, reject) => {
    im.latestConversations({
      onSuccess: function (result) {
        console.log('会话列表', result)
        resolve(result)
      },
      onFailed: function (error) {
        console.log('获取会话列表失败，错误码：' + error.code + ' content:' + error.content)
        reject(error)
      }
    })
  })
}

// 获取指定会话的消息列表
export function goEasyGetMessages(data) {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  const im = goeasy.im
  return new Promise((resolve, reject) => {
    im.history({
      id: data.id,
      type: GoEasy.IM_SCENE.PRIVATE,
      lastTimestamp: data.timestamp,
      limit: 30,
      onSuccess: function (result) {
        resolve(result.content)
      },
      onFailed: function (error) {
        console.log('获取消息列表失败，错误码：' + error.code + ' content:' + error.content)
        reject(error)
      }
    })
  })
}

// 发送文本消息
export function goEasySendMessage(data) {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }
  console.log("```````````````````````名称``````````````````````", data.nickname);

  const goeasy = getPkGoEasy()
  const im = goeasy.im
  let textMessage = im.createTextMessage({
    text: data.text,
    to: {
      type: GoEasy.IM_SCENE.PRIVATE,
      id: data.id,
      data: { avatar: data.avatar, nickname: data.nickname }
    }
  })
  return new Promise((resolve, reject) => {
    im.sendMessage({
      message: textMessage,
      onSuccess: function () {
        resolve(textMessage)
      },
      onFailed: function (error) {
        console.log('Failed to send private message，code:' + error.code + ' ,error ' + error.content)
        reject(error)
      }
    })
  })
}

// 发送图片消息
export function goEasySendImageMessage(data) {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  const im = goeasy.im
  const message = im.createImageMessage({
    file: data.imagefile,
    to: {
      type: GoEasy.IM_SCENE.PRIVATE,
      id: data.id,
      data: { avatar: data.avatar, nickname: data.nickname }
    }
  })
  return new Promise((resolve, reject) => {
    im.sendMessage({
      message: message,
      onSuccess: function () {
        resolve(message)
      },
      onFailed: function (error) {
        console.log('Failed to send message，code:' + error.code + ',error' + error.content)
        reject(error)
      }
    })
  })
}

// 发送 PK 消息
export function goEasySendPKMessage(data) {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  const im = goeasy.im
  const customData = {
    id: data.msgid,
    pkIdA: data.pkIdA,
    pkIdB: data.pkIdB
  }

  const order = {
    customData: customData,
    link: 'https://vv-1317974657.cos.ap-shanghai.myqcloud.com/util/pk.png',
    text: 'PK'
  }

  const customMessage = im.createCustomMessage({
    type: 'pk',
    payload: order,
    to: {
      type: GoEasy.IM_SCENE.PRIVATE,
      id: data.id,
      data: { avatar: data.avatar, nickname: data.nickname }
    }
  })

  return new Promise((resolve, reject) => {
    im.sendMessage({
      message: customMessage,
      onSuccess: function () {
        resolve(customMessage)
      },
      onFailed: function (error) {
        console.log('Failed to send message，code:' + error.code + ',error' + error.content)
        reject(error)
      }
    })
  })
}

// 消息已读
export function goEasyMessageRead(data) {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  const im = goeasy.im
  return new Promise((resolve, reject) => {
    im.markMessageAsRead({
      id: data.id,
      type: GoEasy.IM_SCENE.PRIVATE,
      onSuccess: function () {
        resolve(true)
      },
      onFailed: function (error) {
        console.log('标记私聊已读失败', error)
        reject(error)
      }
    })
  })
}

// 撤回消息
export function goEasyRecallMessage(message) {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  const im = goeasy.im
  return new Promise((resolve, reject) => {
    im.recallMessage({
      messages: [message],
      onSuccess: function () {
        resolve(true)
      },
      onFailed: function (error) {
        console.log('撤回失败, code:' + error.code + ' content:' + error.content)
        reject(error)
      }
    })
  })
}

// 删除会话
export function goEasyRemoveConversation(conversation) {
  if (!isGoEasyEnabled()) {
    return Promise.reject(new Error('GoEasy 未启用'))
  }

  const goeasy = getPkGoEasy()
  const im = goeasy.im
  return new Promise((resolve, reject) => {
    im.removeConversation({
      conversation: conversation,
      onSuccess: function () {
        resolve(true)
      },
      onFailed: function (error) {
        console.log('删除会话失败，code:' + error.code + ',error:' + error.content)
        reject(error)
      }
    })
  })
}

// 导出 GoEasy 常量（用于事件监听）
export { GoEasy }
