<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import Container from "@/components/Container.vue";
import ModalDialog from "@/components/ModalDialog.vue";
import SButton from "@/components/SButton.vue";
import { unbindDeviceByQrcodeIdAPI } from "@/apis";

const deviceQrcodeId = ref("");
const showConfirmDialog = ref(false);
const isSubmitting = ref(false);
const isTestEnvironment = ref(false);

// 提交前移除用户输入中的所有空白字符，兼容复制粘贴的设备编号。
const normalizeDeviceQrcodeId = () =>
  String(deviceQrcodeId.value ?? "").replace(/\s+/g, "");

const getEnvVersion = () => {
  try {
    return uni.getAccountInfoSync?.().miniProgram?.envVersion || "develop";
  } catch (error) {
    console.error("获取小程序环境失败", error);
    return "develop";
  }
};

const validateDeviceQrcodeId = () => {
  const normalizedId = normalizeDeviceQrcodeId();
  deviceQrcodeId.value = normalizedId;
  const numericId = Number(normalizedId);

  if (!/^\d+$/.test(normalizedId) || !Number.isSafeInteger(numericId) || numericId <= 0) {
    uni.showToast({
      title: "请输入正确的设备编号",
      icon: "none",
    });
    return null;
  }

  return numericId;
};

const openConfirmDialog = () => {
  if (!isTestEnvironment.value || validateDeviceQrcodeId() === null) return;
  showConfirmDialog.value = true;
};

const closeConfirmDialog = () => {
  if (isSubmitting.value) return;
  showConfirmDialog.value = false;
};

const confirmUnbind = async () => {
  if (isSubmitting.value) return;
  const id = validateDeviceQrcodeId();
  if (id === null) {
    showConfirmDialog.value = false;
    return;
  }

  isSubmitting.value = true;
  try {
    await unbindDeviceByQrcodeIdAPI(id);
    showConfirmDialog.value = false;
    deviceQrcodeId.value = "";
    uni.showToast({
      title: "解绑成功",
      icon: "success",
    });
  } catch (error) {
    console.error("测试解绑设备失败", error);
  } finally {
    isSubmitting.value = false;
  }
};

onLoad(() => {
  if (getEnvVersion() !== "release") {
    isTestEnvironment.value = true;
    return;
  }

  uni.showToast({
    title: "该功能仅用于测试环境",
    icon: "none",
  });
  setTimeout(() => {
    uni.navigateBack();
  }, 1200);
});
</script>

<template>
  <Container title="解绑设备" :scroll="false">
    <view v-if="isTestEnvironment" class="unbind-page">
      <view class="unbind-form">
        <input
          v-model="deviceQrcodeId"
          class="device-input"
          type="number"
          placeholder="请输入设备编号"
          placeholder-class="device-input-placeholder"
        />
        <SButton
          width="100%"
          :rounded="40"
          :onClick="openConfirmDialog"
        >解绑</SButton>
      </view>
    </view>
  </Container>

  <ModalDialog
    :show="showConfirmDialog"
    content="是否解绑该设备（仅用于测试环境）"
    cancelText="取消"
    confirmText="解绑"
    :onCancel="closeConfirmDialog"
    :onConfirm="confirmUnbind"
  />
</template>

<style scoped lang="scss">
.unbind-page {
  display: flex;
  width: 100%;
  height: 100%;
  padding: 0 72rpx;
  box-sizing: border-box;
  align-items: center;
  justify-content: center;
}

.unbind-form {
  display: flex;
  width: 100%;
  flex-direction: column;
  gap: 36rpx;
}

.device-input {
  width: 100%;
  height: 88rpx;
  padding: 0 32rpx;
  box-sizing: border-box;
  color: #ffffff;
  font-size: 28rpx;
  background: rgba(255, 255, 255, 0.12);
  border: 2rpx solid rgba(255, 255, 255, 0.28);
  border-radius: 44rpx;
}

:deep(.device-input-placeholder) {
  color: rgba(255, 255, 255, 0.55);
}
</style>
