// componets/authorized-login-dialog/authorizedLoginDialog.js
const defaultAvatarUrl = "../../static/images/no-avatar.png"
const homeApi_empower = "https://aipush.aidsleep.cn";
const token_empower = "b74fd5754c5ef24cf600c39194abdaeb";
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    showDialog: {
      type: Boolean,
      value: false,
      observer(newVal, oldVal, changePath) {
        console.log(newVal, oldVal, changePath)
        const that = this;
        if (newVal) {
          // console.log("开始登录");

          // wx.login({
          //   success: res => {
          //     if (res.code) {
          //       // 发送 code 到服务器换取 session_key, openid  
          //       console.log('res.code==' + res.code);
          //       that.setData({ showLoading: false, wxCode: res.code })
          //       that.checkHasUserInfo()
          //     }
          //   }
          // });
        } else {
          console.log('that.data.wxCode==' + that.data.wxCode);
        }
      }
    }
  },

  attached() {
  },
  /**
   * 组件的初始数据
   */
  data: {
    intervalId: null,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    avatarUrl: defaultAvatarUrl,
    tempAvatarUrl: '',
    showLoading: false,
    encryptphone: "",
    phoneNumber: "",
    nickName: "",
    disableCommitBtn: true,
    hasUserInfo: false,
    wxCode: "",
    unionid: "",
    openid: "",
    session_key: "",
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 关闭
    onCloseDialog() {
      this.setData({ showDialog: false });
    },
    // 选择头像 后期需要上传
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail
      // this.setData({
      //   avatarUrl: avatarUrl,
      // })
      // wx.showToast({ title: "进来了" })
      const that = this;

      this.setData({ tempAvatarUrl: avatarUrl });
      if (avatarUrl.includes("wxfile://")) {
        that.uploadAvatar(avatarUrl);
      } else {
        // 下载头像图片
        wx.downloadFile({
          url: avatarUrl,
          success(res) {
            if (res.statusCode === 200) {
              console.log('download success');
              const tempFilePath = res.tempFilePath
              that.uploadAvatar(tempFilePath);
            } else {
              wx.showToast({ title: '上传失败' })
              // wx.showToast({ title: JSON.stringify(res) })
              // wx.showToast({ title: JSON.stringify(avatarUrl) })
            }
          }, fail: function (err) {
            wx.showToast({ title: '上传失败' })
            // wx.showToast({ title: JSON.stringify(err) })
            // wx.showToast({ title: JSON.stringify(avatarUrl) })
          }
        });
      }
      this.checkHasUserInfo();
    },

    uploadAvatar(tempFilePath) {
      wx.showLoading({ title: '上传中...' });
      const randomString = this.generateRandomString(16);
      const base64String = wx.arrayBufferToBase64(new Uint8Array([...randomString].map(c => c.charCodeAt(0))));

      wx.request({
        url: 'https://aipush.aidsleep.cn/wxuptokens',
        method: 'POST',
        data: {
          rk: base64String
        },
        success: (res) => {
          if (res.data.success) {
            this.doUpload(tempFilePath, res.data.token);
          } else {
            wx.hideLoading();
            wx.showToast({ title: '获取上传凭证失败', icon: 'none' });
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({ title: '获取上传凭证失败', icon: 'none' });
        }
      });
    },

    doUpload(tempFilePath, token) {
      wx.uploadFile({
        url: 'https://aipush.aidsleep.cn/wxups',
        filePath: tempFilePath,
        name: 'file',
        formData: {
          'token': token
        },
        success: (res) => {
          wx.hideLoading();
          const data = JSON.parse(res.data);
          if (data.success) {
            this.setData({ avatarUrl: data.url });
            wx.showToast({ title: '头像上传成功', icon: 'success' });
          } else {
            wx.showToast({ title: data.message || '头像上传失败', icon: 'none' });
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({ title: '头像上传失败', icon: 'none' });
        }
      });
    },

    generateRandomString(length) {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
      }
      return result;
    },
    // 输入昵称
    onInputNameChange(e) {
      console.log('e.detail==' + JSON.stringify(e.detail));
      const nickName = e.detail.value
      this.setData({
        nickName: nickName,
      })
      wx.setStorageSync('nickName', nickName);
      this.checkHasUserInfo();
    },
    // 输入手机号
    onInputPhoneChange(e) {
      console.log('e.detail==' + JSON.stringify(e.detail));
      const phoneNumber = e.detail.value
      this.setData({
        phoneNumber: phoneNumber,
      })
      this.checkHasUserInfo();
    },
    // 获取手机号
    onGetPhoneNumber: function (e) {
      console.log('onGetPhoneNumber=' + JSON.stringify(e));
      var that = this;
      if (e.detail.errMsg === "getPhoneNumber:ok") {
        // 发送 encryptedData, iv, 和 sessionKey 到你的后台服务器  
        wx.request({
          url: `${homeApi_empower}/wxtel`,
          method: 'POST',
          data: {
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            token: wx.getStorageSync("token") || token_empower,
          },
          success: function (res) {
            // 处理服务器返回的结果  
            console.log('手机号获取结果:', res.data);
            console.log('手机号获取结果:', res.data.encryptphone);
            console.log('手机号获取结果:', res.data.shieldphone);
            if (!res.data || !res.data.encryptphone || !res.data.shieldphone) {
              wx.showToast({
                title: '无法获取用户手机号',
                icon: 'none'
              });
              return;
            }
            console.log('e==' + JSON.stringify(e));
            console.log('e.detail==' + JSON.stringify(e.detail));
            that.setData({
              encryptphone: res.data.encryptphone,
              phoneNumber: res.data.shieldphone,
            })
            that.checkHasUserInfo();
            wx.setStorageSync('phoneNumber', res.data.shieldphone);
          }
        })
      }
    },
    checkHasUserInfo() {
      var disableCommitBtn = this.data.avatarUrl == defaultAvatarUrl || !this.data.phoneNumber || !this.data.nickName;
      this.setData({
        hasUserInfo: this.data.avatarUrl != defaultAvatarUrl && this.data.phoneNumber && this.data.nickName,
        disableCommitBtn: disableCommitBtn
      })
    },
    // 提交
    handleUserInfo: function (e) {
      if (!this.data.hasUserInfo) {
        wx.showToast({
          title: '请设置头像、昵称和手机号',
          icon: 'none'
        });
        return;
      }
      var that = this;
      if (e.detail.userInfo) {
        // 用户点击允许，获取到用户信息  
        this.setData({
          showLoading: true,
          disableCommitBtn: true,
        });

        wx.request({
          url: `${homeApi_empower}/wxlogin`,
          data: {
            token: wx.getStorageSync("token") || token_empower,
            unionid: wx.getStorageSync("unionid"),
            openid: wx.getStorageSync("openid"),
            avatarUrl: that.data.avatarUrl,
            nickname: that.data.nickName,
            encryptphone: that.data.encryptphone
          },
          method: 'POST',
          success: function (loginRes) {
            console.log('loginRes=' + JSON.stringify(loginRes));
            console.log('loginRes.data=' + JSON.stringify(loginRes.data));
            if (loginRes.data.codes && loginRes.data.codes == 'success') {
              console.log('123123123');
              console.log('loginRes.data.back.unionid=' + loginRes.data.back.unionid);
              console.log('loginRes.data.back.openid=' + loginRes.data.back.openid);
              wx.setStorageSync('unionid', loginRes.data.back.unionid);
              wx.setStorageSync('openid', loginRes.data.back.openid);
              // 获取后台授权
              that.startInterval();
              // 可以在这里提示用户进行手机号授权  
              that.setData({
                unionid: loginRes.data.back.unionid,
                openid: loginRes.data.back.openid,
              });
            } else {
              that.setData({ showLoading: false });
              wx.showToast({
                title: '后台授权失败',
                icon: 'none'
              });
            }
          },
          fail: function () {
            that.setData({ showLoading: false });
            wx.showToast({
              title: '后台授权失败',
              icon: 'none'
            });
          }
        });

      } else {
        // 用户拒绝授权  
        wx.showToast({
          title: '您拒绝了授权',
          icon: 'none'
        });

        // 可以选择在这里处理用户拒绝授权后的逻辑，如跳转到其他页面或显示提示信息  
      }
    },
    // 轮询后台信息
    startInterval: function () {
      var that = this;
      this.data.intervalId = setInterval(() => {
        console.log('后台授权中...');
        wx.request({
          url: `${homeApi_empower}/wxstatus`,
          data: {
            unionid: wx.getStorageSync('unionid'),
            openid: wx.getStorageSync('openid'),
            token: wx.getStorageSync('token') || token_empower,
          },
          method: 'POST',
          success: function (intervalRes) {
            that.setData({ showLoading: false });
            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('hasAuth', true);
              wx.setStorageSync('hotelEmpower', intervalRes.data.hotel);
              wx.setStorageSync('roomEmpower', intervalRes.data.room);
              wx.setStorageSync('userInfo', {
                hotel: intervalRes.data.hotel,
                room: intervalRes.data.room,
                unionid: that.data.unionid,
                openid: that.data.openid,
                session_key: that.data.session_key,
                nickName: that.data.nickName,
                avatarUrl: that.data.avatarUrl,
                encryptphone: that.data.encryptphone,
                phoneNumber: that.data.phoneNumber
              })
              that.setData({
                disableCommitBtn: false,
              });
              wx.showToast({
                title: '后台授权成功',
                icon: 'none'
              });

              that.clearInterval();
              that.triggerEvent('authorizationSuccessful', true);
            } else {
              that.clearInterval();
              wx.showToast({
                title: '授权失败,请先办理入住',
                icon: 'none'
              });
            }
          },
          fail: function (error) {
            that.setData({ showLoading: false });
            that.clearInterval();
            wx.showToast({
              title: '后台授权失败',
              icon: 'none'
            });
          }
        });
      }, 3000);
    },
    clearInterval: function () {
      var that = this;
      if (this.data.intervalId) {
        clearInterval(that.data.intervalId);
        that.data.intervalId = null;
      }
    },
  }
})