import { Message } from 'element-ui'
import { localStore } from '@/utils/index'
import { idCardData, sbData, icData } from '../mockData'

export default {
  state () {
    return {
      socket: null,
      message: null,
      uid: null // 消息对应的组件id
    }
  },
  mutations: {
    SET_SOCKET (state, data) {
      var host = 'ws://127.0.0.1:33666'
      let socket
      if (state.socket == null) {
        socket = new WebSocket(host)
        state.socket = socket
      } else {
        resultMsg('已初始化.')
      }
    }
  },
  actions: {
    initDonsee100R ({ state, commit, dispatch }) {
      if (localStore.get('idDevice') !== 'donsee-100R') return
      commit('SET_SOCKET')

      state.socket.onopen = function () {
        resultInfoMsg('初始化成功')
        dispatch('getVersion') // 可以注释：控件版本号
        dispatch('readSAMID') // 可以注释：读卡器芯片号，全球唯一，通常可用来授权管理
        // autoReadIDCard(); //自动读卡可以放这里，自动读卡放身份证的间隔要>300ms，否则会不读卡
      }

      state.socket.onclose = function () {
        resultInfoMsg('读卡服务已经断开.')
      }

      state.socket.onerror = function () {
        resultMsg('请检查控件是否正常安装.')
      }

      state.socket.onmessage = function (msg) {
        const isDev = process.env.NODE_ENV === 'development'

        if (typeof msg.data === 'string') {
          var msgM = msg.data + ''
          var msgJson = JSON.parse(msgM)
          msgJson.id = new Date().getTime() // 触发数据更新
          console.log('%c [ msgJson ]-93', 'font-size:13px; background:pink; color:#bf2c9f;', msgJson)
          switch (msgJson.fun) {
            case 'EST_GetVersion#': // 获取版本号
              resultInfoMsg(`版本号：${msgJson.errMsg}`)
              break

            case 'EST_Reader_ReadIDCard#': // 单词 -> 读卡
              msgJson = isDev ? idCardData() : msgJson

              if (msgJson.rCode === '0') {
                state.message = msgJson
                console.log('%c [ state.message ]-64', 'font-size:13px; background:pink; color:#bf2c9f;', state.message)
                resultMsg(msgJson.errMsg)
              } else if (msgJson.rCode === '1') {
                resultInfoMsg('已停止自动读卡')
              } else if (msgJson.rCode === '-2') {
                resultInfoMsg('请放身份证')
              } else {
                resultMsg(msgJson.errMsg)
              }
              break

            case 'EST_ReadM1Card#': // IC卡卡号
              msgJson = isDev ? icData() : msgJson

              if (msgJson.rCode === '0') {
                state.message = msgJson
                dispatch('posBeep')
              } else {
                resultMsg(msgJson.errMsg)
              }
              break

            case 'EST_ReadSocialCard#': // 社保卡信息，个别地区社保卡不按国家规范来的，会读取信息不全
              msgJson = isDev ? sbData() : msgJson

              if (msgJson.rCode === '0') {
                state.message = msgJson
                !isDev && dispatch('posBeep')
              } else {
                resultMsg(msgJson.errMsg)
              }
              break

            case 'EST_ReaderGertSAMID#': // 获得读卡器芯片系列号，读卡器授权可以放这里来判断
              if (msgJson.rCode === '0') {
                resultMsg('系列号：' + msgJson.SAMID)
              } else {
                resultMsg(msgJson.errMsg)
              }
              break

            default:
              break
          }
        } else {
          alert('连接异常,请检查是否成功安装控件.')
        }
      }
    },
    getVersion ({ state }) {
      state.socket.send('EST_GetVersion#')
    },
    readSAMID ({ state }) {
      try {
        if (state.socket.readyState === 1) {
          state.socket.send('EST_ReaderGertSAMID#')
        } else {
          resultMsg('未找到控件，请检查控件是否安装.')
        }
      } catch (ex) {
        resultMsg('连接异常,请检查是否成功安装控件.')
      }
    },
    posBeep ({ state }) {
      if (state.socket.readyState === 1) {
        state.socket.send('EST_PosBeep#')
      } else {
        resultMsg('未找到控件，请检查控件是否安装.')
      }
    },
    // 单次读取身份证信息
    readIDCard ({ state }, uid) {
      console.log('%c [ uid ]-136', 'font-size:13px; background:pink; color:#bf2c9f;', uid)
      state.uid = uid
      try {
        if (state.socket.readyState === 1) {
          state.socket.send('EST_Reader_ReadIDCard#')
        } else {
          resultMsg('未找到控件，请检查控件是否安装.')
        }
      } catch (ex) {
        resultMsg('连接异常,请检查是否成功安装控件.')
      }
    },
    // 自动读取身份证信息
    autoReadIDCard ({ state }, uid) {
      state.uid = uid
      try {
        if (state.socket.readyState === 1) {
          state.socket.send('EST_Reader_ReadIDCard#|1')
          // resultMsg("自动读卡，请放身份证...");
        } else {
          resultMsg('未找到控件，请检查控件是否安装.')
        }
      } catch (ex) {
        resultMsg('连接异常,请检查是否成功安装控件.')
      }
    },
    // 停止连续读取身份证信息
    stopAutoReadIDCard ({ state }) {
      try {
        if (state.socket.readyState === 1) {
          state.socket.send('EST_StopReadIDCard#')
        } else {
          resultMsg('未找到控件，请检查控件是否安装.')
        }
      } catch (ex) {
        resultMsg('连接异常,请检查是否成功安装控件.')
      }
    },
    // 读取IC卡号，包括M1、CPU卡，8位16进制数据
    readM1Card ({ state }, uid) {
      state.uid = uid
      try {
        if (state.socket.readyState === 1) {
          state.socket.send('EST_ReadM1Card#')
        } else {
          resultMsg('未找到控件，请检查控件是否安装.')
        }
      } catch (ex) {
        resultMsg('连接异常,请检查是否成功安装控件.')
      }
    },
    // 读取银行卡号，支持QUICK PASS闪付银行卡，大部分卡支持，少部分地方性银行会读取失败
    readBankCard ({ state }) {
      try {
        if (state.socket.readyState === 1) {
          state.socket.send('EST_ReadBankCard#')
        } else {
          resultMsg('未找到控件，请检查控件是否安装.')
        }
      } catch (ex) {
        resultMsg('连接异常,请检查是否成功安装控件.')
      }
    },
    // 读社保卡，支持二代芯片社保卡，三代卡无秘钥不能读取
    readSocialCard ({ state }, uid) {
      state.uid = uid
      try {
        if (state.socket.readyState === 1) {
          state.socket.send('EST_ReadSocialCard#')
        } else {
          resultMsg('未找到控件，请检查控件是否安装.')
        }
      } catch (ex) {
        resultMsg('连接异常,请检查是否成功安装控件.')
      }
    }
  }
}

function resultMsg (msg) {
  if (msg !== '' && msg !== undefined) {
    console.log('%c [ msg ]-47', 'font-size:13px; background:pink; color:#bf2c9f;', msg)
    Message.error({
      message: msg,
      type: 'error'
    })
  }
}

function resultInfoMsg (msg) {
  if (msg !== '' && msg !== undefined) {
    console.log('%c [ msg ]-47', 'font-size:13px; background:pink; color:#bf2c9f;', msg)
  }
}
