const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    huHaoList: [],
    showUnbindModal: false,
    unbindId: null,
    showDefaultModal: false,
    defaultId: null
  },

  onLoad: function (options) {
    this.getAccountList();
  },



  // 点击解除绑定按钮
  unbindHuHao: function (e) {
    const id = e.currentTarget.dataset.id;

    this.setData({
      showUnbindModal: true,
      unbindId: id
    });
  },

  // 取消解绑
  cancelUnbind: function () {
    this.setData({
      showUnbindModal: false,
      unbindId: null
    });
  },

  // 确认解绑
  confirmUnbind: function () {
    const id = this.data.unbindId;
    this.accountUnbind(id);
  },
  // 解绑方法
  accountUnbind: function (id) {
    const unbindInfo = this.data.huHaoList.filter(item => {
      return item.id === id;
    })[0];
    const otherInfo = this.data.huHaoList.filter(item => {
      return item.id != id;
    });
    const _this = this;
    wx.showLoading({
      title: '获取中...',
      mask: true,
    });
    wx.request({
      url: app.globalData.interfaceUrls.accountUnbind,
      method: 'POST',
      data: {
        account: unbindInfo.usernumber,
        deKey: unbindInfo.dsKey,
        refresh: false,
        otherDsKeys: []
      },
      header: {
        'content-type': 'application/json', // 默认值
        'token': app.globalData.userWxInfo.token,
      },
      success(res) {
        wx.hideLoading();
        let apiReturnData = res.data;
        if (apiReturnData.code == '200') {
          wx.showToast({
            title: '解绑成功',
            icon: 'success',
            duration: 2000
          });
          _this.setData({
            huHaoList: otherInfo,
            showUnbindModal: false,
            currentHuHao: null
          });
          
          // 检查是否解绑的是当前正在使用的户号
          const isCurrentAccount = unbindInfo.usernumber === app.globalData.currentAccountInfo.usernumber;
          
          if (otherInfo.length == 0) {
            app.globalData.currentAccountInfo = [];
            app.globalData.userWxInfo.currentDsKey = "";
            wx.redirectTo({
              url: '/pages/FirstBangDing/FirstBangDing',
            })
          } else {
            // 添加刷新列表数据
            _this.getAccountList();
            
            // 如果解绑的是当前户号，需要切换到另一个户号
            if (isCurrentAccount) {
              app.globalData.currentAccountInfo = otherInfo[0];
              app.globalData.userWxInfo.currentDsKey = otherInfo[0].dsKey;
              app.globalData.userWxInfo.username = otherInfo[0].username;
              app.globalData.userWxInfo.usernumber = otherInfo[0].usernumber;
              app.globalData.userWxInfo.address = otherInfo[0].address;
              app.globalData.userWxInfo.groupName = otherInfo[0].groupName;
              
              // 将新选择的户号信息保存到本地存储
              wx.setStorageSync('currentHuHao', otherInfo[0]);
              // 设置一个标记表示需要刷新首页
              wx.setStorageSync('needRefreshHomepage', true);
              wx.setStorageSync('backFromHuHao', true);
              wx.navigateBack();
            }
          }
        } else {
          wx.showToast({
            title: apiReturnData.msg,
            icon: 'error',
            duration: 2000
          })
          wx.hideLoading();
        }
      },
      fail(error) {
        wx.hideLoading();
        utils.simleInfo('户号解绑失败，请稍后再试');
      }
    });
  },
  // 跳转到绑定新户号页面
  goToBindNewHuHao: function () {
    wx.navigateTo({
      url: '/pages/huhaobangding/huhaobangding'
    });
  },

  /**
   * 返回上一页
   */
  goBack: function () {
    wx.navigateBack();
  },

  switchHuHao(e) {
    const huHaoInfo = e.currentTarget.dataset.item;
debugger
    // 更新全局数据
    app.globalData.userWxInfo = {
      ...app.globalData.userWxInfo,
      username: huHaoInfo.username,
      usernumber: huHaoInfo.usernumber,
      address: huHaoInfo.address,
      groupName: huHaoInfo.groupName,
      currentDsKey: huHaoInfo.dsKey // 更新 currentDsKey
    };

    // 更新当前账户信息
    app.globalData.currentAccountInfo = huHaoInfo;
    // 将新选择的户号信息保存到本地存储
    wx.setStorageSync('currentHuHao', huHaoInfo);
    wx.showToast({
      title: '户号切换成功',
      icon: 'success',
      duration: 1500
    });
    // 设置一个标记表示需要刷新首页
    wx.setStorageSync('needRefreshHomepage', true);

    // 延迟跳转到首页
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/homepage/homepage'
      });
    }, 1500);
  },

  // 设置默认户号
  setDefaultHuHao: function (e) {
    const id = e.currentTarget.dataset.id;
    this.setData({
      showDefaultModal: true,
      defaultId: id
    });
  },

  // 取消设置默认户号
  cancelDefault: function () {
    this.setData({
      showDefaultModal: false,
      defaultId: null
    });
  },

  // 确认设置默认户号
  confirmDefault: function () {
    const id = this.data.defaultId;
    this.setDefaultAccount(id);
    this.setData({
      showDefaultModal: false
    });
  },

  // 调用设置默认户号接口
  setDefaultAccount: function (id) {
    wx.showLoading({
      title: '设置中...',
    });
    const unbindInfo = this.data.huHaoList.filter(item => {
      return item.id === id;
    })[0];
    wx.request({
      url: app.globalData.interfaceUrls.setDefaultAccount,
      method: 'POST',
      data: {
        account: unbindInfo.usernumber,
        deKey: unbindInfo.dsKey,
        refresh: false,
        otherDsKeys: []
      },
      header: {
        'content-type': 'application/json', // 默认值
        'token': app.globalData.userWxInfo.token,
      },
      success: (res) => {
        if (res.data.code === "200") {
          wx.showToast({
            title: '设置成功',
            icon: 'success'
          });
          // 延迟一小段时间后刷新列表，确保后台数据已更新
          setTimeout(() => {
            this.getAccountList();
          }, 300);
        } else {
          wx.showToast({
            title: res.data.msg || '设置失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 过滤户号列表，只显示deleted=0的数据，并按默认户号排序
  getAccountList: function () {
    const _this = this;
    wx.showLoading({
      title: '获取中...',
      mask: true,
    });
    wx.request({
      url: app.globalData.interfaceUrls.accountList,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'token': app.globalData.userWxInfo.token,
        'source': "wc",
        '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
      },
      success(res) {

        wx.hideLoading();
        let apiReturnData = res.data;
        // 从全局获取当前账户的信息currentAccountInfo
        const currentUsernumber = app.globalData.currentAccountInfo.usernumber;
        debugger
        // 对返回的数据进行排序，将默认户号(defaultAccount='0')排在前面
        const sortedData = apiReturnData.data.sort((a, b) => {
          // 先按defaultAccount排序（'0'排在前面）
          if (a.defaultAccount !== b.defaultAccount) {
            return a.defaultAccount === '0' ? -1 : 1;
          }
          // 如果defaultAccount相同，则按是否是当前户号排序
          if (a.usernumber === currentUsernumber) return -1;
          if (b.usernumber === currentUsernumber) return 1;
          return 0;
        });

        _this.setData({
          huHaoList: sortedData.map(item => {
            const isCurrent = item.usernumber === currentUsernumber;
            return {
              ...item,
              isCurrentUser: isCurrent
            };
          })
        });
        // 在获取列表后也检查是否为空
        if (_this.data.huHaoList.length === 0) {
          wx.navigateTo({
            url: '/pages/FirstBangDing/FirstBangDing'
          });
        }
      },
      fail(error) {
        wx.hideLoading();
        console.error('获取列表失败:', error);
        wx.showToast({
          title: '获取数据失败，请稍后再试',
          icon: 'none'
        });
      }
    });
  },
  // 阻止事件冒泡
  stopPropagation: function (e) {
    // 空函数，仅用于阻止事件冒泡
  },
})