// pages/mine/mine.js
const defaultAvatarUrl = "../../static/images/no-login.png"
const homeApi_empower = "https://aipush.aidsleep.cn";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showAuthorizedDialog: false,
    showTipsA: false,
    showTipsB: false,
    hasAuth: false,
    avatarUrl: defaultAvatarUrl,
    nickName: "用户登录",
    phoneNumber: "",
    latitude: null,
    longitude: null,
    menuCardList: [{
      icon: "../../static/index/icon/ic_fjkz.png",
      bgIcon: "../../static/index/bg/bg_fjkz.png",
      title: "房间控制",
      type: "navigate",
      color: "#3C84D9",
      bgColor: "#EEF4FF",
      url: "/subpages/main/main"
    }, {
      icon: "../../static/index/icon/ic_sm.png",
      bgIcon: "../../static/index/bg/bg_sm.png",
      title: "扫码",
      type: "navigate",
      color: "#10B09C",
      bgColor: "#E6FFFC",
      url: "/subpages/scan/scan"
    }, {
      icon: "../../static/index/icon/ic_jrsmbg.png",
      bgIcon: "../../static/index/bg/bg_jrsmbg.png",
      title: "最新睡眠报告",
      type: "navigate",
      color: "#8658B9",
      bgColor: "#F6F3FF",
      url: "/subpages/data/data"
    }, {
      icon: "../../static/index/icon/ic_lssmbg.png",
      bgIcon: "../../static/index/bg/bg_lssmbg.png",
      title: "历史睡眠报告",
      type: "navigate",
      color: "#BB6268",
      bgColor: "#FFF6F7",
      url: "/subpages/sleepReport/sleepReport"
    }, {
      icon: "../../static/index/icon/ic_wdcd.png",
      bgIcon: "../../static/index/bg/bg_wdcd.png",
      title: "我的床垫",
      type: "navigate",
      color: "#317A9B",
      bgColor: "#E6FFFC",
      url: "/subpages/myMattress/myMattress"
    }, {
      icon: "../../static/index/icon/ic_zxsc.png",
      bgIcon: "../../static/index/bg/bg_zxsc.png",
      title: "在线商城",
      type: "miniProgram",
      color: "#C2714B",
      bgColor: "#FFF8F4",
      appId: "wx63f79b3d61ba632b" || "gh_78da4ac5d0cc",
      url: "pages/home/dashboard/index"
    }],
    menuList: [{
      icon: "../../static/mine/dcwj.png",
      title: "健康检测",
      type: "navigate",
      url: "/subpages/testSAS/testSAS"
    }, {
      icon: "../../static/mine/zxkf.png",
      title: "在线客服",
      type: "contact",
      url: ""
    }, {
      icon: "../../static/mine/bzzx.png",
      title: "帮助中心",
      type: "navigate",
      url: "/subpages/helpList/helpList"
    }, {
      icon: "../../static/mine/gywm.png",
      title: "关于我们",
      type: "navigate",
      url: ""
    }]

  },
  getLocation() {
    const that = this;
    var hasAuth = wx.getStorageSync("hasAuth");
    if (!hasAuth) {
      return
    }
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation']) {
          // 用户已经授权  
          wx.getLocation({
            type: 'gcj02', // 返回可以用于wx.openLocation的经纬度  
            success(locationRes) {
              that.setData({
                latitude: locationRes.latitude,
                longitude: locationRes.longitude,
              });
              console.log('纬度:', locationRes.latitude);
              console.log('经度:', locationRes.longitude);
              that.savehotelnew();
            },
            fail(err) {
              that.setData({
                latitude: null,
                longitude: null,
                error: err.message
              });
              console.error('获取位置失败:', err.message);
            }
          });
        } else {
          // 用户未授权  
          // wx.authorize({
          //   scope: 'scope.userLocation',
          //   success() {
          //     // 用户同意授权后再次获取位置  
          //     that.savehotelnew();
          //   },
          //   fail() {
          //     // 用户拒绝授权  
          //     that.setData({
          //       latitude: null,
          //       longitude: null,
          //       error: '用户拒绝授权获取地理位置'
          //     });
          //     console.error('用户拒绝授权获取地理位置');
          //   }
          // });
        }
      }
    });
  },
  savehotelnew() {
    const that = this;
    console.log({
      token: "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3" || wx.getStorageSync('token'),
      unionid: wx.getStorageSync('unionid'),
      longandlat: that.data.longitude + "|" + that.data.latitude
    });
    
    wx.request({
      url: 'https://aipush.aidsleep.cn/savehotelnew',
      method: 'POST',
      data: {
        token: "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3" || wx.getStorageSync('token'),
        unionid: wx.getStorageSync('unionid'),
        longandlat: that.data.longitude + "|" + that.data.latitude
      },
      success: (res) => {

      },
      fail: () => {
      }
    });
  },
  onCloseTipsDialog() {
    this.setData({
      showTipsA: false,
      showTipsB: false
    })
  },
  onMenuClick(e) {
    console.log(e.currentTarget.dataset);
    const { index } = e.currentTarget.dataset;
    var hasAuth = wx.getStorageSync("hasAuth");
    switch (index - 0) {
      case 0:
        // need Login
        if (hasAuth) {
          this.toPage(index);
        } else {
          this.showDialog();
        }
        break;
      default:
        this.toPage(index);
        break;
    }

  },
  toPage(index) {
    const type = this.data.menuList[index].type;
    const url = this.data.menuList[index].url;
    if (!url) {
      return
    }
    if (type == 'switchTab') {
      wx.switchTab({
        url: url
      })
    } else if (type == 'navigate') {
      wx.navigateTo({
        url: url
      })
    } else if (type == 'miniProgram') {
      //develop开发版；trial体验版；release正式版
      const appId = this.data.menuCardList[index].appId;
      wx.navigateToMiniProgram({
        appId: appId,
        path: url,
        extraData: {
        },
        envVersion: 'develop',
        success(res) {
          // 打开成功  
        }
      })
    }
  },
  onMenuCardClick(e) {
    console.log(e.currentTarget.dataset);
    const { index } = e.currentTarget.dataset;
    var hasAuth = wx.getStorageSync("hasAuth");
    switch (index - 0) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
        // need Login
        if (hasAuth) {
          if (index == 0) {
            var hasHotelAuth = wx.getStorageSync("hasHotelAuth");
            if (!hasHotelAuth) {
              this.setData({
                showTipsB: true
              })
              return
            }
          }
          if (index == 2) {
            var hasReportAuth = wx.getStorageSync("hasReportAuth");
            var unionid = wx.getStorageSync("unionid");
            if (!unionid) {
              this.setData({
                showTipsA: true
              })
              return
            }
            if (!hasReportAuth) {
              wx.showModal({
                title: '提示',
                content: '没有睡眠报告',
                showCancel: false
              });
              return
            }
          }
          this.toCardPage(index);
        } else {
          this.showDialog();
        }
        break;
      default:
        this.toCardPage(index);
        break;
    }
  },
  toCardPage(index) {
    const type = this.data.menuCardList[index].type;
    const url = this.data.menuCardList[index].url;
    if (!url) {
      return
    }
    if (type == 'switchTab') {
      wx.switchTab({
        url: url
      })
    } else if (type == 'navigate') {
      wx.navigateTo({
        url: url
      })
    } else if (type == 'miniProgram') {
      //develop开发版；trial体验版；release正式版
      const appId = this.data.menuCardList[index].appId;
      wx.navigateToMiniProgram({
        appId: appId,
        path: url,
        extraData: {
        },
        envVersion: 'develop',
        success(res) {
          // 打开成功  
        }
      })
    }
  },
  toSubscriptions() {
    const tmplIds = '0EiOd-aA8Yp9mArcp97948X94cqEloNvIBZ9vyWVgWM';
    // 这里是获取下发权限地方，根据官方文档，可以根据  wx.getSetting() 的 withSubscriptions   这个参数获取用户是否打开订阅消息总开关。后面我们需要获取用户是否同意总是同意消息推送。所以这里要给它设置为true 。
    wx.getSetting({
      withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
      success: function (res) {

        // 调起授权界面弹窗
        if (res.subscriptionsSetting.mainSwitch) {  // 用户打开了订阅消息总开关
          if (res.subscriptionsSetting.itemSettings != null) {   // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
            let moIdState = res.subscriptionsSetting.itemSettings[tmplIds];  // 用户同意的消息模板id
            if (moIdState === 'accept') {
              console.log('接受了消息推送');

            } else if (moIdState === 'reject') {
              console.log("拒绝消息推送");

            } else if (moIdState === 'ban') {
              console.log("已被后台封禁");

            }
          } else {
            // 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
            wx.showModal({
              title: '提示',
              content: '请授权开通服务通知',
              showCancel: true,
              success: function (ress) {
                if (ress.confirm) {
                  wx.requestSubscribeMessage({   // 调起消息订阅界面
                    tmplIds: ['0EiOd-aA8Yp9mArcp97948X94cqEloNvIBZ9vyWVgWM', 'fgohMD69bcSeeXiKJm-3FTcrGz1SD6M6uUb8lvzbi4g'],
                    success(res) {
                      console.log('订阅消息 成功 ');
                      console.log(res);
                    },
                    fail(er) {
                      console.log("订阅消息 失败 ");
                      console.log(er);
                    }
                  })

                }
              }
            })
          }

        } else {
          console.log('订阅消息未开启')
        }
      },
      fail: function (error) {
        console.log(error);
      },
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.hideTabBar()
    this.toSubscriptions();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    wx.hideTabBar()
    this.getLocation();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    wx.hideTabBar()
    this.checkAuth()
  },
  showDialog() {
    var hasAuth = wx.getStorageSync("hasAuth");
    if (hasAuth) {
      return
    }
    this.setData({
      showAuthorizedDialog: true
    })
  },
  checkAuth() {
    var hasAuth = wx.getStorageSync("hasAuth");
    this.setData({
      hasAuth: hasAuth
    })
    if (hasAuth) {
      var userInfo = wx.getStorageSync("userInfo");
      this.setData({
        nickName: userInfo.nickName || "用户登录",
        avatarUrl: userInfo.avatarUrl || defaultAvatarUrl,
        phoneNumber: userInfo.phoneNumber || ""
      })
      // 判断扫码控制权限
      wx.request({
        url: `${homeApi_empower}/wxstatus`,
        data: {
          unionid: wx.getStorageSync('unionid'),
          openid: wx.getStorageSync('openid'),
          token: wx.getStorageSync('token'),
        },
        method: 'POST',
        success: function (intervalRes) {
          console.log('intervalRes=' + JSON.stringify(intervalRes));
          console.log('intervalRes.data=' + JSON.stringify(intervalRes.data));
          //empower.js? [sm]:152 intervalRes.data={"st":"success","status":"0"}
          if (intervalRes.data && intervalRes.data.st && intervalRes.data.status && intervalRes.data.st == 'success' && intervalRes.data.status == '1') {
            wx.setStorageSync('hasHotelAuth', true);
            wx.setStorageSync('hotelEmpower', intervalRes.data.hotel);
            wx.setStorageSync('roomEmpower', intervalRes.data.room);
            wx.setStorageSync('hname', intervalRes.data.hname);
            wx.setStorageSync('rname', intervalRes.data.rname);
          } else {
            wx.setStorageSync('hasHotelAuth', false);
          }
        },
        fail: function (error) {

        }
      });


    }
    return hasAuth;
  },
  authorizationSuccessful() {
    console.log("授权成功");
    this.setData({ showAuthorizedDialog: false })
    this.checkAuth();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})