import { 
  GetRoomTypeNode,
  GetRoomType,
  WebChatUpgrade,
  QueryUpdateHostStatus,
  ForwardQueryUpdateHostProgressBar
} from '../lib/RequestingCenter.js' 
import { EventEmitter } from './eventEmitter.js'

export default class DeviceUpgrader extends EventEmitter {
  constructor() {
    super();
    this.isUpgrading = false;
    this.currentUpgrade = null;
    this.pollTimer = null;
    this.startTime = null;
  }

  /**
   * 开始升级
   * @param {'firmware'|'config'} type 升级类型
   * @param {Object} params 升级参数
   * @param {string} params.roomTypeID 房型ID
   * @param {string[]} params.hostidLists 主机ID列表
   * @param {string} [params.upgradefileName] 升级文件名
   * @param {string} [params.hotelid] 酒店ID（固件升级需要）
   * @returns {Promise}
   */
  startUpgrade(type, params) {
    
    if (this.isUpgrading) {
      return Promise.reject(new Error('已有升级任务进行中'));
    }

    return new Promise((resolve, reject) => {
      this.isUpgrading = true;
      this.startTime = Date.now();
      const timeout = type === 'firmware' ? 10 * 60 * 1000 : 3 * 60 * 1000;

      // 升级任务信息
      this.currentUpgrade = {
        type,
        params,
        resolve,
        reject,
        timeout,
        cancelled: false
      };

      // 发起升级请求
      this._requestUpgrade()
        .then(() => {
          // 开始轮询进度
          this._startPolling();
        })
        .catch(err => {
          this._cleanup();
          reject(err);
        });

      // 超时处理
      setTimeout(() => {
        if (this.isUpgrading) {
          this._handleTimeout();
        }
      }, timeout);
    });
  }

  /**
   * 取消升级
   */
  cancelUpgrade() {
    if (!this.isUpgrading || !this.currentUpgrade) return;

    this.currentUpgrade.cancelled = true;
    this._cleanup();
    this.currentUpgrade.reject(new Error('升级已取消'));
  }

  /**
   * 获取是否正在升级
   */
  getIsUpgrading() {
    return this.isUpgrading;
  }

  /**
   * 请求升级接口
   */
  async _requestUpgrade() {
    
    const roomTypeID=this.currentUpgrade.params.roomTypeID
    const hostidLists = this.currentUpgrade.params.hostidLists
    const  upgradefileName      = this.currentUpgrade.params.upgradefileName
    const res =  await WebChatUpgrade({
      roomTypeID:roomTypeID,
      hostidLists:hostidLists,
      upgradefileName:upgradefileName
    })
  
   
    if (res.IsSuccess) {
      
    }else{
      throw new Error(res.data.message || '升级请求失败');
    }
  }

  /**
   * 开始轮询进度
   */
  _startPolling() {
    this._polling = true; 

    this.pollTimer = setInterval(() => {
      if (!this._polling) return;  
      this._queryProgress()
        .then(progress => {
          this.emit('progress', progress +"%")
          // 进度100%表示完成
          if (progress >= 100) {
            this._polling = false;       // ③ 关闭标记\
            if (this.currentUpgrade) {
              this.currentUpgrade.resolve({ success: true, progress: '100%' });
            }
            this._cleanup();
            //this.currentUpgrade.resolve({ success: true, progress: 100 });
         
            return; 
          }
        })
        .catch(err => {
          this._polling = false;       // ③ 关闭标记
          this.emit('error', err)
          console.log(err)
          this._cleanup();
          this.currentUpgrade.reject(err);
        });
    }, 1000);
    
  }

  /**
   * 查询进度
   */
  async _queryProgress() {
    const { type, params, upgradefileName} = this.currentUpgrade;
    let url, data;
    let res;
    if (type === 'firmware') {
      
      res=  await ForwardQueryUpdateHostProgressBar({
        hostIDList:params.hostidLists      
      })
     
    } else {
     res= await QueryUpdateHostStatus({
        hotelid:params.hotelid,
        roomTypeID:params.roomTypeID
      })
     
    }

  
    
    console.log(res)
    if (type === 'firmware'){
        if (res.IsSuccess) {
          if (Array.isArray(res.Response) && res.Response.length > 0) {
            console.log(res.Response[0].BaiFenBi)
            if (res.Response[0].BaiFenBi===""){
              return 0;
            }
            return res.Response[0].BaiFenBi.replace('%', '') ;
          }else{
            return 0;
          }
      
    }
    else{
      throw new Error('查询进度失败');
    }
    }else{
      
      if (res.total ==1) {      
        var getnode 
          if (res.rows.length>0) {
            getnode=res.rows[0]
            let bufarry = params.upgradefileName.split("_")
            let Version =bufarry[0]+ ".0.0"
            if (getnode.ConfigVersion==Version) {            
              return 100;
            }  else{                           
              return 0;
            }
          }else
          {
            return 0;
          }       
      }
      else{
        throw new Error('查询进度失败');
    }
    }
  }

  /**
   * 处理超时
   */
  _handleTimeout() {
    this._cleanup();
    this.currentUpgrade.reject(new Error('升级超时'));
  }

  /**
   * 清理资源
   */
  _cleanup() {
    this.isUpgrading = false;
    if (this.pollTimer) {
      clearInterval(this.pollTimer);
      this.pollTimer = null;
    }

    this.startTime = null;
    this.currentUpgrade = null;
   
  }
}

// // 使用示例
// const upgrader = new DeviceUpgrader();

// // 开始固件升级
// upgrader.startUpgrade('firmware', {
//   roomTypeID: '123',
//   hostidLists: ['host1', 'host2'],
//   upgradefileName: 'v2.0.bin',
//   hotelid: 'hotel123'
// })
// .then(result => {
//   console.log('升级成功', result);
// })
// .catch(err => {
//   console.error('升级失败', err);
// });

// // 取消升级
// // upgrader.cancelUpgrade();

// // 查询是否升级中
// console.log('是否升级中:', upgrader.getIsUpgrading());
