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 = {
  '银行卡': '01',
  '聚合扫码': '02'
}

function getTranscode (transType, params) {
  let transcode
  let record = params.bocTradeNo ? getPayResponse(params.bocTradeNo) : ''
  // 根据交易类型切换transcode
  switch (transType) {
    // 支付
    case 'C':
      transcode = channelMap[params.payChannel]
      break
    case 'R':
      // 只能使用撤销，退货未开通。有支付方式则为扫码支付，否则是银行卡支付
      transcode = (record?.tradeType === 'S1' ? '04' : '03')
      break
    case 'S':
      // 签到
      transcode = '0005'
  }

  return transcode
}

export default (transType, params, vue) => {
  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')
    let originalInfo = params.bocTradeNo ? getPayResponse(params.bocTradeNo) : ''
    // let tradeDate = originalInfo?.tradeDate || ''
    let transCode = getTranscode(transType, params)
    // params.memberTrade
    let inputData = {
      transCode,
      amt: params.memberTrade ? params.memberTrade.total_money : params.price,
      tradeId: moment().format('YYMMDDHHmmss'), // 外部订单号,保证交易唯一性
      traceNo: originalInfo?.traceNo || '', // 凭证号， 撤销时用
      refNo: (originalInfo?.refNo?.replace(/\s+/g, '') || originalInfo?.orderNo?.replace(/\s+/g, '')) || '', // 参考号， 退货时用
      tradeDate: originalInfo?.dateTime?.slice(0, 8) || moment().format('YYYYMMDD'), // 退货用，交易日期
      orderNo: originalInfo?.orderNo?.replace(/\s+/g, '') || '', // 订单号
      addition: '' // 附加信息
    }
    let child = fork(path.join(__static, 'pos', 'fxsPos.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 => {
      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)
      log.info(`Pos输出：${result}`)
      let response = getPayResponse(result)

      console.log('收到子进程消息', response)

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

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

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