import { fetchData, stsFailContent } from '../utils/index';
let wifiConfigTimer = null;
let wifiConnectTimer = null;

class WeChat_EConnectWifi {
  constructor(params) {
    this.params = params;
    // const { accessToken, deviceSerial, validateCode, customId } = params;
  }

  // 扫描二维码
  scanDevice(accessToken) {
    wx.scanCode({
      success (res) {
        console.log('扫描结果',res)
        const result = res.result;
        console.log(result);
        const temp = result.split('\r');
        console.log('temp', temp);
        if (temp && temp.length > 0) {
          // const res = temp[0];
          const deviceSerial = temp[1];
          const validateCode = temp[2];
          console.log(temp, deviceSerial, validateCode);
          wx.setStorage({
            key: 'deviceSerial',
            data: deviceSerial
          });
    
          wx.setStorage({
            key: 'validateCode',
            data: validateCode
          });

        }
      }
    })
  } 

  searchDeviceInfo = (accessToken = '', deviceSerial = '') => {
    const promise = new Promise((resolve, reject) => {
      if (!accessToken || !deviceSerial) {
        reject('searchDeviceInfo:fail:params error');
      }
      fetchData('/api/v3/device/searchDeviceInfo', '', {accessToken, deviceSerial}, 'POST' ,(res) => {
        
        if (res) {
          resolve(res);
        } else {
          reject('searchDeviceInfo:fail:request fail')
        }
      }, (err) => {
        reject('searchDeviceInfo:fail:network error')
      });
    });

    return promise
  }

  connectWifi = (deviceSerial = '', validateCode = '', accessToken = '', BSSID, SSID, wifiPassword) => {
    const promise = new Promise((resolve, reject) => {
      if (!accessToken || !deviceSerial || !validateCode || !BSSID || !SSID || !wifiPassword) {
        reject('connectWifi:fail:params error');
      }

      const deviceSSID = 'SoftAP_' + deviceSerial;
      const devicePassword = 'SoftAP_' + validateCode;
      wx.startWifi({
        success (res) {
          console.log(res.errMsg);
          wx.connectWifi({ 
            SSID: deviceSSID,
            password: devicePassword,
            success (res) {
              console.log('connectWifi success:', res);
              if (res.errCode == 0 || res.errMsg == 'connectWifi:ok') {

                // 兼容不同机型，有些机型可以通过onWifiConnected识别是否连上目标wifi，有些机型不可以,因此设置定时器
                let timer = setTimeout(() => {
                  console.log('超时调用');
                  wifiConfig(SSID, BSSID, wifiPassword,accessToken);
                  clearTimeout(timer);
                  // 如果设备超时无响应将重试一次
                  // 存在设备超时无响应，此时将再次发送请求
                  let wifiConfigTimer = setTimeout(() => {
                    wifiConfig(SSID, BSSID, wifiPassword,accessToken);
                    clearTimeout(wifiConfigTimer);
                  }, 30000);

                  // 设置第二次超时时间，仍超时，则默认跳转至配置失败页面
                  // 设置响应超时时间为60s
                  wifiConnectTimer = setTimeout(() => {
                    clearTimeout(wifiConnectTimer);
                    
                    reject('connectWifi:fail:connect deviceNetwork fail')
                  }, 31000);

                }, 3000);

                // 判断是否连接上目标网络
                wx.onWifiConnected((result) => {
                  console.log('onWifiConnected',result.wifi.SSID);
                  if (deviceSSID === result.wifi.SSID) {
                    wifiConfig(SSID, BSSID, wifiPassword,accessToken);
                    clearTimeout(timer);
                    // 如果设备超时无响应将重试一次
                    // 存在设备超时无响应，此时将再次发送请求
                    let wifiConfigTimer = setTimeout(() => {
                      wifiConfig(SSID, BSSID, wifiPassword,accessToken);
                      clearTimeout(wifiConfigTimer);
                      
                    }, 30000);

                    // 设置第二次超时时间，仍超时，则默认跳转至配置失败页面
                    // 设置响应超时时间为30s
                    wifiConnectTimer = setTimeout(() => {
                      clearTimeout(wifiConnectTimer);
                      
                      reject('connectWifi:fail:connect deviceNetwork fail')
                    }, 31000);
                  } 
                });
                
              }
            },
            fail(err) {
              console.log(err);
              // that.setData({
              //   pageLoading: false
              // });
              console.log('wifi connect fail');
              // wx.navigateTo({
              //   url: '/packageD/pages/connectWifiFail/index?accessToken='+accessToken+'&validateCode='+validateCode+'&deviceSerial='+deviceSerial,
              // })
              reject('connectWifi:fail:connect deviceNetwork fail')
            }
          })
        }
      });
      
      const wifiConfig = (SSID, BSSID, wifiPassword,accessToken) => {
        
        console.log('正在给设备配置wifi');
    
        wx.request({
          url: 'http://192.168.8.1:8682/PreNetwork/WifiConfig',
          method: 'PUT',
          data: {
            areaCode:"",
            token: accessToken,
            lbs_domain: 'open.ys7.com',
            wifi_info:{
              "bssid": BSSID,
              "ssid": SSID,
              "password":wifiPassword
            },
            token: ''
          },
          header: {
            'content-type': 'text/plain' 
          },
          success:(res) =>{
            console.log('wifiConfig success:',res);
            clearTimeout(wifiConfigTimer);
            clearTimeout(wifiConnectTimer);
            if (res && res.data ) {
              if (wifiConfigTimer) {
                clearTimeout(wifiConfigTimer);
              }
              
              console.log('wifi 配置接口返回',res);
              // 现关闭连接的设备wifi,因为其无法发送网络请求
              wx.startWifi({
                success (res) {
                  console.log(res.errMsg);
                  wx.connectWifi({ 
                    SSID: SSID,
                    password: wifiPassword,
                    success (res) {
                    }
                  })
                }
              });
              // 设备响应需要一定的时间
              let timer = setTimeout(() => {
                
                resolve()
                clearTimeout(timer)
              }, 10000);
               
            } else {
              // this.setData({
              //   pageLoading: false
              // });
              console.log('wifiConfig fail');
    
              // wx.navigateTo({
              //   url: '/packageD/pages/connectWifiFail/index?accessToken='+accessToken+'&validateCode='+validateCode+'&deviceSerial='+deviceSerial,
              // })
              reject('connectWifi:fail:device config fail')
            } 
          },
          error:(err)=>{
            console.log('wifiConfig fail:',err);
            clearTimeout(wifiConfigTimer);
            clearTimeout(wifiConnectTimer);
            // this.setData({
            //   pageLoading: false
            // });
            console.log('wifiConfig fail');
            // wx.navigateTo({
            //   url: '/packageD/pages/connectWifiFail/index?accessToken='+accessToken+'&validateCode='+validateCode+'&deviceSerial='+deviceSerial,
            // })
            reject('connectWifi:fail:device config fail')


          }
        })
      }

    });

    return promise
  } 
  
  // check network
  checkNetWork = () => {
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType;
        if (!networkType || networkType === 'none') {
          wx.showToast({
            title: '当前网络异常',
            icon: 'none',
            duration: 2000,
          });
          return
        }
      }
    })
  }


}


export const EConnectWifi = (props) => {
  const wechat_econnectWif_sdk = new WeChat_EConnectWifi(props)
  return wechat_econnectWif_sdk;
}