import $ from './../../utils/Tool'
import router from './../../utils/router'
import {getSetting,getLocation} from './../../utils/auth'
const AUTH = require('../../utils/auth')
import icons from "../../utils/icon"
import {getPropertyData,submitAdjust,getCurrentSeason,queryUseranswer} from '../../requests/api';
import Toast from '../../vant-weapp/dist/toast/toast';
import {
  userCheck,
  powerCheck,
  getEquipmentAction,
  getfeedBack,
  getSpacedetail,
  openSpace,
  workLeave,
  contactTenant
} from "../../requests/api";
let refreshTimer=null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    surveyShow:false,
    lottieShow:true,
    spaceDetail:null,
    effectTime:-1,
    statusList: icons.statusList,
    spacestatusList:icons.spacestatusList,
    spaceStatus: "",
    spaceStatusId:null,
    tempType: [
      {
        id: 1,
        value: "有点冷",
        checked: false,
        imgSrc: "../../static/images/cold.png"
      },
      {
        id: 3,
        value: "有点热",
        checked: false,
        imgSrc: "../../static/images/hot.png"
      },
      {
        id: 2,
        value: "太冷了",
        checked: false,
        imgSrc: "../../static/images/severityCold.png"
      },
      {
        id: 4,
        value: "太热了",
        checked: false,
        imgSrc: "../../static/images/severityHot.png"
      },
    ],
    windType: [{
      id: 5,
      value: '风太大',
      checked: false,
      imgSrc: "../../static/images/severityWind.png"
    }],
    windTypeValue:-1,
    tempTypeValue:-1,
    currentIndex:-1,
    StandardMode:true, //模式选择
    envNamelist:$.store.get("envNamelist"),
    imgbaseUrl:$.store.get("imgbaseUrl"),
    headerShow:false,
    pageHight:0,
    guideInit:false,
    guideStep:1,
    longitude:null,
    latitude:null,
    feedBack:false, //控制反馈弹窗
    targetTemp:null,
    trunAction:false,
    equipmentStatustext:'',
    equipmentStatus:null,
    willAvg:null,
    tragetChart:[],
    tragetChartcopy:[],
    customPlan:[],
    customPlancopy:null,
    planTemp:null,
    trunupAction:false, //开机提示框
    secondIcon:0,
    secondSpaceStatus:null,
    chartIndex:null,
    targetIndex:0,
    singleOffice:false,
    nextOpenTime:'',
    bgSeasonType:null,
    havePower:{
      result:"fail",
      message:""
    },
    picInitUrl:$.store.get("picInitUrl"),
  },
  onHide(){
    clearInterval(refreshTimer);
    refreshTimer=null;
  },
  // 关闭问卷
  surveyClose(value){
    this.setData({surveyShow:false,lottieShow:true});

    if(value.detail.good){
      wx.showToast({
        title:"感谢您的反馈",
        image:"../../static/images/bixin.png",
        duration: 2000
      })
    }
  },
  // 检查是否需要填写问卷
  async userAnswer(){
    let day = new Date();
    let year = day.getFullYear();
    let month = day.getMonth() + 1;
    month=month<10?('0'+month):month;
    let today = day.getDate();
    today=today<10?('0'+today):today;
    let seasonType="";
    const dataSeason={
      projectId:$.store.get('projectId')||$.storage.get('projectId'),
      date:`${year}${month}${today}`
    }
    await getCurrentSeason(dataSeason).then(res=>{
      if(res.result=="success"){
        seasonType= res.data;
      }
    })
    let projectId= $.store.get('projectId');
    let tenantId= $.store.get('tenantId');
    let data={
      "criteria":{
           "userId": $.store.get('userId'),
           "projectId": projectId,
           "tenantId": tenantId,
           "startTime": {
            "$ge": `${year}${month}${today}`
           },
            "endTime": {
                "$le":`${year}${month}${today}`
            },
        "seasonType": seasonType
       }
    }
    queryUseranswer(data).then(res=>{
      !res.count&&this.setData({surveyShow:true,lottieShow:false})
    })
  },
  goBack(){
    router.pop()
  },
  changeMode(){
    if(this.data.spaceDetail.isClose.toString()!=="true"){
      this.setData({StandardMode:!this.data.StandardMode},()=>{
        if(!this.data.StandardMode){
          this.setData({effectTime:-1})
          this.getChartDate();
        }
      })
    }
  },
  toDetail(e){
    if(Object.keys(e.currentTarget.dataset).length){
      router.push("detail",e.currentTarget.dataset)
    }else{
      router.push("detail",{name:"温度",
      localname:"温度",
      param:"temperature",
      funcid:"Tdb",
      spaceid:this.data.spaceDetail.id,
      projectid:this.data.spaceDetail.projectId})
    }
  },
  checkLevel(value,name){
    let objList={
      humidity:{
        range:[30,70],
        text:["干燥","适宜","湿润"]
      },
      co2:{
        range:[800,1500],
        text:["适宜","偏高","超标"]
      },
      pm25:{
        range:[35,75],
        text:["优","良","差"]
      },
      hcho:{
        range:[0.08,0.1],
        text:["适宜","偏高","超标"]
      }
    };
    value =Number(value)
    let sortArr=[value,...objList[name].range].sort((a,b)=>{return a-b});

    let level=sortArr.findIndex(item=>item===value);
    let levelTxt = objList[name].text[level];
    return {level,levelTxt}
  },
  // 检查是否过引导
  checkGuide(value){
    if(this.data.spaceDetail.isClose.toString()=="true"){
      return
    }
    ($.storage.get('guideInit')&&!$.storage.get('nextRemind')&&value)&&this.userAnswer();
    !$.storage.get('guideInit')&&this.getPageheight();
    this.setData({'guideInit':!$.storage.get('guideInit')})
  },
  // 反馈数据
  changeType(e) {
    if(this.data.bgSeasonType=="Transition"){
      wx.showModal({
        title: '现在是过渡季不可调节',
        showCancel: false,
        confirmText:"我知道了",//默认是“确定”
        // confirmColor: 'skyblue',//确定文字的颜色
        success: function (res) {
        },
        fail: function (res) { },//接口调用失败的回调函数
        complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
     })
      return ;
    }
    if(this.data.havePower.result!=="success"){
      Toast.fail(this.data.havePower.message);
      return
    }
    var currentIndex = e.currentTarget.dataset.index;
    if (e.currentTarget.dataset.type === "temp") {
      this.setData({
        tempTypeValue: currentIndex,
        currentIndex:currentIndex,
        feedBack:true
      });
    } else {
      this.setData({
        windTypeValue: currentIndex,
        currentIndex:currentIndex,
        feedBack:true
      });
    }
    let data = {
      "projectId":this.data.spaceDetail.projectId, //项目id
      "objectId": this.data.spaceDetail.id, //空间id
      "valueType": 1, //固定为1
      "itemId": currentIndex,
      "model":this.data.StandardMode?1:2,
      userId:$.store.get('userId')
    }
    getEquipmentAction(data).then(res => {
      this.setData({
        equipmentStatus: res.equipmentStatus
      });
      let textMsg = "";
      let textMsgarr=[];
      this.data.equipmentStatus.forEach(item => {
        if (item.actions) {
          item.actions.forEach(items => {
            let textMsgobj={};
            textMsgobj.name=item.localName;
            textMsgobj.actions=items;
            textMsgarr.push(textMsgobj);
            textMsg = textMsg + item.localName + '--' + items + ' ';
          })
        }
      })
      this.setData({
        equipmentStatustext: textMsgarr
      });
    })
    getfeedBack(data).then(res => {
      let notice = res.notice ? res.notice.split('。') : [];
      this.setData({
        spaceStatus: res.spaceStatus,
        spaceStatusId: res.icon - 1,
        notice: notice,
        willAvg:res.avg||'--',
      });
      this.buildContact();
    })
  },
  // 建立租户关联
  async buildContact(){
    // let tenatList=$.store.get("tenants");
    let currentTenantId=$.storage.get('tenantId');
    // let flag=false;
    // if(tenatList&&tenatList.length){
    //   flag = tenatList.some(item=>{
    //     return item.tenantId === currentTenantId;
    //   })
    // }
    // if(flag){
    //   return;
    // }
    if(currentTenantId!==this.data.spaceDetail.tenantId){
      // 通过扫码改变租户
      $.store.set('projectId',this.data.spaceDetail.projectId);
      $.store.set('tenantId',this.data.spaceDetail.tenantId);
      $.store.set('changeTenantId',true);
      $.storage.set('projectId',this.data.spaceDetail.projectId);
      $.storage.set('tenantId',this.data.spaceDetail.tenantId);
    }
    this.data.spaceDetail.top=(this.data.spaceDetail.top+''==="undefined")?false:this.data.spaceDetail.top;
    let top = (this.data.spaceDetail.top.toString())=="false"?0:1;
    const data={
      "userId":$.store.get('userId'),//用户id
      "projectId":this.data.spaceDetail.projectId,//项目id
      "spaceId":this.data.spaceDetail.id,//空间id
      "openId":$.store.get('openId'),
      flag:1,
      top:top,
    }

    await contactTenant(data).then(res=>{
      console.log("成功")
    })
  },
  // 下班节能
  turnDown(){
    if(this.data.havePower.result!=="success"){
      Toast.fail(this.data.havePower.message);
      return
    }
    let data = {
      model:1,
      "projectId":this.data.spaceDetail.projectId, //项目id
      "objectId":[this.data.spaceDetail.id], //空间id
      userId:$.store.get('userId'),
      nextOpenTime:this.data.spaceDetail.nextOpenTime||"",
    }
    workLeave(data).then(res=>{
      this.setData({trunAction:true});
      this.buildContact();
    })
  },
  // 重新开启
  turnUp(){
    if(this.data.havePower.result!=="success"){
      Toast.fail(this.data.havePower.message);
      return
    }
    let data = {
      "projectId":this.data.spaceDetail.projectId, //项目id
      "objectId": this.data.spaceDetail.id, //空间id
      model:1,
      userId:$.store.get('userId')
    }
    openSpace(data).then(res=>{
      this.setData({
        secondSpaceStatus: res.spaceStatus,
        secondNotice: res.notice,
        secondIcon: res.icon,
        trunupAction: true
      });
      this.buildContact();
    })
  },
  commitClose(){
    this.setData({trunupAction:false},()=>{
      this.isfeeded(true);
      this.getDetail();
    })
  },
  knowClick(){
    this.setData({feedBack:false,tempTypeValue:-1,windTypeValue:-1,},()=>{
      this.isfeeded();
    });
  },
  knowCloseClick(){
    this.setData({feedBack:false,trunAction:false},()=>{
      this.getDetail();
      this.isfeeded(true);
    });
  },
  // 获取容器高度
  getPageheight:function(){
    let that =this;
    wx.createSelectorQuery().select('#j_page').boundingClientRect(function(rect){
      that.setData({'pageHight':rect.height})
    }).exec()
  },
  //使页面滚动到容器底部
  pageScrollToBottom: function() {
    wx.pageScrollTo({
      scrollTop: this.data.pageHight
    })
  },
  // 步骤引导函数
  nextStep(e){
    if(this.data.guideStep==2){
      $.storage.set('guideInit',true);
      this.setData({'guideInit':false})
    }
    this.setData({'guideStep':2})
    this.pageScrollToBottom();
  },

  async isGetSetting(value) {
    let {authSetting} = await getSetting();
    if(authSetting['scope.userLocation']){
      await this.getUserLocation();
    }else{
      wx.showModal({
        title: '是否授权当前位置',
        content: '需要获取您的地理位置，请确认授权',
        confirmColor: '#f16765',
        success: res => {
          if (res.confirm) {
            wx.openSetting({
              success: async data => {
                  await this.getUserLocation();
                  value&&this.checkPower();
              },
            })
          } else {
            this.setData({havePower: {result: "fail",message: "未定位到您的位置"}})
          }
        }
      })
    }
  },
  // 获取位置信息
  async getUserLocation(cb) {
    var that = this;
    let {latitude,longitude} = await getLocation();
    this.setData({latitude,longitude});
  },
  // 是否有操作权限
  async checkPower() {
    await this.isGetSetting('cb');
    const data = {
      "criteria": {
        "projectId":this.data.spaceDetail.projectId,
        "spaceId": this.data.spaceDetail.id,
        "userId": $.store.get('userId'),
        "tenantId": this.data.spaceDetail.tenantId,
        "longitude": this.data.longitude,
        "latitude": this.data.latitude
      }
    };
    await powerCheck(data).then(res => {
      this.setData({
        havePower: res
      })
    })
  },
  // 获取实时曲线
  async getChartDate(){
    wx.showLoading({
      title:"加载中"
    });
    let data={
      projectId:this.data.spaceDetail.projectId,
      spaceId:this.data.spaceDetail.id,
      funcid:'Tdb'
    }
    let res = await getPropertyData(data);

    if(!res){
      throw "网络错误";
    }
    let {propertyData,dayTarget}=res;
    // 获取期望温度
    this.getHopeTemp(dayTarget).then(()=>{
      this.initDaytarget(dayTarget);
      this.initChartdate(propertyData,dayTarget);
    });
    wx.hideLoading();

  },
  initChartdate(propertyData,dayTarget){
    if(!propertyData&&!propertyData.length&&dayTarget&&!dayTarget.length){
      return ;
    }
    // 目标  { time: "1951",release:0, sales: 38,标准区间: [ 25, 45 ] },
    let baseArr=propertyData&&propertyData.slice(1) || [];
    let tragetChart = [];
    baseArr.forEach(item=>{
      item[1] = (item[1]=="-9999")?null:Number(Number(item[1]).toFixed(1));
    })
    if(baseArr.length===dayTarget.length){
      dayTarget.forEach((item,index)=>{
        let time ='';
        item.time&&(time = item.time.slice(0,2)+':'+item.time.slice(2,4));
        item['temperatureMin']&&(item['temperatureMin']=Number(item['temperatureMin'].toFixed(1)));
        item['temperatureMax']&&(item['temperatureMax']=Number(item['temperatureMax'].toFixed(1)));
        let initObj={
          time:time,
          release:index,
          sales:baseArr[index][1],
          标准区间:[item['temperatureMin'],item['temperatureMax']],
        }
        tragetChart.push(initObj);
      })
    }
    this.setData({tragetChart,tragetChartcopy:tragetChart})
  },
  initDaytarget(value){
    if(!value||!value.length){
      return
    }
    let customPlan=[];
    // 格式化单位 15px为1度 28 18
    let lenpx=25;
    value.forEach((item,index)=>{
      if(item.time.slice(2,6)=="0000"){
        let obj={};
        obj.time=item.date+item.time;
        obj.id=index;
        obj.name=item.time.slice(0,2)+':'+item.time.slice(2,4);
        obj.maxValue= item.temperatureMax;
        obj.minValue = item.temperatureMin || 0;
        obj.distance=(obj.maxValue-obj.minValue)|| 0;
        obj.height=obj.distance*lenpx;
        obj.planTemp=Number(((obj.maxValue+obj.minValue)/2).toFixed(1));
        obj.y=(28 - obj.maxValue)*lenpx;
        customPlan.push(obj)
      }
    })
    this.setData({customPlancopy:this.copyobj(customPlan)})
  },
  getHopeTemp(value){
    return new Promise((reslove,reject)=>{
      if(!value||!value.length){
        return
      }
      let data=new Date();
      let hour = data.getHours();
      let min = data.getMinutes();
      let minIndex = Math.floor(min/15);
      if(minIndex>=3){
        hour = hour + 1;
        min = 0;
      }else{
        min = (minIndex+1)*15;
      }
      let targetTime = (hour>=10?`${hour}`:`0${hour}`)+(min>=10?`${min}`:`0${min}`);
      let isDatelist=[];
      let targetTemp;
      let targetIndex;
      value.forEach((item,index)=>{
        if(item.temperatureMax&&item.temperatureMin){
          isDatelist.push(index)
        }
        if(item.time===`${targetTime}00`){
          targetTemp= parseInt((item.temperatureMax + item.temperatureMin)/2);
          targetIndex = index
        }
      })
      if(targetTemp){
        this.setData({targetTemp:targetTemp,targetIndex:targetIndex})
      }else{
        let index = isDatelist.pop();
        targetTemp = parseInt((value[index].temperatureMax + value[index].temperatureMin)/2);
        this.setData({targetTemp:targetTemp,targetIndex:targetIndex})
      }


      reslove();

    })
    // 获取当前时间最近的15分钟

  },
  // 更改即时调节选项
  effectChange(event){
    this.setData({
      effectTime: event.detail,
    },()=>{
      let changeDate=JSON.parse(JSON.stringify(this.data.tragetChartcopy));
      if(event.detail==='1'){
        let len = (this.data.targetIndex+8)>changeDate.length?changeDate.length:(this.data.targetIndex+8)
        for(var i=this.data.targetIndex;i<len;i++){
          changeDate[i].sales = this.data.targetTemp;
          changeDate[i]['标准区间'] =[changeDate[i].sales-1,changeDate[i].sales+1];
        }
      }else if(event.detail==='2'){
        let len = changeDate.length;
        for(var i=this.data.targetIndex;i<len;i++){
          changeDate[i].sales = this.data.targetTemp;
          changeDate[i]['标准区间'] =[changeDate[i].sales-1,changeDate[i].sales+1];
        }
      }else{
        let len =  (this.data.targetIndex+4)>changeDate.length?changeDate.length:(this.data.targetIndex+4);
        let start = (this.data.targetIndex-4)<0?0:(this.data.targetIndex-4);
        for(var i=start;i<len;i++){
          changeDate[i].sales = this.data.targetTemp;
          changeDate[i]['标准区间'] =[changeDate[i].sales-1,changeDate[i].sales+1];
        }
      }
      this.setData({tragetChart:changeDate});
    });
  },
  // 加期望温度
  addClick(){
    let tepNum=this.data.targetTemp;
    let firstNum = tepNum.toString().split('.')[0];
    let lastNum = tepNum.toString().split('.')[1];
    if(firstNum>=28){
      return
    }
    if(lastNum>=5){
      this.setData({targetTemp:Number(firstNum)+1})
    }else{
      this.setData({targetTemp:Number(firstNum)+0.5})
    }
  },
  // 减期望温度
  minusClick(){
    let tepNum=this.data.targetTemp;
    let firstNum = tepNum.toString().split('.')[0]
    let lastNum = tepNum.toString().split('.')[1]
    if(firstNum<=18&&!lastNum){
      return ;
    }
    if(lastNum>5){
      this.setData({targetTemp:Number(firstNum)+0.5})
    }else if(lastNum<=5){
      this.setData({targetTemp:Number(firstNum)})
    }else{
      this.setData({targetTemp:Number(firstNum)-0.5})
    }
  },
  // 修改期望温度
  taboneSubmit(){
    if(this.data.havePower.result!=="success"){
      Toast.fail(this.data.havePower.message);
      return
    }
    if(!this.data.effectTime||this.data.effectTime<0){
      wx.showToast({
        title:"未选择保持时间",
        icon:"none",
        duration: 1500
      })
      return
    }
    const data={
      "projectId": this.data.spaceDetail.projectId,
      "objectId": this.data.spaceDetail.id,
      "valueType": 2,
      "model":2,
      "durationType":this.data.effectTime || '',
      "value":this.data.targetTemp
    }

    submitAdjust(data).then(async res=>{
      if(res.result="success"){
        wx.hideLoading();
        setTimeout(function () {
          wx.showToast({
            title:"提交成功",
            duration: 2000
          })
        }, 300)

      }
      // this.setData({effectTime:-1})
      await this.buildContact();
      this.isfeeded();
      // this.getChartDate();
    })
  },
  // 修改全天温度
  tabtwoSubmit(){
    if(this.data.havePower.result!=="success"){
      Toast.fail(this.data.havePower.message);
      return
    }
    let customPlan = JSON.parse(JSON.stringify(this.data.customPlan));
    customPlan.forEach(item=>{
      delete item.id;
      delete item.name;
      delete item.planTemp;
      delete item.y;
      delete item.height;
      delete item.distance;
    })
    const data={
      "projectId": this.data.spaceDetail.projectId,
      "objectId": this.data.spaceDetail.id,
      "valueType": 3,
      "model":2,
      "value":this.data.targetTemp,
      "customPlan":customPlan
    }
    submitAdjust(data).then(async res=>{
      wx.hideLoading();
      setTimeout(function () {
        wx.showToast({
          title:"提交成功",
          duration: 2000
        })
      }, 300)
      await this.buildContact();
      this.isfeeded();
      // this.getChartDate();
    })
  },
  showTips(){
      wx.showModal({
        title: '提示',
        content: '非工作时间如需使用空调，或遇特殊问题，请联系环境管理员',
        showCancel:false,
        success: function (res) {
        }
    })
  },
  chartChange(e){
    let y =e.detail.y;
    this.throttle(this.updateChart(y,e),500)
  },
  preventTouchMove: function () {
    return
  },
  updateChart(y,e){
    let lenpx=25;
    let planTempMax = 28 - y/lenpx;
    let {index,distance} =e.currentTarget.dataset;
    let planTemp = Number(((planTempMax*2 - distance)/2).toFixed(1));
    let target=`customPlan[${index}].y`;
    let targetplan=`customPlan[${index}].planTemp`;
    let targetTempMax=`customPlan[${index}].maxValue`;
    let targetTempMin=`customPlan[${index}].minValue`;
    this.setData({[target]:y,[targetplan]:planTemp,chartIndex:index,[targetTempMax]:planTempMax,[targetTempMin]:planTempMax-2});
  },
  throttle(func, delay) {
      let prev = Date.now();
  　　return function() {
          let context = this;
          let args = arguments;
          let now = Date.now();
  　　　　if (now - prev >= delay) {
  　　　　　　func.apply(context, args);
  　　　　　　prev = Date.now();
  　　　　}
  　　}
  },
  fillZore(value) {
    if (value < 10) {
      value = 0 + value
    }
    return value
  },
  formatTimeall(value) {
    let stringValue;
    const date = new Date();
    var nowMonth = date.getMonth() + 1;
    let nowDay = date.getDate();
    let torrowDay = new Date(date);
    torrowDay.setDate(date.getDate() + 1);
    let torrowMonth = torrowDay.getMonth() + 1;
    nowDay = this.fillZore(nowDay);
    nowMonth = this.fillZore(nowMonth);
    torrowMonth = this.fillZore(torrowMonth);
    if (nowMonth == value.substring(4, 6) || torrowMonth == value.substring(4, 6)) {
      if (value.substring(6, 8) == nowDay) {
        stringValue = "今日"
      }
      let torrowVlue = torrowDay.getDate();
      torrowVlue = this.fillZore(torrowVlue);
      if (value.substring(6, 8) == torrowVlue) {
        stringValue = "明日"
      }
    }
    if (stringValue) {
      stringValue = stringValue + `${value.substring(8,10)}:${value.substring(10,12)}`
    } else {
      stringValue = `${value.substring(4,6)}月${value.substring(6,8)}日${value.substring(8,10)}:${value.substring(10,12)}`
    }
    return stringValue
  },
  isfeeded(value){

    !value&&router.pop();
  },
  copyobj(a){
    var c={};
    c=JSON.parse(JSON.stringify(a));
    return c;

  },
  tabChange(event){
    let that = this;
    if(event.detail.name==1){
      that.setData({customPlan:null,chartIndex:null},()=>{
        that.setData({customPlan:this.copyobj(this.data.customPlancopy)})
      })
    }else{
      this.setData({effectTime:-1})
      this.getChartDate();
    }
  },
  getnowSeason(){
    let day = new Date();
    let year = day.getFullYear();
    let month = day.getMonth() + 1;
    month=month<10?('0'+month):month;
    let today = day.getDate();
    today=today<10?('0'+today):today;
    const data={
      projectId:this.data.spaceDetail.projectId,
      date:`${year}${month}${today}`
    }
    getCurrentSeason(data).then(res=>{
      if(res.result=="success"){
        this.setData({bgSeasonType:res.data})
      }
    })
  },
  // 自动刷新
  autoRefresh(fn){
    if(refreshTimer){
      clearInterval(refreshTimer);
      refreshTimer = null;
    }
    let refreshTime=$.store.get("autoRefreshTime");
    refreshTimer = setTimeout(()=>{
      fn();
      this.autoRefresh(fn);
    },refreshTime)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options = JSON.parse(decodeURIComponent(JSON.stringify(options)));
    if(options.md1){
      this.getDetail(options.md1);
      this.autoRefresh(this.getDetail);
    }else{
      options.humidity&&(options.humiditylevel = this.checkLevel(options.humidity,"humidity"));
      options.co2&&(options.co2level = this.checkLevel(options.co2,"co2"));
      options.pm25&&(options.pm25level = this.checkLevel(options.pm25,"pm25"));
      options.hcho&&(options.hcholevel = this.checkLevel(options.hcho,"hcho"));
      options.isPassengerPassShow&&(options.isPassengerPassShow=JSON.parse(options.isPassengerPassShow));
      // if(typeof options.isPassengerPass==="undefined"){
      //   options.isPassengerPassShow=false;
      // }else{
      //   options.isPassengerPassShow=true;
      //   options.isPassengerPass=options.isPassengerPass?'有人':'无人'
      // }
      this.setData({spaceDetail:options},()=>{
        this.checkGuide();
        this.getnowSeason();
        let higthSpace=["311","312"];
        if(this.data.spaceDetail.roomFuncType&&higthSpace.includes(this.data.spaceDetail.roomFuncType)){
          this.setData({singleOffice:true})
        }
        this.checkPower();
        this.autoRefresh(this.getDetail);
      })
    }

  },
  async getDetail(value){
    let data;
    if(value){
      let projectId = 'Pj' + value.substring(2, 12);
      this.setData({spaceId:value,projectId:projectId});
      data= {
        criteria: {
          "spaceId": value,
          "userId": $.store.get('userId')||$.storage.get('userId'),
          "projectId": projectId
        }
      }
    }else{
      data= {
        criteria: {
          "spaceId": this.data.spaceDetail.id,
          "userId": $.store.get('userId')||$.storage.get('userId'),
          "projectId": this.data.spaceDetail.projectId
        }
      }
    }
    // wx.showLoading();
    let res = await getSpacedetail(data);
    // wx.hideLoading();
    let {content} = res;
    if(content){
      (content[0].humidity||content[0].humidity==0)&&(content[0].humiditylevel = this.checkLevel(content[0].humidity,"humidity"));
      (content[0].co2||content[0].co2==0)&&(content[0].co2level = this.checkLevel(content[0].co2,"co2"));
      (content[0].pm25||content[0].pm25==0)&&(content[0].pm25level = this.checkLevel(content[0].pm25,"pm25"));
      (content[0].hcho||content[0].hcho==0)&&(content[0].hcholevel = this.checkLevel(content[0].hcho,"hcho"));
      if(typeof content[0].isPassengerPass==="undefined"){
        content[0].isPassengerPassShow=false;
      }else{
        content[0].isPassengerPassShow=true;
        content[0].isPassengerPass=content[0].isPassengerPass?'有人':'无人'
      }
    }
    this.setData({spaceDetail:content[0]},()=>{
      this.checkGuide(value);
      this.getnowSeason();
      // if(this.data.spaceDetail.nextOpenTime){
      //   let value = this.formatTimeall(this.data.spaceDetail.nextOpenTime);
      //   this.setData({nextOpenTime:value})
      // }
      if(this.data.spaceDetail.roomFuncType&&this.data.spaceDetail.roomFuncType.startsWith("31")){
        this.setData({singleOffice:true})
      }
    });
    $.storage.get("wxqcode")&&$.storage.set("wxqcode",'');
    // 判断是否可以调节
    await this.checkPower();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    setTimeout(()=>{
      this.setData({'headerShow':true})
    },500)
  },
})