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',
  '聚合扫码': '06', // 无硬件扫码
  // '预付卡': '03',
  '银行卡': '04'
}

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

  return transcode
}

export default (transType, params, vue) => {
  console.log('%c [ transType ]-40', 'font-size:13px; background:pink; color:#bf2c9f;', transType)
  return new Promise((resolve, reject) => {
    // 模拟支付
    if (localStore.get('mock')) {
      // 支付
      if (transType === 'C') {
        resolve('00WXZF                        17508100000001800010000成功响应码                         89831994733015C015C0001      050117164428030602316W          534000000018000000000000000000000000000000000000000     微信钱包支付180.0元                                                                                                                                                                                     微信钱包                                          20230501171642028030602316                        202305011716425560262031741417350                 1                                                                                                                                                                                                                                                                                       ')
      }

      if (transType === 'R') {
        // 退款
        resolve('00WXZF                        84778500000001800010000成功响应码                         89831994733015C015C0001      050117225928030602316W          651000000018000000000000000000000000000000000000000                                                                                                                                                                                                             微信钱包                                                                                                                                              1                                                                                                                                                                                                                                                                                       ')
      }

      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,
      tradeDate: '', // tradeDate ? moment().format('YYYY') + tradeDate :
      traceNo: '', // 参考号 originalInfo?.traceNo ||
      refNo: originalInfo?.refNo || '', // 凭证号
      LRC: '888',
      memo: params.qrCode || '',
      bankOderNo: originalInfo?.bankOderNo || '',
      ERP: '',
      qrcodeId: '',
      mchtBill: '',
      remarks: ''
    }

    let child = fork(path.join(__static, 'pos', 'dflzPos.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.errorInfo)
        resolve()
      } else {
        const posRecord = localStore.get('posRecord') || {}

        const posRecordList = posRecord?.dflz || []

        posRecordList.push(result)

        try {
          process.env.NODE_ENV === 'development' && localStore.set('posRecord', posRecord)
        } catch (e) {
          console.log(e)
        }

        resolve(result)
      }
    })

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

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