<template>
  <view class="container">
    <text>服务端IP:</text>
    <input v-model="serverIp" placeholder="192.168.1.100" />
    
    <button @click="scan">🔍 自动扫描</button>
    <button @click="connect">🚀 连接</button>
    
    <text v-if="scanning">扫描中...</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      serverIp: uni.getStorageSync('serverIp') || '',
      scanning: false
    };
  },
  methods: {
    async scan() {
      if (this.scanning) return;
      this.scanning = true;

      const ip = await this.scanNetwork();
      if (ip) {
        this.serverIp = ip;
        uni.showToast({ title: '发现: ' + ip });
      } else {
        uni.showToast({ icon: 'none', title: '未发现' });
      }

      this.scanning = false;
    },

    async scanNetwork() {
      // 1. 试上次 IP
      const lastIp = uni.getStorageSync('serverIp');
      if (lastIp && await this.testIp(lastIp)) {
        return lastIp;
      }

      // 2. 获取网段
      const prefix = this.getNetworkPrefix();

      // 3. 扫描 1-50
      for (let i = 1; i <= 50; i++) {
        const ip = `${prefix}${i}`;
        if (await this.testIp(ip)) {
          return ip;
        }
        await this.delay(100);
      }

      return null;
    },

    testIp(ip) {
      return new Promise(resolve => {
        uni.request({
          url: `http://${ip}:8811/ping`,
          timeout: 3000,
          success: res => {
            resolve(res.statusCode === 200 ? ip : null);
          },
          fail: () => resolve(null)
        });
      });
    },

    getNetworkPrefix() {
      let prefix = '192.168.1.';
      if (typeof plus !== 'undefined' && plus.networkinfo) {
        const ip = plus.networkinfo.getIPAddress();
        if (ip) prefix = ip.replace(/\.\d+$/, '.') + '.';
      }
      return prefix;
    },

    delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },

    connect() {
      if (!this.serverIp) {
        uni.showToast({ icon: 'none', title: '请先设置IP' });
        return;
      }

      uni.setStorageSync('serverIp', this.serverIp);

      uni.connectSocket({ url: `ws://${this.serverIp}:8811` });
      uni.onSocketOpen(() => {
         'link';
      });
    }
  }
};
</script>