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).tradeType === 'C') {
    process.send('00621485******8058   C000000000001000491907921687738091      130804630025191046300569111160804145549D_U                                                                0000000000010000000000000804145549000491921687738091      130804                                                     001')
    process.exit(0)
  }

  // 模拟退货成功
  if (posConfig && posConfig.mock && JSON.parse(m).tradeType === 'R') {
    process.send('00621485******8058   C000000000001000491308921687738091      130804630025191046300569111160804145549D_U                                                                0000000000010000000000000804145549000491921687738091      130804                                                     001')
    process.exit(0)
  }

  // console.log('子进程接收到消息' + m, __dirname)
  const ffi = require('ffi')
  let posPath = require('path').join(posConfig.softposPath, 'softpos.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)

  console.log('软件路径', posPath)

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

  try {
    let output = Buffer.alloc(287)
    let input = Buffer.alloc(287)
    input.write(getPayParams(JSON.parse(m)))
    softpos.CreditTransABC(input, output)
    // 输出结果
    process.send(output.toString('utf-8'))

    process.kill(process.pid)
    process.exit(0)
  } catch (e) {
    console.log('错误', e)
  }
  // sendHandle是一个 net.Socket 或 net.Server 对象
})

process.on('uncaughtException', function (err) {
  console.log('捕获到一个未被处理的错误:', err)
})

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

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.log({
    termId, salerId, tradeType, total, payType, codeInfo, originalInfo
  })

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

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)))
    })
  })
}
