const fs = require('fs')

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

  const ffi = require('ffi')
  let posPath = require('path').join(posConfig.softposPath, 'sldll.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}`

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

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

    input.write(getPayParams(JSON.parse(m)))
    mispos.CardTrans(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) => {
    const configFile = path

    const 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, posTradeNo = '', cashierDevNo = '', cashierNo = '', traceNo = '', authNo = '', orgTradeDate = '', cardType, tradeIndex, secondTrack = '', thirdTrack = '', orgTradeCode = '', orgTerminalNo = '', orgAuthNo = '', accountNo = '', mallNo = '', billNo = '', orderNo = '', orgRefNo = '', orgTradeTime = '', orgTradeAmt = '' } = params

  amt = (parseInt(params.amt * 100) + '').padStart(12, '0')
  posTradeNo = posTradeNo.padEnd(6, ' ')
  cashierDevNo = cashierDevNo.padEnd(10, ' ')
  cashierNo = cashierNo.padEnd(10, ' ')
  traceNo = traceNo.padStart(15, ' ')
  authNo = authNo.padStart(6, ' ')
  orgTradeDate = orgTradeDate.padStart(8, ' ')
  tradeIndex = tradeIndex.padStart(76, ' ')
  secondTrack = secondTrack.padStart(37, ' ')
  thirdTrack = thirdTrack.padStart(104, ' ')
  orgTradeCode = orgTradeCode.padStart(2, ' ')
  orgTerminalNo = orgTerminalNo.padStart(15, ' ')
  orgAuthNo = orgAuthNo.padStart(6, ' ')
  accountNo = accountNo.padStart(3, ' ')
  mallNo = mallNo.padEnd(20, ' ')
  billNo = billNo.padEnd(30, ' ')
  orderNo = orderNo.padStart(15, ' ')
  orgRefNo = orgRefNo.padStart(6, ' ')
  orgTradeTime = orgTradeTime.padStart(6, ' ')
  orgTradeAmt = orgTradeAmt.padStart(12, ' ')

  return transId + amt + posTradeNo + cashierDevNo + cashierNo + traceNo + authNo + orgTradeDate + cardType + tradeIndex + secondTrack + thirdTrack + orgTradeCode + orgTerminalNo + orgAuthNo + accountNo + mallNo + billNo + orderNo + orgRefNo + orgTradeTime + orgTradeAmt
}
