// index.ts
// 获取应用实例
const app = getApp();
const { login, listByDevice } = require('../../utils/api.js');
const { isCN } = require('../../utils/util.js');
let _this = null;
const interval = null;
// import routeUtil from '../../utils/route_util.js'
import routeUtil from '../../utils/route_util'
import route_constant from '../../utils/route_constant.js'

Page({
  data: {
    navBarHeight: app.globalData.navBarHeight,
    MenuButtonheight: app.globalData.MenuButtonheight,
    MenuButtonTop: app.globalData.MenuButtonTop,
    actionIndex: null,
    isShowDevicelist: false,
    luoma: ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", " Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ", "Ⅻ"],
    channelData: [],
    deviceList: [],
    deviceListIndex: null,
    showLogin: false,
    isOneLoading: true,
    uid: null,
    showDelete: false,
    isSetWake: false,
    thisDeviceMac: null,
    battery: 4, // 0≤电量<20，0格
    newVersion: false,
  },
  onShow() {
    if ((!this.data.isOneLoading)) {
      wx.getStorage({
        key: 'userInfo',
        fail(res) {
          // 取消订阅
          if (_this.data.thisDeviceMac !== null) {
            app.unsubscribe(`/${_this.data.thisDeviceMac}/user/pub_response`);
          };
          _this.setData({
            showLogin: true,
          });
        },
        success() {
          if (app.globalData.newDeviceId) {
            // 获取设备本地数据
            _this.getDeviceData();
          } else if (_this.data.deviceListIndex !== null) {
            // 更新
            _this.actionDevice(_this.data.deviceListIndex);
          }
        }
      });
    };
  },
  onLoad() {
    _this = this;
    // 版本自动更新代码
    const updateManager = wx.getUpdateManager();
    updateManager.onUpdateReady(function () {
      _this.setData({
        newVersion: true
      });
    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '已有新版本咯',
        content: '请您删除当前小程序，重新打开呦~',
        showCancel: false
      })
    })

    wx.showLoading({
      title: '加载中',
    });

    const str = setTimeout(() => {
      clearTimeout(str);
      if (_this.data.isOneLoading) {
        _this.setData({
          isOneLoading: false,
        });
      }
    }, 500);

    // 获取缓存的频道数据
    wx.getStorage({
      key: "channelData",
      success(res) {
        _this.setData({
          channelData: res.data
        })
      }
    });
    // 登录
    this.login();
  },
  
  login() {
    wx.login({
      success: res => {
        let phone = undefined;
        try {
          var value = wx.getStorageSync('userInfo')
          if (value) {
            phone = value.phone || undefined;
          };
        } catch (e) {
          // Do something when catch error
        };
        // 请求登录
        login({ code: res.code, phone }).then((res) => {

          app.globalData.userInfo = res;
          wx.setStorage({
            key: "userInfo",
            data: res
          });
          // 需要用授权登录
          if ((res.isNewUser && res.isNewUser === true) || !phone) {
            _this.setData({
              showLogin: true,
            });
            return;
          };
          // 获取设备本地数据
          this.getDeviceData();

          _this.setData({
            showLogin: false,
          });
          wx.setStorage({
            key: "token",
            data: JSON.stringify({
              id: res.userId,
              token: res.accessToken,
            }),
          });
        });
      },
    })
  },
  getDeviceData() {
    // 获取设备数据
    wx.getStorage({
      key: 'devicelist',
      success(res) {
        wx.hideLoading();
        if (res.data) {
          const resData = JSON.parse(res.data);
          _this.setData({
            deviceList: resData
          });
          // 连接mqtt
          if (app.globalData.client === null) {
            app.connect();
          } else if (app.globalData.newDeviceId) {
            _this.setData({
              actionIndex: null,
              deviceListIndex: null,
            });

            // 监听
            let topic = `/AIrSMArT_${resData[0].name.split("BLUFI_")[1]}/status/onoffline`;
            app.subscribe(topic);
            const Timeout = setTimeout(() => {
              clearTimeout(Timeout);
              _this.actionDevice(0);
            }, 1000);
          }

          // // 有新设备
          // if(app.globalData.newDeviceId) {
          //   _this.setData({
          //     actionIndex: null,
          //     deviceListIndex: null,
          //   });
          //   let topic = `/AIrSMArT_${resData[0].name.split("BLUFI_")[1]}/status/onoffline`;
          //   app.subscribe(topic);
          // }
        }
      },
      fail(e) {
        wx.hideLoading();
      }
    });
  },
  // 回调
  mqttCallback(type, option) {
    let payloads = null;
    if (option) {
      payloads = JSON.parse(option.payload);
    };
    switch (type) {
      case "connect":
        _this.connectSuccess();
        break;
      case "message_onoffline":
        _this.online(payloads);
        break;
      case "message":
        // 接收设备播放信息
        if (payloads.type === "get_position" && payloads.other) {
          let actionIndex = null;

          _this.data.channelData.map((v, index) => {
            if (v.channelNum === payloads.other.channel) {
              actionIndex = index;
            }
          });
          _this.setData({
            actionIndex,
          });
        } else if (payloads.type === "play" || payloads.type === "play_state") {

          if (_this.data.deviceListIndex === null) {
            return;
          }
          // 接收设备当前播放状态
          const obj = {
            DstDeviceName: _this.getThisDeviceID()
          }
          app.PubMsg({ type: "get_position", ...obj });
        } else if (payloads.type === "get_dev_info") {
          // 接收设备当前信息
          this.getchannelData(payloads.other.ProdModel);
          // 电量
          _this.setData({
            battery: _this._battery(payloads.other.Power),
          })
          // 当前设备木有设置定时
          _this.setData({
            isSetWake: false,
          });
          payloads.other.alarm.map((v) => {
            if (v.enable === "1") {
              _this.setData({
                isSetWake: true
              });
            }
          });
          // 更新信息
          _this.data.deviceList.map((v, index) => {
            if (payloads.SrcDeviceName && payloads.SrcDeviceName.indexOf(v.name.split("BLUFI_")[1]) !== -1) {
              _this.data.deviceList[index].ProdModel = payloads.other.ProdModel;
              _this.data.deviceList[index].devName = payloads.other.devName;
            }
          });
          // 更新缓存
          wx.setStorage({
            key: "devicelist",
            data: JSON.stringify(_this.data.deviceList),
            success() {
              _this.setData({
                deviceList: _this.data.deviceList
              })
            }
          });
        } else if (payloads.type === "battery" && payloads.other) {
          _this.setData({
            battery: _this._battery(payloads.other.battery),
          })
        }
        break;
      default:

    }
  },
  // 格式化电量
  _battery(battery) {
    let _battery = 0;
    if (battery < 20) {
      _battery = 0
    } else if (20 <= battery && battery < 40) {
      _battery = 1
    } else if (40 <= battery && battery < 60) {
      _battery = 2
    } else if (60 <= battery && battery < 80) {
      _battery = 3
    } else if (80 <= battery && battery <= 100) {
      _battery = 4
    } else if (battery > 100) {
      _battery = 5
    };
    return _battery
  },
  connectSuccess() {
    // 订阅设备在线信息
    _this.subscribeDevicesStatus();
  },
  online(payloads) {
    // 设置在线状态
    _this.data.deviceList.map((v, index) => {
      if (payloads.uuid && payloads.uuid.indexOf(v.name.split("BLUFI_")[1]) !== -1) {
        _this.data.deviceList[index].state = payloads.state;
      }
    });
    _this.setData({
      deviceList: _this.data.deviceList,
    });
    // 更新缓存
    wx.setStorage({
      key: "devicelist",
      data: JSON.stringify(_this.data.deviceList)
    });
    // 如没有选中，选中最新的
    (() => {
      if (_this.data.deviceListIndex === null) {
        let itue = false;
        _this.data.deviceList.map((v, index) => {
          if (v.state === "online" && !itue) {
            itue = true;
            _this.actionDevice(index);
          }
        });
      }
      //  else {
      //   _this.actionDevice(_this.data.deviceListIndex);
      // };

    })();

    // 当前播放设备离线
    if (_this.data.deviceListIndex !== null && _this.data.deviceList[_this.data.deviceListIndex].state !== "online") {
      _this.setData({
        actionIndex: null,
        deviceListIndex: null,
      });
    };
  },
  // 订阅设备在线状态
  subscribeDevicesStatus() {
    this.data.deviceList.forEach((value) => {
      let topic = `/AIrSMArT_${value.name.split("BLUFI_")[1]}/status/onoffline`;
      app.subscribe(topic);
    })
  },

  // 订阅消息
  subscribeCurrDevice() {
    if (!(app.globalData.client && app.globalData.client.connected)) {
      console.log("未连接MQTT服务器");
      const str = setInterval(() => {
        clearInterval(str);
        _this.subscribeCurrDevice();
      }, 500);
      return;
    };
    if (this.data.deviceList.length === 0 || this.data.deviceListIndex === null) {
      return
    };
    let topic = `/AIrSMArT_${this.data.deviceList[this.data.deviceListIndex].name.split("BLUFI_")[1]}/user/pub_response`;
    app.subscribe(topic);
    const obj = {
      DstDeviceName: _this.getThisDeviceID()
    };
    app.PubMsg({ type: "get_dev_info", ...obj });
  },

  isShowDevicelistFun() {
    this.setData({
      isShowDevicelist: !_this.data.isShowDevicelist
    })
  },
  actionMusic(e) {
    if (e.currentTarget.dataset.index === this.data.actionIndex) {
      return;
    };
    if (this.data.deviceListIndex === null) {
      wx.showToast({
        title: '请选择设备',
        icon: "none"
      })
      return;
    };
    this.setData({
      actionIndex: e.currentTarget.dataset.index
    });
    const other = {
      "url": "",
      "media_data": "",
      "user_id": `${app.globalData.userInfo.deviceUid}`,
      "timestamp": `${Math.round(new Date() / 1000)}`,
      "channel_id": `${this.data.channelData[e.currentTarget.dataset.index].channelNum}`,
      "order": "",
      "resource_from": "",
      "songAlbumID": "",
      "version": 3,
      "is_debug": app.globalData.is_debug
    };
    app.PubMsg({
      type: "play",
      DstDeviceName: _this.getThisDeviceID(),
      other
    });
  },
  actionDeviceIndex(e) {
    if (e.currentTarget.dataset.index === this.data.deviceListIndex) {
      return
    };
    this.actionDevice(e.currentTarget.dataset.index)
  },

  actionDevice(index) {
    const device = this.data.deviceList[index];
    if (device.state !== "online") {
      return;
    };
    // 取消订阅
    if (this.data.thisDeviceMac !== null) {
      app.unsubscribe(`/${this.data.thisDeviceMac}/user/pub_response`);
    };

    this.setData({
      deviceListIndex: index,
      thisDeviceMac: `AIrSMArT_${this.data.deviceList[index].name.split("BLUFI_")[1]}`
    });

    // app.PubMsg({
    //   type: "get_dev_info",
    //   DstDeviceName: _this.getThisDeviceID()
    // });
    this.subscribeCurrDevice();
  },
  getThisDeviceID() {
    return `AIrSMArT_${this.data.deviceList[this.data.deviceListIndex].name.split("BLUFI_")[1]}`
  },
  goLogin() {
    wx.navigateTo({
      url: './../login/login',
    });
  },
  goDeviceConnect() {
    routeUtil.jump(route_constant.deviceList)

    return;
    wx.navigateTo({
      url: './../deviceConnect0/deviceConnect0',
    });
    this.setData({
      isShowDevicelist: false
    })
  },
  getchannelData(clientType) {
    let _this = this;
    if (this.data.deviceListIndex === null) {
      return;
    };
    listByDevice({ clientType }).then((res) => {
      _this.setData({
        channelData: res
      });
      // 接收设备当前播放状态
      const obj = {
        DstDeviceName: _this.getThisDeviceID()
      }
      app.PubMsg({ type: "get_position", ...obj });
      wx.setStorage({
        key: "channelData",
        data: res
      });

      // 有新设备
      if (app.globalData.newDeviceId) {
        app.globalData.newDeviceId = null;
        return;
        // 去掉此功能，先留着吧
        // const other= {
        //   "url": "",
        //   "media_data": "",
        //   "user_id": `${app.globalData.userInfo.deviceUid}`,
        //   "timestamp": `${Math.round(new Date() / 1000)}`,
        //   "channel_id": `${res[1].channelNum}`,
        //   "order": "",
        //   "resource_from": "",
        //   "songAlbumID":"",
        //   "version":3,
        //   "is_debug": app.globalData.is_debug
        // };
        // app.PubMsg({
        //   type: "play",
        //   DstDeviceName: _this.getThisDeviceID(),
        //   other
        // });
      }

    })
  },
  showDelete() {
    // wx.navigateTo({
    //   url: './../deviceRoter3/deviceRoter3',
    // })
    this.setData({
      showDelete: !this.data.showDelete
    });
  },
  deleteDevice(e) {

    const id = this.data.deviceList[e.currentTarget.dataset.index].deviceId;
    let name = _this.data.deviceListIndex !== null ? this.data.deviceList[_this.data.deviceListIndex].name : null;
    const deviceList = this.data.deviceList.filter((v, i) => {
      return id !== v.deviceId
    });
    // 取消订阅
    app.unsubscribe(`/AIrSMArT_${_this.data.deviceList[e.currentTarget.dataset.index].name.split("BLUFI_")[1]}/user/pub_response`);

    wx.setStorage({
      key: "devicelist",
      data: JSON.stringify(deviceList),
      success() {

        _this.setData({
          deviceList,
          thisDeviceMac: null
        });

        // 当前没有设备
        if (deviceList.length === 0) {
          _this.setData({
            showDelete: false,
            actionIndex: null,
            deviceListIndex: null,
            isShowDevicelist: false,
          });
        }

        if (_this.data.deviceListIndex === null) {
          return
        };
        if (e.currentTarget.dataset.index === _this.data.deviceListIndex) {
          let index_ = null;
          deviceList.map((v, index) => {
            if (v.state === "online" && index_ === null) {
              index_ = index;
            }
          });
          if (index_ !== null) {
            _this.actionDevice(index_);
          } else {
            _this.setData({
              actionIndex: null,
              deviceListIndex: null,
            });
          };
        } else {
          deviceList.map((v, index) => {
            if (v.name === name) {
              _this.setData({
                deviceListIndex: index,
              });
            }
          });
        }
      }
    })

  },
  goWake() {
    if (this.data.deviceListIndex === null) {
      return;
    };
    wx.navigateTo({
      url: './../deviceWake/deviceWake?deviceId=' + this.data.deviceList[this.data.deviceListIndex].deviceId + "&clientType=" + this.data.deviceList[this.data.deviceListIndex].ProdModel,
    });

  },
  goChnnel() {
    wx.setStorage({
      key: "channelDeta",
      data: this.data.channelData[this.data.actionIndex],
      success() {
        wx.navigateTo({
          url: './../channelDetails/channelDetails'
        })
      }
    })

  },
  updata() {
    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
    wx.getUpdateManager().applyUpdate()
  },
  updataClone() {
    this.setData({
      newVersion: false
    })
  },
  onUnload() {
    if (app.globalData.client === null) {
      return;
    };
    app.globalData.client.end(true);
    app.globalData.client.end(true);
    app.globalData.client = null;
  },
})
