import { Message } from 'element-ui'
import { getPayResponse } from '@/utils'
// import iconv from 'iconv-lite'
import moment from 'moment'
const Store = require('electron-store')
const localStore = new Store()

const iconv = require('iconv-lite')
const log = require('electron-log')

export default (transcode, params, vue) => {
  let amount

  if (params.memberTrade) {
    amount = parseInt(params.memberTrade.total_money) * 100 + ''
  } else {
    amount = parseInt(params.price * 100) + ''
  }

  return new Promise((resolve, reject) => {
    if (localStore.get('mock')) {
      setTimeout(() => {
        resolve(JSON.stringify({ 'bank_code': '0308', 'shopno': '104328679910002', 'terminal': '32160740', 'cardno': '6225758111667621    ', 'expr': '2201', 'trace': '001723', 'amount': '000000000100', 'ordernum': '102141156876                                      ', 'zffs': '01', 'preorder': 'AD6DCCD1D49FFB78', 'resp_code': '00', 'resp_chin': '交易成功' }))
      }, 5000)

      return
    }

    let originalInfo = params.bocTradeNo ? getPayResponse(params.bocTradeNo) : ''
    console.log('原始信息', originalInfo)

    let inputData = {
      transcode, // 交易码
      amount: amount.padStart(12, '0'), // 金额
      old_date: originalInfo ? moment(params.createTime).format('YYYYMMDD') : '', // 原交易日期create_time
      old_reference: originalInfo ? '192543245926' : '', // 原交易参考号
      zffs: originalInfo ? originalInfo.zffs.trim() : '',
      // zffs: '03',
      old_orderno: originalInfo ? originalInfo.ordernum.trim() : '',
      // 重打印，使用参数传的值
      old_trace: params.trace_no || (originalInfo ? originalInfo.trace.trim() : '') // 原流水
    }
    console.log('输入', inputData)
    const { fork } = require('child_process')
    const path = require('path')

    let child = fork(path.join(__static, 'pos', 'mis.js'))

    // 支付进程传回页面实例，便于退出

    // 确认vue.posProcess可以push
    console.log('vue.posProcess', vue.posProcess)
    if (!vue.posProcess) {
      vue.posProcess = [] //  有可能vue.posProcess为undefined
      // 防止vue.posProcess为undefined时，vue.posProcess.push(child) 悄悄失败
    }

    vue.posProcess.push(child)

    log.info(`Pos输入：${JSON.stringify(inputData)}`)
    child.send(localStore.path + '=' + JSON.stringify(inputData))
    console.log(localStore.path + '=' + JSON.stringify(inputData))

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

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

      console.log(result)

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

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

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

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

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