<template>
  <gui-page
    :custom-header="true"
    :is-header-sized="false"
    :header-class="['gui-theme-background-color', isLandscapeScreen?'width: 100vmax;':'']"
    :style="[isLandscapeScreen?'width: 100vmax':'']"
  >
    <template #gHeader>
      <view
        :style="[isLandscapeScreen?'height:44px;width: 100vmax':'height:44px;']"
        class="gui-flex gui-nowrap gui-rows gui-align-items-center"
      >
        <!-- 使用组件实现返回按钮及返回首页按钮 -->
        <text
          style="font-size:44rpx;"
          class="gui-header-leader-btns gui-color-white font-icons"
          @tap="goHome"
        >&#xe6c5;</text>
        <!-- 导航文本此处也可以是其他自定义内容 -->
        <text
          class="gui-h4 gui-blod gui-flex1 gui-text-center gui-color-white gui-ellipsis gui-primary-text"
        >蓝牙设置</text>
        <!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
        <!-- 实际宽度请根据自己情况设置 -->
        <view style="width:40px;">
          <text
            style="font-size:44rpx;"
            class="gui-color-white font-icons"
            @tap="saveBluetoothConfig"
          >&#xe6b4;</text>
        </view>
      </view>
    </template>
    <template #gBody>
      <!--
			1.手机蓝牙打开
			2.微信也许访问蓝牙和位置信息
			3.重启蓝牙设备
			4.不行的时候,删掉手机中蓝牙,重新链接
			-->
      <view class="content">

        <button size="mini" type="primary" @tap="startBluetoothDeviceDiscovery">搜索周边设备</button>
        <button size="mini" type="warn" @tap="stopBluetoothDevicesDiscovery">停止搜索</button>

        <scroll-view class="device_list" scroll-y="true" show-scrollbar="true">
          <radio-group>
            <!--  v-if="item.name.length>0" -->
            <view v-for="(item,index) in devicesList" :key="index" class="device_item">
              <view style="font-size: 32rpx; color: #333;">
                <radio :value="item.deviceId" @tap="select_deviceId(item)" />{{ item.name }}
              </view>
              <view style="font-size: 20rpx">信号强度: ({{ computedDBM(Math.max(100+item.RSSI,0)) }})
              </view>
              <view style="font-size: 20rpx">deviceId: {{ item.deviceId }}</view>
              <view style="font-size: 20rpx">Service数量: {{ item.advertisServiceUUIDs.length || 0 }}</view>

              <radio-group v-if="deviceId===item.deviceId">
                <view
                  v-for="(service,service_index) in serviceList"
                  :key="service_index"
                  style="font-size: 20rpx"
                >
                  <radio
                    style="transform:scale(0.7)"
                    :value="service.uuid"
                    @tap="select_service(service)"
                  />
                  {{ service.uuid }}
                </view>
              </radio-group>
            </view>
          </radio-group>
        </scroll-view>
        <canvas canvas-id="shareCanvas" style="width: 240px; height: 240px;" />
      </view>
    </template>
  </gui-page>
</template>

<script>
import Bluetooth from '@/unit/print/bluetooth.js'
import {
  setFileStorage
} from '@/unit/fileStorage.js'

const bluetooth = new Bluetooth()

