const fs = require('fs')

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

  // 模拟交易成功
  if (posConfig && posConfig.mock && JSON.parse(m).transcode === '00') {
    let output = JSON.stringify({
      resp_code: '00',
      resp_chin: '支付成功',
      bank_code: 'aaaaa',
      cardno: 'bbbbbb',
      expr: 'ccccccc',
      trace: 'ddddddd',
      amount: '0000000000001',
      authcode: 'xxxxx',
      ordernum: 'eeeeee',
      zffs: '01',
      shopno: 'ffffff',
      terminal: 'ggggg'
    })
    process.send(output)
    process.exit(0)
  }

  const ffi = require('ffi')
  let posPath = require('path').join(posConfig.softposPath, 'MISPOS.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, {
    'BankTrans': ['int', ['char*', 'char*']]
  })

  try {
    let output = Buffer.alloc(500)
    let input = Buffer.alloc(500)
    input.write(m)
    mispos.BankTrans(input, output)

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

function exit () {
  process.send(0)
  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)))
    })
  })
}
