import common from '../utils/util';
import constant from '../utils/constant';

var app = getApp();
var dataSendTimeout = 0;

function getData(url, callback) {
  if (!app.globalData.IsProduction)
    console.log("加密前的结果为===", url);
  var url = common.Encrypt(url);
  //console.log("加密后的结果为===",url);
  wx.request({
    url: app.globalData.serverUrl + url,
    timeout:150000,
    success: function (res) {
      if (res.statusCode)
        common.checkError(res.statusCode);
      var data = res.data.result;
      callback(data);
    },
    fail: function () {
      wx.showToast({
        title: '系统忙请稍候',
        // image: "../images/universalpic_warning_white_126x120.png",
        duration: 3000
      });
      var err={};
      err.errCode=100;
      err.errMsg="网络错误";
      callback(null,err);
    },
  });
}

function postData(url, postData, callback) {
  console.log("加密前的结果为===", url);
  var url = common.Encrypt(url);
  //console.log("加密后的结果为===",url);
  wx.request({
    url: app.globalData.serverUrl + url,
    method: "POST",
    timeout:150000,
    data: postData,
    success: function (res) {
      if (res.statusCode)
        common.checkError(res.statusCode);
      var data = res.data.result;
      callback(data);
    },
    fail: function () {
      wx.showToast({
        title: '系统忙请稍候',
        duration: 3000
      });
    },
  });
}

function getLocalHost(callback) {
  if (!app.globalData.IsProduction) {
    var url = common.Encrypt("Ping");
    wx.request({
      url: app.globalData.serverUrlLocalhost + url,
      success: function (res) {
        app.globalData.serverUrl = app.globalData.serverUrlLocalhost;
        callback();
      },
      fail: function () {
        app.globalData.serverUrl = app.globalData.serverUrlServer;
        callback();
      },
    });
  } else {
    app.globalData.serverUrl = app.globalData.serverUrlServer;
    callback();
  }
}

function getPageInfo(){
  let result={};
  const pages = getCurrentPages(); // 获取页面栈
  result.NavigationDepth = pages.length;
  console.log("导航深度:", result.NavigationDepth);
  const prevPage = pages[pages.length - 2];
  result.FromRoute = prevPage ? prevPage.route : null;
  console.log("来源页面:", result.FromRoute);
  const currentPage = pages[pages.length - 1]; // 当前页面对象
  result.CurrentRoute = currentPage.route; // 当前页面路径
  console.log("当前页面:", result.CurrentRoute);

  if (pages.length > 1) {
    result.BackFromPage = pages[pages.length - 1].route;
    console.log("返回来源页面:", result.BackFromPage);
  }
  
  return result;
}

function getWindowHeight() {
  var height = app.globalData.systemInfo.windowHeight;
  //console.log("app.globalData.systemInfo.windowHeight:" + app.globalData.systemInfo.windowHeight * 2);
  if (app.globalData.systemInfo.model) {
    if (height == 504 && (
        app.globalData.systemInfo.model.indexOf("iPhone 6<") >= 0 ||
        app.globalData.systemInfo.model.indexOf("iPhone 7<") >= 0 ||
        app.globalData.systemInfo.model.indexOf("iPhone 6s<") >= 0 ||
        app.globalData.systemInfo.model.indexOf("iPhone 5") >= 0 ||
        app.globalData.systemInfo.model.indexOf("iPhone SE") >= 0
      )) {
      height = 596;
    } else if (app.globalData.systemInfo.model.indexOf("iPad") >= 0) {
      height = 470;
    }
  }

  height = height * 2;
  if (app.globalData.systemInfo.system && app.globalData.systemInfo.system.indexOf("Android") >= 0) {
    height = height + 168;
  } else {
    height = height + 50;
  }
  //console.log("height:" + height);

  //var height = app.globalData.systemInfo.screenHeight * 2;
  return height;
}

function onSelect(obj,event,callback){
  var result=false;
  var str=event.currentTarget.dataset.object;
  var index=event.currentTarget.dataset.index;
  var clickType=event.currentTarget.dataset.clicktype;

  if (clickType=="checkbox"){
    if (obj.data[str][index].CSS)
      obj.data[str][index].CSS="";
    else{
      obj.data[str][index].CSS="Selected";
      result=true;
    }
  }
  else{
    for(var i=0;i<obj.data[str].length;i++){
      if (i==index){
        obj.data[str][i].CSS="Selected";
      }
      else{
        obj.data[str][i].CSS="";
      }
    }
  }
  obj.setData(obj.data);
  callback(obj,event,result);
}

function checkGenerating(){
  let that=this;
  if (app.globalData.Generating && !app.globalData.GeneratingStart){
    app.globalData.GeneratingStart=true;
    let timeStart=new Date().getTime();
    let intervalGenerate=setInterval(function(){
      let time=(new Date().getTime()-timeStart)/1000;
      console.log(time);
      if (!app.globalData.Generating){
        clearInterval(intervalGenerate);
        let page=that.getPageInfo();
        if (!(page.NavigationDepth==3 
          && page.CurrentRoute=="pages/main/article" 
          && page.BackFromPage=="pages/main/article")){
            app.globalData.Generating=false;
            app.globalData.GeneratingStart=false;
            wx.showModal({
              title: '通知',
              content: '文章生成好了。',
              cancelText:"不去",
              confirmText:"去看",
              complete: (res) => {
                if (res.confirm) {
                  let next='article?ID=MAX';
                  wx.reLaunch({
                    url: 'index',
                    complete:function(){
                      wx.navigateTo({
                        url: next,
                      })
                    }
                  })
                }
              }
            });
          }
      }
      if (time > 60){
        app.globalData.Generating=false;
        app.globalData.GeneratingStart=false;
        clearInterval(intervalGenerate);
      }

    },1000);
  }
}

function showGuideContainer(obj,myClass,imageLeft,imageTop,imageName,closeLeft,closeTop,offsetLeft,offsetTop){
  setTimeout(function(){
    wx.createSelectorQuery().select(myClass).boundingClientRect(function (rect) {
      console.log("rect.left:"+rect.left);
      console.log("rect.top:"+rect.top);
      console.log("rect.width:"+rect.width);
      console.log("rect.height:"+rect.height);
      if (offsetTop)
        rect.top+=offsetTop;
      if (offsetLeft)
        rect.left+=offsetLeft;
        
      rect.left2=(rect.left+rect.width);

      obj.setData({
        panelGuideContainerTop:rect.top,
        panelGuideContainerWidth1:rect.left,
        panelGuideContainerHeight1:rect.height,
        panelGuideContainerLeft2:rect.left2,
        panelGuideContainerCloseLeft:closeLeft,
        panelGuideContainerCloseTop:closeTop,
        panelGuideContainerImage:imageName,
      });
      obj.setData({
        panelGuideContainerImageLeft:obj.data.panelGuideContainerWidth1+imageLeft,
        panelGuideContainerImageTop:obj.data.panelGuideContainerTop+imageTop,
      });
    }).exec();
  },200);
}


// 阻止示例面板的触摸事件传递到底层
function catchTouchMove(e) {
  // 这个函数不需要做任何事情，只需要捕获事件防止冒泡
  return false;
}

module.exports = {
  getData: getData,
  postData: postData,
  getLocalHost: getLocalHost,
  getWindowHeight: getWindowHeight,
  onSelect:onSelect,
  checkGenerating:checkGenerating,
  getPageInfo:getPageInfo,
  showGuideContainer:showGuideContainer,
  catchTouchMove: catchTouchMove,
}