<template>
  <view class="scan-page">
    <!-- 顶部品牌 -->
    <view class="brand-area">
      <text class="brand-name">智联方舟</text>
    </view>

    <!-- 中间扫一扫按钮 -->
    <view class="scan-area">
      <view class="scan-btn" @click="handleScan">
        <!-- 二维码图标 -->
        <view class="qr-icon">
          <view class="qr-row">
            <view class="qr-block"></view>
            <view class="qr-block"></view>
            <view class="qr-space"></view>
            <view class="qr-block"></view>
          </view>
          <view class="qr-row">
            <view class="qr-block"></view>
            <view class="qr-space"></view>
            <view class="qr-block"></view>
            <view class="qr-space"></view>
          </view>
          <view class="qr-row">
            <view class="qr-space"></view>
            <view class="qr-block"></view>
            <view class="qr-space"></view>
            <view class="qr-block"></view>
          </view>
          <view class="qr-row">
            <view class="qr-block"></view>
            <view class="qr-block"></view>
            <view class="qr-block"></view>
            <view class="qr-space"></view>
          </view>
        </view>
        <text class="scan-text">扫一扫</text>
      </view>
      <text class="scan-tip">扫描货柜上的二维码开始购物</text>
    </view>

    <!-- 我的入口 -->
    <view class="mine-entry" @click="goMine">
      <view class="mine-icon">
        <view class="mine-head"></view>
        <view class="mine-body"></view>
      </view>
      <text class="mine-text">我的</text>
    </view>

    <!-- 底部客服电话 -->
    <view class="footer">
      <text class="footer-text">客服电话：</text>
      <text class="footer-phone" @click="callService">{{ servicePhone }}</text>
    </view>
  </view>
</template>

<script>
import config from '@/config/env.js';

export default {
  data() {
    return {
      servicePhone: config.servicePhone,
    };
  },
  onLoad(options) {
    // 退出登录后跳转过来，清除标记，停留在扫码页
    if (uni.getStorageSync('__logout_flag')) {
      uni.removeStorageSync('__logout_flag');
      return;
    }

    // 1. 检查 JWT（App.vue 已处理首次跳转，这里兜底）
    const token = uni.getStorageSync('token');
    if (!token) {
      // 无 JWT → 跳转授权 Loading 页
      uni.redirectTo({ url: '/pages/auth/loading' });
      return;
    }

    // 2. 有 JWT + query 参数中携带设备编号
    if (options.device_id) {
      uni.redirectTo({
        url: '/pages/index/index?device_id=' + options.device_id,
      });
      return;
    }

    // #ifdef H5
    // 3. URL 路径中携带设备编号（如 http://xxx/A1036）
    const path = window.location.pathname;
    const segments = path.split('/').filter(Boolean);
    if (segments.length > 0) {
      const last = segments[segments.length - 1];
      if (/^[A-Z][A-Z0-9]+$/.test(last)) {
        uni.redirectTo({
          url: '/pages/index/index?device_id=' + last,
        });
        return;
      }
    }
    // #endif
  },
  methods: {
    handleScan() {
      // #ifdef H5
      // 检测是否在微信环境
      const isWechat = /MicroMessenger/i.test(navigator.userAgent);
      if (isWechat) {
        // 微信环境：拉起微信扫一扫
        // 注意：需要后端配合引入微信 JS-SDK 并完成签名配置
        uni.showToast({ title: '请使用微信扫一扫功能', icon: 'none' });
        // 如果已配置微信 JS-SDK，可以使用：
        // wx.scanQRCode({
        //   needResult: 1,
        //   scanType: ['qrCode', 'barCode'],
        //   success: (res) => {
        //     const result = res.resultStr;
        //     this.parseScanResult(result);
        //   }
        // });
      } else {
        // 非微信环境
        uni.showToast({ title: '请使用微信扫码或在小程序中打开', icon: 'none' });
      }
      // #endif

      // #ifdef MP-WEIXIN
      uni.scanCode({
        onlyFromCamera: false,
        success: (res) => {
          this.parseScanResult(res.result);
        },
        fail: () => {
          uni.showToast({ title: '扫码取消', icon: 'none' });
        },
      });
      // #endif
    },
    parseScanResult(result) {
      // 解析扫码结果，提取 device_id
      // 预期格式：https://domain/A1036 或 device_id=A1036
      let deviceId = '';

      try {
        const url = new URL(result);
        // 取路径最后一段作为设备编号
        const pathParts = url.pathname.split('/').filter(Boolean);
        if (pathParts.length > 0) {
          deviceId = pathParts[pathParts.length - 1];
        }
      } catch {
        // 非 URL 格式，尝试直接匹配
        if (/^[A-Z][A-Z0-9]+$/.test(result)) {
          deviceId = result;
        }
      }

      if (deviceId) {
        uni.redirectTo({
          url: '/pages/index/index?device_id=' + deviceId,
        });
      } else {
        uni.showToast({ title: '无效的二维码', icon: 'none' });
      }
    },
    goMine() {
      uni.navigateTo({ url: '/pages/index/index?tab=mine' });
    },
    callService() {
      // #ifdef H5
      window.location.href = 'tel:' + this.servicePhone;
      // #endif

      // #ifndef H5
      uni.makePhoneCall({ phoneNumber: this.servicePhone, fail: () => {} });
      // #endif
    },
  },
};
</script>

<style scoped>
page {
  height: 100%;
  background-color: #fff;
}

.scan-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
  background-color: #fff;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

/* 品牌区域 */
.brand-area {
  margin-top: 200rpx;
  margin-bottom: 80rpx;
}

.brand-name {
  font-size: 96rpx;
  font-weight: bold;
  color: #000;
  letter-spacing: 12rpx;
}

/* 扫一扫按钮 */
.scan-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80rpx;
}

.scan-btn {
  width: 360rpx;
  height: 360rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #2979ff, #1e60e0);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 20rpx 60rpx rgba(41, 121, 255, 0.4);
}

/* 二维码图标 */
.qr-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.qr-row {
  display: flex;
  margin-bottom: 6rpx;
}

.qr-row:last-child {
  margin-bottom: 0;
}

.qr-block {
  width: 24rpx;
  height: 24rpx;
  background-color: #fff;
  margin-right: 6rpx;
  border-radius: 4rpx;
}

.qr-space {
  width: 24rpx;
  height: 24rpx;
  margin-right: 6rpx;
}

.scan-text {
  font-size: 40rpx;
  font-weight: bold;
  color: #fff;
}

.scan-tip {
  font-size: 26rpx;
  color: #999;
  margin-top: 40rpx;
}

/* 我的入口 */
.mine-entry {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 140rpx;
}

.mine-icon {
  width: 60rpx;
  height: 54rpx;
  position: relative;
  margin-bottom: 12rpx;
}

.mine-head {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #999;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}

.mine-body {
  width: 44rpx;
  height: 26rpx;
  border-radius: 22rpx 22rpx 0 0;
  background-color: #999;
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
}

.mine-text {
  font-size: 28rpx;
  color: #999;
}

/* 底部客服 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32rpx 0;
  padding-bottom: calc(32rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
}

.footer-text {
  font-size: 26rpx;
  color: #999;
}

.footer-phone {
  font-size: 26rpx;
  color: #2979ff;
}
</style>
