import {
  mapState
} from 'vuex'
import store from "@/store"
import io from '@hyoga/uni-socket.io';

// 尝试将用户在根目录中的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 {}
  },
  computed: {
    // 将vuex的state中的所有变量，解构到全局混入的mixin中
    ...mapState($uStoreKey)
  },
  methods: {
    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) {
        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',
              // pdf_path: 'http://192.168.3.91:8082/static/123.pdf',
              pdf_path: res.fileUrl,
            });
          }
        });
      } else {
        this.$u.toast('打印机连接失败');
      }
    }
  }
}