// pythonBridge.js
import { ref, onMounted } from 'vue';

const bridge = ref(null);

// 统一安全调用，确保 Qt 响应有回调可执行
const callBridge = (method, ...args) => {
  if (!bridge.value || typeof bridge.value[method] !== 'function') return;
  const last = args[args.length - 1];
  const hasCallback = typeof last === 'function';
  const callback = hasCallback ? args.pop() : () => { };
  bridge.value[method](...args, callback);
};

// 防御：若 Qt 返回了未知 id，忽略以免 execCallbacks 报错
const patchQWebChannel = () => {
  if (!window.QWebChannel || QWebChannel.__patchedIgnoreMissing) return;
  const originalHandleResponse = QWebChannel.prototype.handleResponse;
  QWebChannel.__patchedIgnoreMissing = true;
  QWebChannel.prototype.handleResponse = function (message) {
    const cb = this.execCallbacks && this.execCallbacks[message.id];
    if (message.id && typeof cb !== 'function') {
      console.warn('忽略未知的 WebChannel 响应', message);
      return;
    }
    return originalHandleResponse.call(this, message);
  };
};

// 初始化 QWebChannel
const initBridge = () => {
  if (/localhost/.test(window.location.href)) return;
  patchQWebChannel();
  new QWebChannel(qt.webChannelTransport, (channel) => {
    // 兜底：任何缺失的回调都返回空函数，避免 execCallbacks 报错
    channel.execCallbacks = new Proxy(channel.execCallbacks || {}, {
      get(target, prop) {
        const val = target[prop];
        if (typeof val === 'function') return val;
        // 返回空函数，确保 handleResponse 可调用
        return () => {};
      },
      set(target, prop, value) {
        target[prop] = value;
        return true;
      },
    });

    bridge.value = channel.objects.bridge;
  });
};

export function usePythonBridge() {
  // 调用 Python 方法
  const fetchDataConfig = (data) => {
    return new Promise((resolve) => {
      if (!bridge.value) return resolve(null);
      callBridge('fetchDataConfig', data, (result) => {
        resolve(result);
      });
    });
  };

  // 查询获取主播的数据
  const fetchDataCount = () => {
    return new Promise((resolve) => {
      if (!bridge.value) return resolve(null);
      callBridge('fetchDataCount', (result) => {
        resolve(result);
      });
    });
  };

  // 打开 tk 后台
  const loginTikTok = () => {
    callBridge('loginTikTok');
  };

  // 登录 tk 后台
  const loginBackStage = (data) => {
    if (data.index == 0) {
      callBridge('loginBackStage', JSON.stringify(data));
    } else if (data.index == 1) {
      callBridge('loginBackStageCopy', JSON.stringify(data));
    }
  };

  // 跳转到主播页面
  const givePyAnchorId = (id) => {
    callBridge('givePyAnchorId', id);
  };

  // 查询登录状态
  const backStageloginStatus = () => {
    return new Promise((resolve) => {
      if (!bridge.value) return resolve(null);
      callBridge('backStageloginStatus', (result) => {
        resolve(result);
      });
    });
  };

  // 查询登录状态（副账号）
  const backStageloginStatusCopy = () => {
    return new Promise((resolve) => {
      if (!bridge.value) return resolve(null);
      callBridge('backStageloginStatusCopy', (result) => {
        resolve(result);
      });
    });
  };

  // 导出表格
  const exportToExcel = (data) => {
    callBridge('exportToExcel', JSON.stringify(data));
  };

  const stopScript = () => {
    callBridge('stopScript');
  };

  // 获取版本号
  const getVersion = () => {
    return new Promise((resolve) => {
      if (!bridge.value) return resolve(null);
      callBridge('currentVersion', (result) => {
        resolve(result);
      });
    });
  };

  // 在组件挂载时初始化桥接
  onMounted(initBridge);

  return {
    fetchDataConfig,
    fetchDataCount,
    loginBackStage,
    loginTikTok,
    givePyAnchorId,
    backStageloginStatus,
    backStageloginStatusCopy,
    exportToExcel,
    stopScript,
    getVersion,
  };
}
