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

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

// 测试环境
const POS_ENV = 'dev'

function getTranscode (transType, params) {
  let transcode
  let record = params.bocTradeNo ? getPayResponse(params.bocTradeNo) : ''
  // 根据交易类型切换transcode
  switch (transType) {
    // 支付
    case 'C':
      if (params.payChannel.indexOf('银行卡') > -1) {
        transcode = POS_ENV === 'dev' ? '消费' : '01'
      }
      if (params.payChannel.indexOf('聚合') > -1) {
        transcode = POS_ENV === 'dev' ? '聚合扫码支付' : '36'
      }
      break
    case 'R':
      if (record.payWayId === 'ALI_WX_PAY') {
        transcode = POS_ENV === 'dev' ? '聚合扫码退货' : '37'
      } else {
        transcode = POS_ENV === 'dev' ? '撤销' : '02'
        // transcode = POS_ENV === 'dev' ? '退货' : '03'
        // transcode = '撤销'
      }
  }

  return transcode
}

export default (transType, params, vue) => {
  console.log(params)

  const amount = (parseInt(params.price * 100) + '').padStart(12, '0')

  return new Promise((resolve, reject) => {
    // 模拟支付
    if (localStore.get('mock')) {
      setTimeout(() => {
        const response = { 'resCode': '00', 'resMsg': '消费成功', 'merchantName': '天津市海河资产经营管理有限公司', 'merchantID': '105000079911771', 'terminalID': '10028398', 'operID': '01', 'cardNo': '0000799117710001jie79', 'cardIputMethod': '99', 'transName': '微信支付', 'batchNo': '000004', 'traceNo': '000183', 'checkNo': '', 'refNo': '813266629789', 'transDate': '0718', 'transTime': '140712', 'amt': '000000000001', 'oldAmount': '000000000001', 'payChannel': 'CHANNEL_WEPAY', 'orgAmt': '000000000001', 'payWayId': 'ALI_WX_PAY', 'wxAliPayOrderNo': '0000799117710001jie79', 'wxAliPayUnionNo': '0000799117710001jie79', 'wxAliPayOldOrderNo': '0000799117710001jie79', 'accountNo': 'wx3b8b********bb07' }

        const posRecord = localStore.get('posRecord') || []

        posRecord.push(response)

        localStore.set('posRecord', posRecord)
        resolve(JSON.stringify(response))
      }, 5000)

      return
    }

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

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

    console.log(originalInfo)

    let inputData = {
      appName: '建行收单应用',
      transId: getTranscode(transType, params),
      amt: originalInfo ? originalInfo.amt : amount,
      inputRemarkInfo: '',
      qrCodeParam: params.qrCode || ''
    }

    if (originalInfo) {
      inputData = Object.assign(inputData, {
        orgTraceNo: originalInfo && originalInfo.traceNo,
        orgRefNo: originalInfo && originalInfo.refNo,
        transDate: originalInfo && originalInfo.transDate,
        qrCodeParam: originalInfo && originalInfo.wxAliPayUnionNo
      })
    }

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

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

    child.send(localStore.path + '=' + iconv.encode(JSON.stringify(inputData), 'gbk').toString('hex'))

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

      if (!msg.data) return

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

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

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

      if (response.resCode !== '00') {
        Message.error(response.resMsg || response.reason)
        resolve()
      } else {
        // const posRecord = localStore.get('posRecord') || {}

        // const posRecordList = posRecord?.tjzy || []

        // posRecordList.push(JSON.parse(result))

        // localStore.set('posRecord', posRecord)

        resolve(result)
      }
    })

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

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