// 设备工具类 - 对应Flutter的device_util.dart
const config = require('../config/config.js');

class DeviceUtil {
  constructor() {
    this.systemInfo = null;
    this.deviceId = null;
    this.initialized = false;
  }

  // 初始化
  async init() {
    try {
      // 获取系统信息
      await this.getSystemInfo();
      
      // 生成设备ID
      this.generateDeviceId();
      
      this.initialized = true;
      console.log('设备工具初始化完成');
      console.log('设备信息:', this.getDeviceInfo());
    } catch (error) {
      console.error('设备工具初始化失败:', error);
    }
  }

  // 获取系统信息
  async getSystemInfo() {
    return new Promise((resolve, reject) => {
      wx.getSystemInfo({
        success: (res) => {
          this.systemInfo = res;
          console.log('系统信息获取成功:', res);
          resolve(res);
        },
        fail: (error) => {
          console.error('获取系统信息失败:', error);
          reject(error);
        }
      });
    });
  }

  // 生成设备ID
  generateDeviceId() {
    // 小程序无法获取真正的设备ID，使用时间戳+随机数生成
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000000);
    this.deviceId = `mp_${timestamp}_${random}`;
    
    // 尝试从存储中获取已保存的设备ID
    try {
      const savedDeviceId = wx.getStorageSync('lanmei_deviceId');
      if (savedDeviceId) {
        this.deviceId = savedDeviceId;
      } else {
        // 保存生成的设备ID
        wx.setStorageSync('lanmei_deviceId', this.deviceId);
      }
    } catch (error) {
      console.error('设备ID操作失败:', error);
    }
  }

  // 获取设备ID
  getDeviceId() {
    if (!this.deviceId) {
      this.generateDeviceId();
    }
    return this.deviceId;
  }

  // 获取设备型号
  getDeviceModel() {
    if (!this.systemInfo) {
      return 'Unknown';
    }
    return this.systemInfo.model || 'Unknown';
  }

  // 获取设备类型 - 与Flutter项目保持一致
  getDeviceType() {
    // 小程序使用android类型，后端只接受'android'或'ios'
    return 'android';
  }

  // 获取系统版本
  getSystemVersion() {
    if (!this.systemInfo) {
      return 'Unknown';
    }
    return this.systemInfo.system || 'Unknown';
  }

  // 获取微信版本
  getWeChatVersion() {
    if (!this.systemInfo) {
      return 'Unknown';
    }
    return this.systemInfo.version || 'Unknown';
  }

  // 获取应用版本
  getAppVersion() {
    return config.appVersion;
  }

  // 获取平台信息
  getPlatform() {
    if (!this.systemInfo) {
      return 'unknown';
    }
    return this.systemInfo.platform || 'unknown';
  }

  // 获取屏幕信息
  getScreenInfo() {
    if (!this.systemInfo) {
      return {
        screenWidth: 375,
        screenHeight: 812,
        windowWidth: 375,
        windowHeight: 812,
        pixelRatio: 2
      };
    }

    return {
      screenWidth: this.systemInfo.screenWidth,
      screenHeight: this.systemInfo.screenHeight,
      windowWidth: this.systemInfo.windowWidth,
      windowHeight: this.systemInfo.windowHeight,
      pixelRatio: this.systemInfo.pixelRatio,
      statusBarHeight: this.systemInfo.statusBarHeight
    };
  }

  // 获取网络类型
  async getNetworkType() {
    return new Promise((resolve) => {
      wx.getNetworkType({
        success: (res) => {
          console.log('网络类型:', res.networkType);
          resolve(res.networkType);
        },
        fail: (error) => {
          console.error('获取网络类型失败:', error);
          resolve('unknown');
        }
      });
    });
  }

  // 获取电量信息
  async getBatteryInfo() {
    return new Promise((resolve) => {
      wx.getBatteryInfo({
        success: (res) => {
          console.log('电量信息:', res);
          resolve({
            level: res.level,
            isCharging: res.isCharging
          });
        },
        fail: (error) => {
          console.error('获取电量信息失败:', error);
          resolve({
            level: 100,
            isCharging: false
          });
        }
      });
    });
  }

  // 获取指南针信息
  async getCompassInfo() {
    return new Promise((resolve) => {
      // 先启动指南针
      wx.startCompass({
        success: () => {
          // 监听指南针数据
          wx.onCompassChange((res) => {
            resolve({
              direction: res.direction,
              accuracy: res.accuracy
            });
            // 取消监听
            wx.offCompassChange();
          });
        },
        fail: (error) => {
          console.error('启动指南针失败:', error);
          resolve({
            direction: 0,
            accuracy: 0
          });
        }
      });
    });
  }

  // 获取加速计信息
  async getAccelerometerInfo() {
    return new Promise((resolve) => {
      wx.startAccelerometer({
        interval: 'normal',
        success: () => {
          wx.onAccelerometerChange((res) => {
            resolve({
              x: res.x,
              y: res.y,
              z: res.z
            });
            // 取消监听
            wx.offAccelerometerChange();
            wx.stopAccelerometer();
          });
        },
        fail: (error) => {
          console.error('启动加速计失败:', error);
          resolve({
            x: 0,
            y: 0,
            z: 0
          });
        }
      });
    });
  }

  // 获取陀螺仪信息
  async getGyroscopeInfo() {
    return new Promise((resolve) => {
      wx.startGyroscope({
        interval: 'normal',
        success: () => {
          wx.onGyroscopeChange((res) => {
            resolve({
              x: res.x,
              y: res.y,
              z: res.z
            });
            // 取消监听
            wx.offGyroscopeChange();
            wx.stopGyroscope();
          });
        },
        fail: (error) => {
          console.error('启动陀螺仪失败:', error);
          resolve({
            x: 0,
            y: 0,
            z: 0
          });
        }
      });
    });
  }

  // 获取设备方向
  async getDeviceOrientation() {
    return new Promise((resolve) => {
      wx.startDeviceMotionListening({
        interval: 'normal',
        success: () => {
          wx.onDeviceMotionChange((res) => {
            resolve({
              alpha: res.alpha,
              beta: res.beta,
              gamma: res.gamma
            });
            // 取消监听
            wx.offDeviceMotionChange();
            wx.stopDeviceMotionListening();
          });
        },
        fail: (error) => {
          console.error('启动设备方向监听失败:', error);
          resolve({
            alpha: 0,
            beta: 0,
            gamma: 0
          });
        }
      });
    });
  }

  // 获取完整设备信息
  getDeviceInfo() {
    return {
      deviceId: this.getDeviceId(),
      model: this.getDeviceModel(),
      type: this.getDeviceType(),
      system: this.getSystemVersion(),
      platform: this.getPlatform(),
      wechatVersion: this.getWeChatVersion(),
      appVersion: this.getAppVersion(),
      screen: this.getScreenInfo()
    };
  }

  // 监听电量变化
  onBatteryLevelChange(callback) {
    if (this.canUseApi('onBatteryLevelChange')) {
      wx.onBatteryLevelChange(callback);
    } else {
      console.warn('当前环境不支持电量变化监听API');
      // 提供模拟回调
      setTimeout(() => {
        callback({
          level: 100,
          isCharging: false
        });
      }, 100);
    }
  }

  // 监听指南针变化
  onCompassChange(callback) {
    wx.startCompass({
      success: () => {
        wx.onCompassChange(callback);
      },
      fail: (error) => {
        console.error('启动指南针监听失败:', error);
      }
    });
  }

  // 监听加速计变化
  onAccelerometerChange(callback, interval = 'normal') {
    wx.startAccelerometer({
      interval: interval,
      success: () => {
        wx.onAccelerometerChange(callback);
      },
      fail: (error) => {
        console.error('启动加速计监听失败:', error);
      }
    });
  }

  // 监听陀螺仪变化
  onGyroscopeChange(callback, interval = 'normal') {
    wx.startGyroscope({
      interval: interval,
      success: () => {
        wx.onGyroscopeChange(callback);
      },
      fail: (error) => {
        console.error('启动陀螺仪监听失败:', error);
      }
    });
  }

  // 监听设备方向变化
  onDeviceMotionChange(callback, interval = 'normal') {
    wx.startDeviceMotionListening({
      interval: interval,
      success: () => {
        wx.onDeviceMotionChange(callback);
      },
      fail: (error) => {
        console.error('启动设备方向监听失败:', error);
      }
    });
  }

  // 停止所有传感器监听
  stopAllSensors() {
    try {
      // 安全地停止传感器
      if (this.canUseApi('stopCompass')) wx.stopCompass();
      if (this.canUseApi('stopAccelerometer')) wx.stopAccelerometer();
      if (this.canUseApi('stopGyroscope')) wx.stopGyroscope();
      if (this.canUseApi('stopDeviceMotionListening')) wx.stopDeviceMotionListening();
      
      // 安全地取消监听
      if (this.canUseApi('offBatteryLevelChange')) wx.offBatteryLevelChange();
      if (this.canUseApi('offCompassChange')) wx.offCompassChange();
      if (this.canUseApi('offAccelerometerChange')) wx.offAccelerometerChange();
      if (this.canUseApi('offGyroscopeChange')) wx.offGyroscopeChange();
      if (this.canUseApi('offDeviceMotionChange')) wx.offDeviceMotionChange();
      
      console.log('所有传感器监听已停止');
    } catch (error) {
      console.error('停止传感器监听失败:', error);
    }
  }

  // 检查是否支持指定API
  canUseApi(apiName) {
    return typeof wx[apiName] === 'function';
  }

  // 获取支持的API列表
  getSupportedApis() {
    const apis = [
      'getBatteryInfo',
      'startCompass',
      'startAccelerometer',
      'startGyroscope',
      'startDeviceMotionListening',
      'getLocation',
      'chooseLocation',
      'openLocation'
    ];

    const supportedApis = [];
    apis.forEach(api => {
      if (this.canUseApi(api)) {
        supportedApis.push(api);
      }
    });

    return supportedApis;
  }

  // 振动反馈
  vibrate(type = 'short') {
    if (type === 'short') {
      wx.vibrateShort({
        success: () => console.log('短震动成功'),
        fail: (error) => console.error('短震动失败:', error)
      });
    } else if (type === 'long') {
      wx.vibrateLong({
        success: () => console.log('长震动成功'),
        fail: (error) => console.error('长震动失败:', error)
      });
    }
  }

  // 设置屏幕亮度
  setScreenBrightness(value) {
    wx.setScreenBrightness({
      value: value,
      success: () => console.log('设置屏幕亮度成功:', value),
      fail: (error) => console.error('设置屏幕亮度失败:', error)
    });
  }

  // 获取屏幕亮度
  async getScreenBrightness() {
    return new Promise((resolve) => {
      wx.getScreenBrightness({
        success: (res) => {
          console.log('屏幕亮度:', res.value);
          resolve(res.value);
        },
        fail: (error) => {
          console.error('获取屏幕亮度失败:', error);
          resolve(0.5);
        }
      });
    });
  }

  // 保持屏幕常亮
  keepScreenOn(keepOn = true) {
    wx.setKeepScreenOn({
      keepScreenOn: keepOn,
      success: () => console.log('设置屏幕常亮:', keepOn),
      fail: (error) => console.error('设置屏幕常亮失败:', error)
    });
  }
}

// 创建单例
const deviceUtil = new DeviceUtil();

module.exports = deviceUtil; 