<template>
  <view class="nfc-con">
    <view class="nfc-bg">
        <view class="nfc-title">
            <uni-icons type="closeempty" size="20" class="nfc-close"  @click="handleClose"></uni-icons>NFC识别
        </view>
        <block v-if="formData.deviceId==''">
            <view class="nfc-pic">
                <img  class="nfc-pic-animal" :src="'static/images/polling/nfc-logo.png'" />
            </view>
            <view class="nfc-desc">请将设备靠近NFC识别</view>
        </block>

        <!-- 识别成功 -->
        <view class="result-section" v-else>
            <block v-if="readStatus">
                <view class="result-header">
                    <img class="result-img" :src="'static/images/polling/icon-success.png'" />
                    <view class="result-label">识别成功</view>
                </view>
                <view class="result-value">
                    <view>识别时间</view>
                    <view>{{parseTime(new Date().getTime(),'{y}年{m}月{d}日 星期{a} {h}:{i}')}}</view>
                </view>
                <view class="btn-blue" @click="handleClose">确定</view>
            </block>
            <block v-else>
                <view class="result-header">
                    <img class="result-img" :src="'static/images/polling/icon-Alert.png'" />
                    <view class="result-label result-err">识别失败</view>
                </view>
                <view class="result-value">
                    可能的失败原因：手机距离NFC设备较远、手机未联网、NFC设备故障……
                </view>
                <view class="btn-blue" @click="open">重新识别</view>
            </block>
        </view>
    </view>
</view>
</template>
 
<script setup>
import { ref, onBeforeUnmount,onMounted } from "vue";
import { parseTime } from '@/utils/datetime.js';

// 定义组件 emits
const emit = defineEmits(['close',"changeNfc"]);

// 状态管理
const formData = ref({
  deviceId: "", //录入的id
});
const readStatus=ref(false);//读取状态 true 成功

// 变量初始化
let NfcAdapter = null;
let MifareClassic = null;
let isListening = false;

// 检查NFC状态
function open() {
  try {
    const main = plus.android.runtimeMainActivity();
    NfcAdapter = plus.android.importClass("android.nfc.NfcAdapter");
    const nfcAdapter = NfcAdapter.getDefaultAdapter(main);

    if (!nfcAdapter) {
      uni.showToast({
        icon: "error",
        title: "该设备不支持NFC",
        duration: 5000,
      });
      return;
    }

    if (!nfcAdapter.isEnabled()) {
      uni.showToast({
        icon: "error",
        title: "NFC功能未打开",
        duration: 5000,
      });
      return;
    }

    initNFC();
  } catch (e) {
    console.error("打开NFC失败:", e);
    uni.showToast({
      icon: "error",
      title: "初始化NFC失败",
    });
  }
}

// 初始化NFC监听
function initNFC() {
  try {
    const main = plus.android.runtimeMainActivity();
    const Intent = plus.android.importClass("android.content.Intent");
    const Activity = plus.android.importClass("android.app.Activity");
    const PendingIntent = plus.android.importClass("android.app.PendingIntent");
    const IntentFilter = plus.android.importClass(
      "android.content.IntentFilter"
    );

    // 导入需要的NFC类
    plus.android.importClass("android.nfc.NdefRecord");
    plus.android.importClass("android.nfc.NdefMessage");
    MifareClassic = plus.android.importClass("android.nfc.tech.MifareClassic");
    NfcAdapter = plus.android.importClass("android.nfc.NfcAdapter");

    const nfcAdapter = NfcAdapter.getDefaultAdapter(main);
    if (!nfcAdapter || !nfcAdapter.isEnabled()) return;

    // 创建Intent过滤器
    const ndef = new IntentFilter("android.nfc.action.NDEF_DISCOVERED");
    const tag = new IntentFilter("android.nfc.action.TAG_DISCOVERED");
    const tech = new IntentFilter("android.nfc.action.TECH_DISCOVERED");

    const intentFiltersArray = [ndef, tag, tech];

    // 技术列表
    const techListsArray = [
      ["android.nfc.tech.Ndef"],
      ["android.nfc.tech.IsoDep"],
      ["android.nfc.tech.NfcA"],
      ["android.nfc.tech.NfcB"],
      ["android.nfc.tech.NfcF"],
      ["android.nfc.tech.Nfcf"],
      ["android.nfc.tech.Nfef"],
      ["android.nfc.tech.Ndef"],
      ["android.nfc.tech.NfcV"],
      ["android.nfc.tech.NdefFormatable"],
      ["android.nfc.tech.MifareClassi"],
      ["android.nfc.tech.MifareUltralight"],
    ];

    // 创建PendingIntent
    const _intent = new Intent(main, main.getClass());
    _intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    const pendingIntent = PendingIntent.getActivity(main, 0, _intent, 0);
    // 监听NFC事件
    startNFCListener();

    // 启用前台调度
    nfcAdapter.enableForegroundDispatch(
      main,
      pendingIntent,
      intentFiltersArray,
      techListsArray
    );
  } catch (e) {
    console.error("初始化NFC失败:", e);
  }
}

