import { Message } from 'element-ui'
import { getPayResponse } from '@/utils/posUtils'
// import moment from 'moment'

const Store = require('electron-store')
const localStore = new Store()
const iconv = require('iconv-lite')
const log = require('electron-log')

function getTranscode (transType, params) {
  const qrCodeArr = ['0', '1', '2', '3']

  switch (transType) {
    case 'C':
      return params.payChannel === '银行卡' ? '01' : '72'
    case 'R':
      const originalInfo = params.bocTradeNo ? getPayResponse(params.bocTradeNo) : ''
      return qrCodeArr.indexOf(originalInfo?.tradeCode?.replace(' ', '')) > -1 ? '73' : '09'
  }
}

export default (transType, params, vue) => {
  log.info('建行支付')
  return new Promise((resolve, reject) => {
    // 模拟支付
    if (localStore.get('mock')) {
    //   resolve('00招商银行621483******7245    407780000000000001交易成功                                898319947330106010600070001480722170501000193053349000000    23900000000000100000000000000000000000000000000000001CUP                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      ')

    //   return
    }

    const { fork } = require('child_process')
    const path = require('path')

    const originalInfo = params.bocTradeNo ? getPayResponse(params.bocTradeNo) : ''

    console.log(originalInfo)

    // let tradeDate = originalInfo?.tradeDate || ''
    const transId = getTranscode(transType, params)

    if (!transId) {
      Message.error('参数错误')
      resolve()
      return
    }

    const inputData = {
      transId,
      amt: params.memberTrade ? params.memberTrade.total_money : params.price,
      cardType: params.payChannel === '银行卡' ? 'H' : 'U',
      tradeIndex: '',
      traceNo: originalInfo?.traceNo || '',
      thirdTrack: originalInfo?.qrCodeOrderNo || '', // 二维码退款
      orgTradeDate: originalInfo?.bankDate?.slice(-4) || '' // 原交易日期
    }

    const child = fork(path.join(__static, 'pos', 'lbyPos_jh.js'))
    // 支付进程传回页面实例，便于退出
    vue.posProcess.push(child)

    console.log(getPayParams(inputData))

    log.info(`Pos输入：${JSON.stringify(inputData)}`)

    // eslint-disable-next-line no-unreachable
    child.send(localStore.path + '=' + JSON.stringify(inputData))

    child.on('message', msg => {
      console.log(msg)
      if (msg === 0) {
        Message.error(`未找到银行支付程序，查找路径为${localStore.get('softposPath')}`)
        resolve()
        return
      }

      const result = iconv.decode(Buffer.from(msg.data), 'gbk').replace(/\0/g, '')

      //   const response = JSON.parse(result)
      console.log('收到子进程消息', result)

      log.info(`Pos输出：${result}`)

      const response = getPayResponse(result)
      console.log(response)
      if (response.rescode !== '000000') {
        Message.error(response.rescodeInfo)
        resolve()
      } else {
        resolve(result)
      }
    })

    child.on('exit', () => {
      log.info('支付进程结束')
    })

    child.on('uncaughtException', function (err) {
      log.info('未知错误' + JSON.stringify(err))
      console.log('捕获到一个未被处理的错误:', err)
      reject(err)
    })
  })
}

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
}
