process.on('message', (m, setHandle) => {
  // console.log('子进程接收到消息' + m, __dirname)
  const ffi = require('ffi')
  let posPath = require('path').join(__dirname, 'softpos.dll')
  if (process.env.NODE_ENV !== 'development') {
    posPath = posPath.replace('app.asar', 'app.asar.unpacked')
  }

  console.log(posPath)
  let softpos = ffi.Library(posPath, {
    'CreditTrans': ['int', ['char*', 'char*']]
  })

  try {
    let output = Buffer.alloc(287)
    let input = Buffer.alloc(287)
    input.write(getPayParams(JSON.parse(m)))
    softpos.CreditTrans(input, output)
    // 输出结果
    process.send(output.toString('utf-8'))
  } catch (e) {
    console.log('错误', e)
  }
  // sendHandle是一个 net.Socket 或 net.Server 对象
})

function getPayParams (params) {
  let { termId, salerId, tradeType, total, payType, codeInfo, originalInfo } = params
  termId = termId.padEnd(10)
  salerId = salerId.padEnd(10)
  total = total.padStart(12, '0')
  codeInfo = codeInfo.padEnd(32)
  originalInfo = originalInfo.padEnd(96)

  console.table({
    termId, salerId, tradeType, total, payType, codeInfo, originalInfo
  })

  return termId + salerId + tradeType + total + payType + codeInfo + originalInfo
}
