<script setup>
import { onLaunch, onShow } from '@dcloudio/uni-app'
import { getCurrentInstance, onMounted, ref ,onUnmounted} from 'vue'  // 从vue导入
import Util from './utils/util.js'

// 全局数据管理
const globalData = ref({
  share: false,
  height: 0,
  statusBarHeight: uni.getSystemInfoSync()['statusBarHeight'],
  overlayVisible: false,
  quickMenu: {
    x: 0,
    y: 0
  },
  currentRoute: ''	// 存储当前页面路由
})

// 获取全局实例
const app = getCurrentInstance()
app.appContext.config.globalProperties.$globalData = globalData

// 变量声明
let main, receiver, filter

// 生命周期：应用启动
onLaunch(() => {
  uni.getSystemInfo({
    success: (res) => {
      globalData.height = res.statusBarHeight
    }
  })
  setBROADCAST()
})

// 生命周期：页面显示
onShow(() => {})

// 生命周期：创建
onMounted(() => {
  initScan()
  startScan()
})

// 生命周期：卸载
onUnmounted(() => {
  // 页面退出时卸载监听，防止重复扫码
  stopScan()
})

// 初始化扫描
function initScan() {
  main = plus.android.runtimeMainActivity() // 获取activity
  const IntentFilter = plus.android.importClass('android.content.IntentFilter')
  filter = new IntentFilter()
  filter.addAction('com.seuic.scan') // 广播动作

  receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
    onReceive: function(context, intent) {
       try {
            plus.android.importClass(intent)
            let code = intent.getStringExtra('scannerdata')
            // 清除空白字符（确保code格式正确）
            if (typeof code === 'string') {
              code = code.replace(/\s+/g, '')
            }
            console.log('接收的条码数据：', code)
      
             // 从全局变量中获取当前路由（避开uni API）
			  const currentRoute = uni.$appGlobal?.globalData?.value?.currentRoute || ''
		
			  // 目标页面路由
			  const targetPagePath = 'pages/nurseRecordPage/nurseRecordPage'
			  
			 if (currentRoute === targetPagePath) {
				 // 调用目标页面方法（需确保页面已加载）
				 // 延迟确保页面已完全加载
				 setTimeout(() => {
				   const pages = getCurrentPages()
				   if (!pages || pages.length === 0) {
					 console.error('页面栈为空，无法获取页面实例')
					 return
				   }
				   const currentPage = pages[pages.length - 1]
				   // 严格检查页面实例和函数是否存在
				   if (!currentPage) {
					 console.error('当前页面实例不存在')
					 return
				   }
				   if (!currentPage.$vm) {
					 console.error('当前页面的Vue实例不存在')
					 return
				   }
				   if (typeof currentPage.$vm.getPDAScanInfo !== 'function') {
					 console.error('目标页面未定义getPDAScanInfo函数，请检查页面代码')
					 return
				   }
				   // 所有检查通过后调用
				   currentPage.$vm.getPDAScanInfo(code)
				 }, 100) // 适当延长延迟时间，确保页面初始化完成
			   } else {
				 if (code.length === 10) {
				   Util.getPatInfoNew(code, (patInfo) => {
				     uni.navigateTo({
				       url: '../patMainPage/patMainPage'
				     })
				   })
				 }
			   }
          } catch (err) {
            console.error('条码接收回调异常：', err.message, err.stack)
          }
    }
  })
}

// 设置广播模式
function setBROADCAST() {
  const main2 = plus.android.runtimeMainActivity() // 获取activity
  const Intent = plus.android.importClass('android.content.Intent')
  const intent2 = new Intent('com.android.scanner.service_settings')
  intent2.putExtra('barcode_send_mode', 'BROADCAST')
  main2.sendBroadcast(intent2)
  setBROADCASTACTION()
}

// 设置广播动作
function setBROADCASTACTION() {
  const main2 = plus.android.runtimeMainActivity() // 获取activity
  const Intent = plus.android.importClass('android.content.Intent')
  const intent2 = new Intent('com.android.scanner.service_settings')
  intent2.putExtra('action_barcode_broadcast', 'com.seuic.scan')
  main2.sendBroadcast(intent2)
}

// 开始扫描
function startScan() {
  main.registerReceiver(receiver, filter)
}

// 停止扫描
function stopScan() {
  main.unregisterReceiver(receiver)
}

// 挂载到全局，方便其他地方访问
uni.$appGlobal = {
  globalData: globalData
}
</script>

<style>
/**app.wxss**/
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  background: #fff;
  font-family: Arial, Helvetica, sans-serif;
}

page {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  background: #fff;
  color: #333;
  font-size: 28rpx;
  overflow: hidden;
}

.multiBtn-content {
  height: 90rpx;
  font-size: 30rpx;
  color: #fff;
  padding: none;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
}

.multiBtn-left {
  flex: 1;
  align-items: center;
  justify-content: center;
  display: flex;
  border-radius: 0 !important;
}

.multiBtn-right {
  flex: 1;
  align-items: center;
  justify-content: center;
  display: flex;
  background-color: #1890ff;
  color: #ffffff;
  border-radius: 0 !important;
  font-size: 34rpx;
}

/* 首页组件样式 */
.patlist .van-icon__image,
.patlist .van-icon--image {
  margin-top: 10rpx;
  width: 78rpx;
  height: 78rpx;
}
.searchcontent .van-search{
  background: none !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
}

/* 表单详情页组件样式 */
.comboboxclass .van-checkbox {
  margin-top: 12rpx !important;
}
.radioboxclass .van-radio{
  margin-top: 12rpx !important;
}
.inputclass .van-cell {
  padding: 0 !important;
}
.inputclass .uni-input-input{
  font-size: 28rpx;
}
.inputclass .uni-input-placeholder{
  font-size: 28rpx;
}
.inputclass .van-field__input{
  height: 60rpx;
}
.selectclass .van-cell {
  min-height: 60rpx !important;
  line-height: 60rpx !important;
  padding: 0rpx !important;
}
.selectclass .van-cell__value {
  text-align: left;
  line-height: normal;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-top: 10rpx;
}
</style>