const fs = require('fs')

process.on('message', async (message, setHandle) => {
  try {
    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, 'PortComm.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, {
      'POSP_Chang': ['int', ['char*', 'char*', 'char*']]
    })

    let output = Buffer.alloc(1024)
    let input = Buffer.alloc(1024)
    let pszCommData = Buffer.alloc(0)
    input.write(getPayParams(JSON.parse(m)))

    // input.write(getPayParams(refundParams))

    // 执行操作
    mispos.POSP_Chang(pszCommData, input, output)

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

function exit (info) {
  process.send(info)
  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 { transCode, amt, tradeId, traceNo, refNo, tradeDate, orderNo, addition } = params

  amt = (parseInt(params.amt * 100) + '').padStart(12, '0')
  traceNo = traceNo.padEnd(6, ' ') // 参考号
  refNo = refNo.padEnd(30, ' ') // 凭证号
  orderNo = orderNo.padEnd(30, ' ')
  addition = addition.padEnd(255, ' ')

  return transCode + amt + tradeId + traceNo + refNo + tradeDate + orderNo + addition
}
