// /* eslint-disable */
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')

const channelMap = {
  '聚合扫码': '02', // 无硬件扫码
  '银行卡': '00'
}

function getTranscode (transType, params) {
  let transcode
  let record = params.bocTradeNo ? getPayResponse(params.bocTradeNo) : ''

  // 根据交易类型切换transcode
  switch (transType) {
    // 支付
    case 'C':
      transcode = channelMap[params.payChannel] + String('').padStart(16, ' ') + '00'
      break
    case 'R':
      // 根据配置页设置 revoke：撤销；refunds: 退货
      const refundWay = localStore.get('refundWay') || 'revoke'
      // 只能使用撤销，退货未开通。有支付方式则为扫码支付，否则是银行卡支付

      const isOnline = ['0ZFB', 'WXZF', 'YLSM'].indexOf(record?.bankNo) > -1

      if (isOnline) {
        transcode = '02' + String('').padStart(16, ' ') + '02' // 在线支付使用退货
      } else {
        transcode = '00' + String('').padStart(16, ' ') + (refundWay === 'revoke' ? '01' : '02') // 银行卡根据系统配置
      }
      break
    case 'S':
      // 签到
      transcode = '0005'
  }

  return transcode
}

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

        return
      }

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

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

      console.log(originalInfo)

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

      let inputData = {
        transId,
        amt: params.memberTrade ? params.memberTrade.total_money : params.price,
        old_date: tradeDate ? moment().format('YYYY') + tradeDate : '',
        old_reference: originalInfo?.refNo || '',
        old_trace: originalInfo?.traceNo || '',
        lrc: '',
        postCode: params.qrCode || '',
        unionMerchant: originalInfo?.unionMerchant || '',
        erpMerchant: '',
        qrCodeId: ''
      }

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

      log.info(`Pos输入：${JSON.stringify(inputData)}`)
      // return
      // // 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
        }

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

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

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

        let response = getPayResponse(result)

        if (response.rescode !== '00') {
          Message.error(response.infoMsg)
          resolve()
        } else {
          resolve(result)
        }
      })

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

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

      console.log(inputData)
    } catch (e) {
      console.error(e)
    }
  })
}
