const fs = require('fs')

process.on('message', async (message, setHandle) => {
  try {
    let path = message.split('=')[0]
    let m = message.split('=')[1]
    let posConfig = await getPosConfigData(path)

    const ffi = require('ffi')
    let posPath = require('path').join(posConfig.softposPath, 'BlueComClient.dll')
    const isExist = fs.existsSync(posPath)

    if (!isExist) {
    // 未找到支付程序
      exit()
    }

    if (process.env.NODE_ENV !== 'development') {
      posPath = posPath.replace('app.asar', 'app.asar.unpacked')
    }

    const kernel32 = ffi.Library('kernel32', {
      'SetDllDirectoryA': ['bool', ['string']]
    })

    kernel32.SetDllDirectoryA(posConfig.softposPath)

    let mispos = ffi.Library(posPath, {
      'APOSBankTrans': ['int', ['char*', 'char*']]
    })

    let output = Buffer.alloc(1024)
    mispos.APOSBankTrans(Buffer.from(m, 'hex'), output)

    // 输出结果
    process.send(output)
    process.kill(process.pid)
    process.exit(0)
  } catch (e) {
    exit(e)
  }
})

function exit (info) {
  process.send(info)
  process.kill(process.pid)
  process.exit(0)
}

function getPosConfigData (path) {
  return new Promise((resolve, reject) => {
    let configFile = path
    console.log(configFile)
    let fs = require('fs')
    fs.open(configFile, 'r', (err, data) => {
      if (err) {
        console.log(err)
        resolve()
        return
      }
      resolve(JSON.parse(fs.readFileSync(configFile)))
    })
  })
}
