import {
  mapState
} from 'vuex'
import store from "@/store"
import io from '@hyoga/uni-socket.io';
var tsc = require('../components/gprint/tsc')
import bluetoothTool from '../components/gprint/BluetoothTool.js'
import { base64ToPath } from '../components/gprint/image-tools.js';

// 尝试将用户在根目录中的store/index.js的vuex的state变量，全部加载到全局变量中
let $uStoreKey = [];
try {
  $uStoreKey = store.state ? Object.keys(store.state) : [];
} catch (e) {

}

module.exports = {
  beforeCreate() {
    // 将vuex方法挂在到$u中
    // 使用方法为：如果要修改vuex的state中的user.name变量为"史诗" => this.$u.vuex('user.name', '史诗')
    // 如果要修改vuex的state的version变量为1.0.1 => this.$u.vuex('version', '1.0.1')
    this.$u.vuex = (name, value) => {
      this.$store.commit('$uStore', {
        name,
        value
      })
    }
  },
  data() {
    return {
      devices: [],
      cuDevice: null,
      first:true,
      currentRow: null,
      canvasWidth: 800,
      canvasHeight: 600
    }
  },
  computed: {
    // 将vuex的state中的所有变量，解构到全局混入的mixin中
    ...mapState($uStoreKey),
    currentBleName() {
      if(this.currentRow && this.currentRow.printerName){
        return this.currentRow.printerName
      } else {
        return this.vuex_printerInfo.printerName
      }
    }
  },
  methods: {
    initBle(){
        //#ifdef APP-PLUS
        // 蓝牙
        try {
          this.$u.vuex('vuex_printConnect', false);
          bluetoothTool.init({
              listenBTStatusCallback: (state)=> {
                console.log('listenBTStatusCallback', state);
                if (state === 'STATE_OFF') {
                  this.$u.vuex('vuex_printConnect', false);
                }
                if (state === 'STATE_OFF_First') {
                  this.$u.vuex('vuex_printConnect', false);
                  uni.$emit('BLEstatus', false)
                }
              },
              discoveryDeviceCallback: this.onDevice,
              discoveryFinishedCallback: (status) => {
                  console.log('搜索完成', this.devices, status)
                  if(!this.cuDevice) {
                    this.$u.vuex('vuex_printConnect', false);
                    uni.$emit('BLEstatus', false)
                  }
                  if (typeof status === 'boolean') {
                    this.$u.vuex('vuex_printConnect', status);
                    uni.$emit('BLEstatus', status)
                  }
              },
              readDataCallback: (dataByteArr) => {
                  this.$u.vuex('vuex_printConnect', false);
              },
              connExceptionCallback: (e) => {
                  console.log('connExceptionCallback', e);
                  this.$u.vuex('vuex_printConnect', false);
              }
          });
          this.first = true
          this.cuDevice = null
          this.searchBle()
        } catch (error) {
          console.log('error', error)
        }
        
        
        //#endif
    },
    searchBle() {
        var that = this
        console.log("initBule")
        // 使用openBluetoothAdapter 接口，免去主动申请权限的麻烦
        uni.openBluetoothAdapter({
            success(res) {
                this.devices = []
                uni.getBluetoothAdapterState({
                  success: function(res) {
                    console.log(res)
                    if (res.available) {
                      const list = bluetoothTool.getPairedDevices()
                      const item = list.find(v=>v.name === that.currentBleName)
                      if(item && item.device) {
                        that.cuDevice = item
                        bluetoothTool.connPairDevice(item.device,(result)=>{
                          if(result) {
                            that.$u.vuex('vuex_printConnect', true);
                            uni.$emit('BLEstatus', true)
                          } else {
                            uni.$emit('BLEstatus', false)
                          }
                          console.log('连接结果：',result)
                        });
                      }
                      //搜索蓝牙
                      //开始搜寻附近的蓝牙外围设备
                      uni.startBluetoothDevicesDiscovery({
                        success(res) {
                          if (!that.vuex_printConnect) {
                            bluetoothTool.discoveryNewDevice();
                          }
                        }
                      })
                    } else {
                      console.log('本机蓝牙不可用')
                    }
                  },
                  fali: () => {
                    console.log('本机蓝牙不可用')
                  }
                })
            },
            fail: function(msg) {
              console.log(msg)
            }
        })
    },
    onDevice(newDevice){
        console.log("监听寻找到新设备的事件---------------")
        console.log(newDevice)
        if(newDevice.name && newDevice.name != 'null') {
            this.devices.push({
                name: newDevice.name,
                address: newDevice.address
            })
            if (newDevice.name === this.currentBleName && (newDevice.type === 1 || newDevice.type === 3) && this.first) {
                this.cuDevice = newDevice
                this.onConn(newDevice)
                this.first = false
            }
        }
    },
    onConn(item) {
        console.log("连接蓝牙---------------" + item.address)
        /* uni.showLoading({
            title: '连接中',
            mask: false
        }); */
        
        bluetoothTool.connDevice(item.address,(result)=>{
            if(result) {
              this.$u.vuex('vuex_printConnect', true);
              uni.$emit('BLEstatus', true)
            } else {
              uni.$emit('BLEstatus', false)
            }
            console.log('连接结果：',result)
        });
    },
    blePrint (filePath) {
        if(!filePath) {
          console.log('没有图片路径')
          return
        }
        const firstCanvas = uni.createCanvasContext('firstCanvas');
        console.log('rescanvas前')
        const that = this
        uni.getImageInfo({
            src: filePath,
            success(img) {
              that.canvasWidth = 800
              that.canvasHeight = 640
              firstCanvas.drawImage(img.path, 0, 0, that.canvasWidth, that.canvasHeight);
              firstCanvas.draw(true, ()=>{
                uni.canvasGetImageData({
                  canvasId: 'firstCanvas',
                  x: 0,
                  y: 0,
                  width: that.canvasWidth,
                  height: that.canvasHeight,
                  success: (res)=> {
                    var command = tsc.jpPrinter.createNew()
                    command.init()
                    command.setSize(100, 80)
                    command.setGap(2)
                    command.setCls()
                    command.setBitmap2(0, 0, 0, res)
                    command.setPagePrint()
                    console.log('数据发送： \n',command.getRawData())
                    let data = command.getData()
                    bluetoothTool.sendByteData(data)
                    console.log('发送完毕')
                  },
                  fail: function(res) {
                      console.log(res)
                  }
              })
              });
            }
        })
    },
    createSocket() {
      if (getApp().globalData.printSocket && Object.keys(getApp().globalData.printSocket).length > 0) {
        getApp().globalData.printSocket.close && getApp().globalData.printSocket.close()
      }
      this.$u.vuex('vuex_printConnect', false)
      let socket = io(this.vuex_printerInfo.hostUrl, {
        transports: ['websocket'],
        auth: {
          token: 'Bearer ' + this.vuex_token, // 在此处填入你 client 设置的 token，缺省可留空
        },
      });

      socket.on('connect', () => {
        console.log('连接成功444');
        // TODO: Do something for your project
        this.$u.vuex('vuex_printConnect', true);
        // console.log(this.vuex_printConnect, 'vuex_printConnect');
      });
      socket.on('clients', (clients) => {
        console.log(clients, 'clients');
      });
      socket.on('printerList', (printerList) => {
        // globalThis.printerList = printerList;
        // console.log(printerList, 'printerList');
      });
      socket.on('success', (res) => {
        console.log(res, '打印成功');
      });

      socket.on('error', (res) => {
        console.log(res, '打印失败');
      });
      socket.on('disconnect', () => {
        console.log('打印机断开');
        this.$u.vuex('vuex_printConnect', false);
        this.createSocket()
      });
      getApp().globalData.printSocket = socket
    },
    async printPdfSocket(params) {
      
      if (!this.vuex_printerInfo.hostUrl) {
        this.$u.toast('请绑定打印机');
        return;
      }
      if (this.vuex_printConnect) {
        if (this.vuex_printerInfo.connectionType === 'bluetooth') {
          console.log('蓝牙开始打印')
          await this.$u.api.getPrintPNG(params).then(async (res) => {
            console.log('请求接口', res)
            const codeUrl =  'data:image/png;base64,'+uni.arrayBufferToBase64(res)
            base64ToPath(codeUrl, '.png').then(imgPath=>{
              console.log('imgPath', imgPath)
              this.blePrint(imgPath)
            }).catch(e=> {
              console.log('转图片错误')
            })
          }).catch(e => {
            console.log('err', e)
          })
        } else {
          this.$u.api.getPrintDown(params).then((res) => {
            if (res.code === 200) {
              getApp().globalData.printSocket.emit('news', {
                client: null,
                printer: this.vuex_printerInfo.printerName,
                type: 'url_pdf',
                orientation: 'portrait',
                // pdf_path: 'http://192.168.3.91:8082/static/123.pdf',
                pdf_path: res.fileUrl,
              });
            }
          });
        }
        
      } else {
        this.$u.toast('打印机连接失败');
      }
    }
  }
}