// 开始NFC监听
function startNFCListener() {
  if (isListening) return;

  plus.globalEvent.addEventListener("newintent", handleNewIntent);
  isListening = true;
}

// 停止NFC监听
function stopNFCListener() {
  if (isListening) {
    plus.globalEvent.removeEventListener("newintent", handleNewIntent);
    isListening = false;
  }
}

// 处理新的NFC意图
function handleNewIntent() {
  readNFCData();
  stopNFCListener();
}

// 读取NFC数据
function readNFCData() {
  try {
    const main = plus.android.runtimeMainActivity();
    const _intent = main.getIntent();
    // 只处理 NDEF 数据
    let rawMsgs = _intent.getParcelableArrayExtra(
      "android.nfc.extra.NDEF_MESSAGES"
    );
    if (rawMsgs && rawMsgs.length > 0) {
      try {
        const records = rawMsgs[0].getRecords();
        const result = records[0].getPayload();
        // 取 deviceId
        function bytesToString(result) {
          return String.fromCharCode(...result);
        }
        formData.value.deviceId = bytesToString(result).substring(3);
        emit("changeNfc", formData.value.deviceId);
        readStatus.value=true;
      } catch (e) {
        console.log("读取NDEF数据错误:", e);
        uni.showToast({ title: "读取数据失败,请重新读取", icon: "none" });
      }
    } else {
      uni.showToast({ title: "未识别到NFC标签", icon: "none" });
    }
  } catch (e) {
    console.error("读取NFC数据失败:", e);
    uni.showToast({ title: "读取数据失败,请重新读取", icon: "none" });
  }
}

const handleClose = ()=>{
	emit('close');
}

onMounted(() => {
  open();
});

// 组件卸载前清理
onBeforeUnmount(() => {
  stopNFCListener();
});


defineExpose({
  open
});
</script>

<style lang="scss" scoped>
.nfc-con {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	background: rgba(0, 0, 0, 0.4);
	z-index: 9999;
}
.nfc-con .nfc-bg{
    position:absolute;
    bottom:0;
    left:0;
    background-color:#fff;
    border-radius:18rpx 18rpx  0 0;
    text-align:center;
    width:650rpx;
    padding:30rpx 50rpx 130rpx;
}
.nfc-bg .nfc-title{
    text-align:center;
    color:#333333;
    font-size:32rpx;
    font-weight:bold;
    position:relative;
}
.nfc-bg .nfc-title .nfc-close{
    position:absolute;
    top:0rpx;
    left:-20rpx
}
.nfc-con .nfc-bg .nfc-pic{
    padding:126rpx 0 86rpx;
}
.nfc-con .nfc-bg .nfc-pic img{
    width:260rpx;
    height:208rpx;
    
}
.nfc-con .nfc-bg .nfc-desc{
    text-align:center;
    color:#0395E0;
    font-size:36rpx;
    font-weight:bold;
}

.nfc-pic-animal{
    animation: elasticLoop 3s ease-in-out infinite;
}
@keyframes elasticLoop {
    0%, 100% { transform: scale(1); }
    25% { transform: scale(1.2); }
    50% { transform: scale(0.95); }
    75% { transform: scale(1.1); }
}


.result-section{
    .result-header{
        padding:70rpx 0 0; 
        .result-img{
            width:120rpx;
            height:120rpx;
        }
        .result-label,.result-err{
            text-align:center;
            color:#00BF5A;
            font-size:36rpx;
            font-weight:bold;
            padding:20rpx 0;
        }
        .result-err{
            color:#FF9638;
        }
    }
    .result-value{
        color:#333;
        text-align:center;
        font-size:30rpx;
        margin-top:20rpx;
    }
    .btn-blue{
        background-color:#05A3F4;
        border-radius:40rpx;
        width:380rpx;
        height:80rpx;
        line-height:80rpx;
        text-align:center;
        color:#fff;
        font-size:36rpx;
        margin:50rpx auto 0;
    }
}
</style>