import {
  mapState
} from 'vuex'
import store from "@/store"
import io from '@hyoga/uni-socket.io';
import CTPL from "../uni_ctpl_sdk/ctpl.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 {
      pageObj: {
        width: 100,
        height: 80
      },
      device: null,
      imagePath: '/static/1.png'
    }
  },
  computed: {
    // 将vuex的state中的所有变量，解构到全局混入的mixin中
    ...mapState($uStoreKey)
  },
  async mounted(){
    
  },
  methods: {
    // 获取图片信息
    getImageData() {
      const $this = this
      uni.getImageInfo({
          src: this.imagePath,
          success: (res) => {
              // const scale = ($this.pageObj.width * 8) / res.width
              const newWidth = $this.pageObj.width * 8
              const newHeight = $this.pageObj.height * 8
              const ctx = uni.createCanvasContext("canvas", $this)
              ctx.drawImage(this.imagePath, 0, 0, newWidth, newHeight)
              ctx.draw(false, () => {
                  uni.canvasGetImageData(
                      {
                          canvasId: "canvas",
                          x: 0,
                          y: 0,
                          width: newWidth,
                          height: newHeight,
                          success: function (response) {
                            console.log('转换成canvas的时间',response)
                            const imageRes = response
                            CTPL.drawBitMap(
                                0,
                                0,
                                imageRes.width,
                                imageRes.height,
                                0,
                                response.data
                            )
                            CTPL.setPrintCopies(1, 1)
                            CTPL.execute((res) => {
                              console.log('打印完成', res)
                              CTPL.disconnect()
                            })
                          },
                          fail: function (res) {
                            console.log('sda',res)
                            CTPL.disconnect()
                          },
                      },
                      $this
                  )
              })
          },
      })
    },
    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;
      }
      await CTPL.init();
      await CTPL.discovery( (res) => {
        if (res.name === 'CT-428D') {
          
          this.device = res
          console.log(this.device)
        }
      });
      const $this = this
      setTimeout(()=>{
        CTPL.connect(
          $this.device,
          function success(res1) {
            console.log('扫描到的打印机',res1)
            CTPL.setSize($this.pageObj.width, $this.pageObj.height)
            CTPL.clearCache()
            $this.getImageData((response)=>{
              console.log('response', response)
              const imageRes = response
              // CTPL.drawBitMap(
              //     0,
              //     0,
              //     imageRes.width,
              //     imageRes.height,
              //     0,
              //     response.data
              // )
              // CTPL.setPrintCopies(1, 1)
              // CTPL.execute((res) => {
              //   console.log('res', res)
              // })
            })
          },
          function fail(e) {
            console.log('报错',e)
          }
        )
        uni.onBLEConnectionStateChange(function (res) {
          console.log('sadsada', res)
        })
        
      }, 6000)
      return
    }
  }
}