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)

  const ffi = require('ffi')
  let posPath = require('path').join(posConfig.softposPath, 'posinf.dll')

  console.log(posPath)

  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)

  // process.env.PATH = `${process.env.PATH}${path.delimiter}${posConfig.softposPath}`

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

  try {
    // 有时候无法调起成功，可能是因为位数不够
    let output = Buffer.alloc(1024)
    let input = Buffer.alloc(1024)

    input.write(getPayParams(JSON.parse(m)))
    mispos.bankall(input, output)

    process.send(output)
    process.kill(process.pid)
    process.exit(0)
  } catch (e) {
    process.send(e.toString())
    process.kill(process.pid)
    process.exit(0)
  }
})

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

function getPayParams (params) {
  let { transId, amt, tradeDate, refNo, traceNo, LRC, memo, bankOderNo, ERP, qrcodeId, mchtBill, remarks } = params

  amt = (parseInt(params.amt * 100) + '').padStart(12, '0')
  tradeDate = tradeDate.padStart(8, ' ')
  traceNo = traceNo.padStart(12, ' ') // 参考号
  refNo = refNo.padStart(6, ' ') // 凭证号
  LRC = (new Date().getTime() + '').slice(-3) // 3位随机数
  memo = memo.padEnd(50, ' ')
  bankOderNo = bankOderNo.padEnd(50, ' ')
  ERP = ERP.padEnd(50, ' ')
  qrcodeId = qrcodeId.padEnd(32, ' ')
  mchtBill = mchtBill.padEnd(20, ' ')
  remarks = remarks.padEnd(40, ' ')

  return transId + amt + tradeDate + traceNo + refNo + LRC + memo + bankOderNo + ERP + qrcodeId + mchtBill + remarks
}
