const baseUrl = 'http://127.0.0.1:6045'

/**
 * 列出所有读卡设备
 */
export function listCard() {
  return new Promise((resolve, reject) => {
    window.$.ajax({
      contentType: 'application/json;charset=UTF-8',
      dataType: 'jsonp',
      timeout: 10000,
      jsonp: 'callback',
      url: `${baseUrl}/getCardReaderList`,
      success: function(resultInfo, status) {
        // 取出错误信息
        const error = resultInfo.filter(r => r.error)
        // 如果设备报错，且全都是错误信息，则取出第一个报错信息
        if (error.length > 0 && error.length === resultInfo.length) {
          return reject(error.map(e => e.error).join(','))
        }
        resolve(resultInfo)
      },
      error: function(jqXHR, textStatus, errorThrown) {
        reject(errorThrown)
      }
    })
  })
}

export function readCard(readerIndex = 0) {
  const param = '{"portType": 5}'
  return new Promise((resolve, reject) => {
    window.$.ajax({
      contentType: 'application/json;charset=UTF-8',
      dataType: 'jsonp',
      timeout: 10000,
      jsonp: 'callback',
      url: baseUrl + '/readCard?param=' + param + '&index=' + readerIndex,
      success(resultInfo, status) {
        // 如果接口返回正确
        if (resultInfo && resultInfo.resultFlag === 0) {
          // 如果性别是中文，则转换成数值类型
          resultInfo.resultContent.gender = resultInfo.resultContent.gender === '男' ? '1' : '2'
          resolve(resultInfo.resultContent)
        } else {
          reject(resultInfo ? resultInfo.errMsg : '设备驱动失败，请重试')
        }
      },
      error(jqXHR, textStatus, errorThrown) {
        reject(errorThrown)
      }
    })
  })
}

export function readCardNumber(readerIndex = 1) {
  return new Promise((resolve, reject) => {
    window.$.ajax({
      contentType: 'application/json;charset=UTF-8',
      dataType: 'jsonp',
      timeout: 10000,
      jsonp: 'callback',
      url: baseUrl + '/readCardNo?index=' + readerIndex,
      success(resultInfo, status) {
        resolve(resultInfo)
      },
      error(jqXHR, textStatus, errorThrown) {
        reject(errorThrown)
      }
    })
  })
}
