import jsonp from 'jsonp';  // 引入 jsonp 库

const orgId = 'H33060201427' // 医保机构id

const cardBASEURL = 'http://localhost:8732';
const scanQrcodeURL = `${cardBASEURL}/Design_Time_Addresses/Service/ServiceDk/DzpzRead?businessType=01101&orgId=${orgId}`;
const readCardURL = `${cardBASEURL}/Design_Time_Addresses/Service/ServiceDk/CardRead`
const fingerprintURL = `${cardBASEURL}/Design_Time_Addresses/Service/ServiceDk/FingerRead`
const fingerMatchURL = `${cardBASEURL}/Design_Time_Addresses/Service/ServiceDk/FingerMatch`


function toObject(str) {
  try {
    const data = JSON.parse(str);
    return data
  } catch (e) {
    return str
  }
}

const jsonpRequest = (url, msg, timeout = 30 * 1000) => {
  return new Promise((resolve, reject) => {
    let timer = null;
    if (timeout > 0) {
      timer = setTimeout(() => {
        reject(msg || '请求超时');  // 超时后 reject
      }, timeout);
    }
    jsonp(url, { param: 'jsoncallback' }, (err, data) => {
      timer && clearTimeout(timer)
      if (err) {
        reject(err);
      } else {
        resolve(toObject(data));
      }
    });
  })
};

export function scanCodeApi() {
  return jsonpRequest(scanQrcodeURL)
}

export function getReadCardApi() {
  return jsonpRequest(readCardURL, '读取卡信息超时')
}

export function getFingerprintApi() {
  return jsonpRequest(fingerprintURL, '读取指纹信息超时')
}

export function getFingerMatchApi({ fingerA, fingerB, timeout = 30 * 1000 } = {}) {
  if (!fingerA && !fingerB) {
    return Promise.reject(new Error('缺少指纹比对参数: fingerA / fingerB 至少需要一个'));
  }

  const encodedFingerA = encodeURIComponent(fingerA);
  const encodedFingerB = encodeURIComponent(fingerB);
  const url = `${cardBASEURL}/Design_Time_Addresses/Service/ServiceDk/FingerMatch?finger=${encodedFingerA}&finger2=${encodedFingerB}`
  console.log("指纹获取:", url);
  return jsonpRequest(url, '指纹比对超时', timeout);
}