// pages/deviceWake/deviceWake.js
const app = getApp();
const { formatNumber }=require('./../../utils/util.js');
const { deviceWakedetail }=require('./../../utils/api.js');
let _this = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '定时设置', //导航栏 中间的标题
    },
    switch1Checked: false,
    alarm_id_0_time: "00:00:00",
    switch2Checked: false,
    deviceMac: null,
    devicerStatus: false,  // false 已断开连接
    alarm_id_0: {}, // 休眠
    alarm_id_1: {}, // 唤醒
    timeindex: 1,
    timeArray: [
      {
        id: 600,
        name: '10分钟'
      },
      {
        id: 1800,
        name: '30分钟'
      },
      {
        id: 3600,
        name: '60分钟'
      },
      {
        id: 5400,
        name: '90分钟'
      }
    ],
    clientType: "",
    time0: '00:00:00',
    time: '07:00:00',
    repeat: "",
    repeat0: "",
    week: ["周日","周一","周二","周三","周四","周五","周六"],
    week_actives: [],
    isOne: true,
    wakeName: "",
    toastData: {
      titlePicUrl: "./../../../img/gt.png",
      titlePicUrlWidth: 140,
      title: ["温馨提醒"],
      info: ["当前设备电量低"],
      isShowTwoBut: true,
      twoButText: "好的",
      footTop: 10,
    },
    twoButCallback: ()=> {},
    toast_visible: false,
    // 后续新加需求
    deviceOther: null,
    updataDeviceInfo: false,
    repeatIndex: 0,
  },
  onShow(options) {
    app.PubMsg({type: "get_dev_info", DstDeviceName: _this.data.deviceMac});
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    _this = this;
    deviceWakedetail({
      clientType: options.clientType,
      deviceMac: `AIrSMArT_${options.deviceId.split("BLUFI_")[1]}`,
    }).then((res)=> {
      if(res && res.length > 0) {
        this.setData({
          wakeName: res[0].audioName || null
        });
      }
    })
    this.data.clientType = options.clientType
    this.data.deviceMac = `AIrSMArT_${options.deviceId.split("BLUFI_")[1]}`;
    // this.data.deviceMac =  `AIrSMArT_${"BLUFI_7cdfa1fd3cfc".split("BLUFI_")[1]}`;
    app.PubMsg({type: "get_dev_info", DstDeviceName: this.data.deviceMac});

    // 赋值按钮回调
    this.setData({
      twoButCallback: ()=> {
        _this.setData({
          toast_visible: false
        })
      }
    })

  },
  mqttCallback(type, option) {
    let payloads = null;
    if(option) {
      payloads = JSON.parse(option.payload);
    };
    console.log(payloads)
    switch(type) {
      case "message_onoffline":
        if(payloads.state !== "online") {
          wx.showToast({
            title: '设备已断开连接',
            icon: 'none',
            duration: 2000
          });
          _this.setData({
            devicerStatus: false,
          })
        } else {
          _this.setData({
            devicerStatus: true,
          })
        }
        break;
      case"message":
        // 设备信息
        if(payloads.type === "get_dev_info") {
          _this.setData({
            deviceOther: payloads.other,
            updataDeviceInfo: true,
          });
          if(payloads.other.alarm) {
            payloads.other.alarm.map((v)=> {
              if(v.alarm_id === "0") {
                v.action = "update";
                // 休眠
                _this.setData({
                  alarm_id_0: v
                });
                
                // 定时时间
                if(v.on_off_timestamp !== "")  {
                  _this.setData({
                    alarm_id_0_time: v.on_off_timestamp
                  })
                }
                

                // 是否启用
                if(v.enable === "1")  {
                  _this.setData({
                    switch1Checked: true
                  })
                } else {
                  _this.setData({
                    switch1Checked: false
                  })
                }

                // 重复
                if(v.week_actives) {
                  _this.setData({
                    repeat0: _this.repeatText(v.week_actives),
                  })
                }

              } else if(v.alarm_id === "1") {
                // 唤醒
                _this.setData({
                  alarm_id_1: v
                });
                // 定时时间
                if(v.on_off_timestamp !== "")  {
                  _this.setData({
                    time: v.on_off_timestamp
                  })
                }
                // 是否启用
                if(v.enable === "1")  {
                  _this.setData({
                    switch2Checked: true
                  })
                } else {
                  _this.setData({
                    switch2Checked: false
                  })
                }
                // 重复
                if(v.week_actives) {
                  _this.setData({
                    repeat: _this.repeatText(v.week_actives),
                  })
                }
              }
            })
          }
        } else if(payloads.type === "alert_set") {
          if(payloads.code === 200) {
            app.PubMsg({type: "get_dev_info", DstDeviceName: _this.data.deviceMac});
          } else {
            wx.showModal({
              title: '保存失败',
              content: '请保持设备网络通畅并检查是否已连接电源？',
              success (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }
        }
      default:
    }
  },

  // 休眠-选择时间
  switch1Change(e) {
    let other = this.data.alarm_id_0;
    if(e.detail.value) {
      _this.setData({
        switch1Checked: e.detail.value
      });
      const thisTime = Math.round(new Date() / 1000);
      other = this.setOther(other, 1);
      other.on_off_timestamp = _this.data.alarm_id_0_time;

      // 有重复
      if(other.week_actives.filter((v)=> v === 1).length > 0) {
        // other.week_actives = [0,1,1,1,1,1,0],
        other.weekly_repeat = "1";
      } else {
        other.weekly_repeat = "0";
      };
      // 如果跨天了
      if(!this.compareDate(_this.data.alarm_id_0_time, this.formatTime(thisTime, "h:m:s"))) {
        const date = new Date((_this.formatTime(thisTime, "Y-M-D") + " 00:00:00").replace(/-/g,'/'));
        other.current_timestamp = this.formatTime(date.getTime() / 1000 + 86400, "Y-M-D h:m:s");
      };
      app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other});
    } else {
      _this.setData({
        switch1Checked: e.detail.value
      });
      other = this.setOther(other, 0);
      app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other});
    }
  },
  switch2Change(e) {
    _this.data.updataDeviceInfo = false;
    let other = _this.data.alarm_id_1;
    if(e.detail.value) {
      if(_this.data.deviceOther && _this.data.deviceOther.Power < 20) {
        _this.setData({
          toast_visible: true,
        });
      };
      app.PubMsg({type: "get_dev_info", DstDeviceName: _this.data.deviceMac});
      // 循环查询
      const Interval = setInterval(()=> {
        if(_this.data.updataDeviceInfo) {
          clearInterval(Interval);
          other.on_off_timestamp = _this.data.time;
          other = this.setOther(other, 1);
          if(other.week_actives.filter((v)=> v === 1).length > 0) {
            // other.week_actives = [0,1,1,1,1,1,0],
            other.weekly_repeat = "1";
          } else {
            other.weekly_repeat = "0";
          };
          app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other});
          // 需打开休眠
          if(_this.data.alarm_id_0.enable === "0") {

            const thisTime = Math.round(new Date() / 1000);
            const alarm_id_0 = this.setOther(_this.data.alarm_id_0, 1);
            alarm_id_0.on_off_timestamp = _this.data.alarm_id_0_time;
      
            // 有重复
            if(alarm_id_0.week_actives.filter((v)=> v === 1).length > 0) {
              alarm_id_0.weekly_repeat = "1";
            } else {
              alarm_id_0.weekly_repeat = "0";
            };;
            // 如果跨天了
            if(!this.compareDate(_this.data.alarm_id_0_time, this.formatTime(thisTime, "h:m:s"))) {
              const date = new Date((_this.formatTime(thisTime, "Y-M-D") + " 00:00:00").replace(/-/g,'/'));
              alarm_id_0.current_timestamp = this.formatTime(date.getTime() / 1000 + 86400, "Y-M-D h:m:s");
            };
            app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other: alarm_id_0});
          }

        }
      }, 500);
    } else {
      other = this.setOther(other, 0);
      app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other});
    }
  },
  // bindPickerChange(e) {
  //   let other = this.data.alarm_id_0;
  //   const thisTime = Math.round(new Date() / 1000);
  //   other = this.setOther(other, 1);
  //   other.on_off_timestamp = this.formatTime(thisTime + this.data.timeArray[e.detail.value].id, "h:m:s");
  //   // 如果跨天了
  //   if(parseInt(this.formatTime(thisTime + this.data.timeArray[e.detail.value].id, "D")) > parseInt(this.formatTime(thisTime, "D"))) {
  //     const date = new Date(_this.formatTime(thisTime, "Y-M-D") + " 00:00:00");
  //     other.current_timestamp = this.formatTime(date.getTime() / 1000 + 86400, "Y-M-D h:m:s");
  //   };
  //   app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other});
  // },
  bindTimeChange0: function(e) {
    this.setData({
      alarm_id_0_time: e.detail.value + ":00"
    });
    let other = this.data.alarm_id_0;
    other.on_off_timestamp = e.detail.value + ":00";
    other = this.setOther(other, 1);
    // 有重复
    if(other.week_actives.filter((v)=> v === 1).length > 0) {
      // other.week_actives = [0,1,1,1,1,1,0],
      other.weekly_repeat = "1";
    } else {
      other.weekly_repeat = "0";
    };
    // 如果跨天了
    const thisTime = Math.round(new Date() / 1000);
    if(!this.compareDate(_this.data.alarm_id_0_time, this.formatTime(thisTime, "h:m:s"))) {
      const date = new Date((_this.formatTime(thisTime, "Y-M-D") + " 00:00:00").replace(/-/g,'/'));
      other.current_timestamp = this.formatTime(date.getTime() / 1000 + 86400, "Y-M-D h:m:s");
    };
    app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other});
  },
  bindTimeChange: function(e) {
    this.setData({
      time: e.detail.value + ":00"
    });
    let other = this.data.alarm_id_1;
    other.on_off_timestamp = e.detail.value + ":00";
    other = this.setOther(other, 1);
    app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other});
  },
  setRepeat(arr) {
    let other = this.data.repeatIndex === "0" ? _this.data.alarm_id_0 : _this.data.alarm_id_1;
    other = this.setOther(other, 1);
    other.week_actives = arr;
    other.weekly_repeat = arr.filter((v)=> v === 1).length > 0 ? "1" : "0";
    // 倒计时
    if(this.data.repeatIndex === "0") {
      // 如果跨天了
      const thisTime = Math.round(new Date() / 1000);
      if(!this.compareDate(_this.data.alarm_id_0_time, this.formatTime(thisTime, "h:m:s"))) {
        const date = new Date((_this.formatTime(thisTime, "Y-M-D") + " 00:00:00").replace(/-/g,'/'));
        other.current_timestamp = this.formatTime(date.getTime() / 1000 + 86400, "Y-M-D h:m:s");
      };
    }
    app.PubMsg({type: "alert_set", DstDeviceName: _this.data.deviceMac, other});
  },
  goWakeList() {
    wx.navigateTo({
      url: './../wakeList/wakeList?clientType=' + this.data.clientType + "&deviceMac=" + this.data.deviceMac,
    })
  },
  gorepeat(e) {
    this.data.repeatIndex = e.currentTarget.dataset.index;
    this.data.week_actives = e.currentTarget.dataset.index === "0" ? _this.data.alarm_id_0.week_actives : _this.data.alarm_id_1.week_actives;
    wx.navigateTo({
      url: './../repeat/repeat?week_actives=' + this.data.week_actives
    })
  },
  setdeviceWakedetail() {
    deviceWakedetail({
      clientType: this.data.clientType,
      deviceMac: this.data.deviceMac,
    }).then((res)=> {
      this.setData({
        wakeName: res[0].audioName
      })
    })
  },
  /** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
*/
 formatTime(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
},
  // type: 0 关闭  1 开启
  setOther(other, type) {
    if(type === 0) {
      other.enable = "0";
      other.alarm_name = "close";
      other.operation = "off";
    } else if(type === 1){
      other.enable = "1";
      other.alarm_name = "open";
      other.operation = "on";
    }
    const thisTime = Math.round(new Date() / 1000);
    other.current_timestamp = this.formatTime(thisTime, "Y-M-D h:m:s");
    other.action = "update",
    other.song_uri = "-1";
    other.version = 3;
    other.is_debug = app.globalData.is_debug
    return other
  },
  // 判断当天时间前后
  compareDate(t1, t2) {
    var date = new Date();
    var a = t1.split(":");
    var b = t2.split(":");
    return date.setHours(a[0], a[1]) > date.setHours(b[0], b[1]);
  },
  repeatText(arr) {

    let text = "";
    if(arr.toString() === [0, 1, 1, 1, 1, 1, 0].toString()) {
      text = "工作日";
    } else if(arr.toString() === [1, 0, 0, 0, 0, 0, 1].toString()) {
      text = "周末";
    } else {
      arr.map((v, index)=> {
        if(v === 1) {
          if(text === "") {
            text = text + _this.data.week[index]
          } else {
            text = text + "、" + _this.data.week[index];
          }
        }
      });
      if(text === "") {
        text = "不重复";
      };
    }
    return text.length < 20 ? text : "每日";
  }

})