export default {
  components: {},
  data() {
    return {
      isOpenBle: false, // 是否已经打开蓝牙，默认为false
      devicesList: [], // 设备列表
      serviceList: [], // 服务列表
      deviceId: '', // 选中的deviceId
      canvas_width: 240,
      canvas_height: 240
    }
  },
  // 页面卸载是关闭蓝牙链接
  onUnload() {
    // bluetooth.closeBLEConnection();
    // bluetooth.closeBluetoothAdapter();
  },
  // 页面打开,获取位置,打开蓝牙链接
  onLoad() {
    uni.getLocation({
      type: 'wgs84',
      success: function(res) {
        console.log('当前位置的经度：' + res.longitude)
        console.log('当前位置的纬度：' + res.latitude)
      }
    })

    bluetooth.serviceName = ''
    bluetooth.openBluetoothAdapter()
  },
  computed: {
    computedDBM: function() {
      return (num) => {
        if (num < 33.33) {
          return '弱'
        } else if (num > 33.33 && num < 66.66) {
          return '中'
        } else if (num > 66.66 && num < 100) {
          return '强'
        }
      }
    }
  },
  methods: {
    // 搜索周边设备
    startBluetoothDeviceDiscovery() {
      uni.showLoading({
        title: '蓝牙搜索中'
      })

      const self = this
      self.devicesList = []

      setTimeout(() => {
        plus.bluetooth.startBluetoothDevicesDiscovery({
          success: res => {
            plus.bluetooth.onBluetoothDeviceFound(devices => {
              // console.log("发现设备: " + JSON.stringify(devices));
              if (devices.devices[0]?.name !== '') {
                self.devicesList.push(devices.devices[0])
              }
              // 不重复,就添加到devicesList中,
              // if (!self.devicesList.some(item => {
              // 		return item.deviceId === devices.devices[0]
              // 			.deviceId
              // 	})) {
              // 	if (devices.devices[0]?.name !== "") {
              // 		self.devicesList.push(devices.devices[0])
              // 	}
              // }
            })
          },
          fail: res => {
            uni.hideLoading()
            // self.showToast(`搜索设备失败` + JSON.stringify(err))
          }
        })
      }, 200)
    },

    // 停止搜索蓝牙设备
    stopBluetoothDevicesDiscovery() {
      uni.hideLoading()
      bluetooth.stopBluetoothDevicesDiscovery()
    },

    // 选中设备
    async select_deviceId(item) {
      this.deviceId = item.deviceId
      bluetooth.serviceName = item.name
      bluetooth.deviceId = item.deviceId
      uni.setStorageSync('deviceId', bluetooth.deviceId)

      this.serviceList = []

      try {
        // 1.链接设备
        // const result = await bluetooth.createBLEConnection()
        await bluetooth.createBLEConnection()
        // 2.寻找服务
        const result2 = await bluetooth.getBLEDeviceServices()

        if (result2?.length === 0) {
          uni.showToast({
            title: '此设备无服务',
            duration: 2000,
            icon: 'none'
          })
        }

        // console.log("获取服务: " + JSON.stringify(result2));

        this.serviceList = result2
      } catch (e) {
        // TODO handle the exception
        // console.log("e: " + JSON.stringify(e));
        if (e.message === 'already connect') {
          // 2.寻找服务
          const result2 = await bluetooth.getBLEDeviceServices()
          this.serviceList = result2
        }
      }
    },

    // 选中服务
    async select_service(res) {
      bluetooth.serviceId = res.uuid
      uni.setStorageSync('serviceId', res.uuid)
      // console.log(JSON.parse(JSON.stringify(this.serviceList)));

      try {
        // const result = await bluetooth.getBLEDeviceCharacteristics()
        await bluetooth.getBLEDeviceCharacteristics()
      } catch (e) {
        // TODO handle the exception
        console.log('e: ' + JSON.stringify(e))
      }
    },
    goHome() {
      uni.setStorageSync('bluetoothConfig', JSON.stringify(bluetooth))
      uni.$goHome()
    },
    // 保存设置
    saveBluetoothConfig() {
      // #ifdef APP-PLUS
      setFileStorage('bluetoothConfig.txt', 0, bluetooth)
      // #endif
    }

  }
}
</script>

<style>
	.content {
		height: calc(100vh - 85px);
		margin-top: 85px;
	}

	page {
		color: #333;
	}

	button {
		margin: 10upx;
	}

	.gui-header-leader-btns {
		color: black;
		font-size: 24px !important;
		margin-left: 24rpx;
	}

	.devices_summary {
		margin-top: 5rpx;
		padding: 20rpx;
		font-size: 30rpx;
	}

	.device_list {
		margin: 5rpx 20rpx 5rpx 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		background-color: #FdFdFd;
		min-height: 0rpx;
		max-height: calc(100vh - 300px);
		width: 700rpx;

	}

	.device_item {
		border-bottom: 1rpx solid #ddd;
		padding: 20rpx;
		color: #666;

	}

	.device_item_hover {
		background-color: rgba(0, 0, 0, .1);
	}

	.connected_info {
		position: fixed;
		bottom: 0;
		width: 100%;
		background-color: #F0F0F0;
		padding: 10px;
		padding-bottom: 20px;
		margin-bottom: env(safe-area-inset-bottom);
		font-size: 14px;
		min-height: 100px;
		box-shadow: 0px 0px 3px 0px;
	}

	.connected_info .operation {
		position: absolute;
		display: inline-block;
		right: 30px;
	}
</style>
