import http from 'axios'
const Store = require('electron-store')
const localStore = new Store()

let readerApi = {
  info: 'http://127.0.0.1:24010/ZKIDROnline/info',
  speak: 'http://127.0.0.1:24010/ZKIDROnline/ScanReadIdCardInfo?OP-DEV=1&CMD-URL=16&VoiceType=',
  readId: 'http://127.0.0.1:24010/ZKIDROnline/ScanReadIdCardInfo?OP-DEV=1&CMD-URL=4&REPEAT=1&READTYPE=1',
  finger: 'http://127.0.0.1:24010/ZKIDROnline/IDFP?OP-DEV=1&CMD-URL=1',
  iccard: 'http://127.0.0.1:24010/ZKIDROnline/MFCard?OP-DEV=1&CMD-URL=1&iPort=',
  iccardForPay: 'http://127.0.0.1:24010/ZKIDROnline/MFCard?OP-DEV=1&CMD-URL=3&Sector=1&Idx=1&Key=FFFFFFFFFFFF&iPort=',
  comName: 'http://127.0.0.1:24010/ZKIDROnline/MFCard?OP-DEV=1&CMD-URL=5'
}

export function getReaderInfo () {
  return http.post(readerApi.info)
}

export function getIdInfo () {
  return http.post(readerApi.readId).then(res => {
    try {
      let data = typeof res.data === 'string' ? JSON.parse(res.data.replace(/\r|\n|\t/g, '').replace(/\\/g, '\\\\')) : res.data
      return data
    } catch (e) {
      console.log(e)
      return {}
    }
  })
}

export function getFingerInfo () {
  return http.post(readerApi.finger)
}

export function getComName () {
  return http.post(readerApi.comName)
}

export function getIccard (comName, isPay) {
  return http.post((isPay ? readerApi.iccardForPay : readerApi.iccard) + comName).then(res => {
    try {
      let data = typeof res.data === 'string' ? JSON.parse(res.data.replace(/\r|\n|\t/g, '').replace(/\\/g, '\\\\')) : res.data
      return localStore.get('mock') ? {
        'ret': 0,
        'dev': 1,
        'data': {
          'ICdata': '900000000000000FFFFFFFFFFFFFFFFFFFFFF',
          'ICid': 562033726
        }
      } : data
    } catch (e) {
      console.log(e)
      return {}
    }
  })
}
/*
 * @export
 * @param {*} type
 * 0  请放卡
 * 1  读卡成功
 * 2  读卡失败，请重新放卡
 * 3  读卡成功，请核验指纹
 * 4  核验成功
 * 5  核验失败，请重按手指
 * 6  写卡成功
 * 7  写卡失败
 */
export function speak (type) {
  return http.post(`${readerApi.speak}${type}`)
}
