// pages/profile/social-binding/social-binding.ts
import { EmployeeService } from '../../../services/employee';

Page({
  data: {
    // 小红书
    xiaohongshuBinded: false,
    xiaohongshuPhone: '',
    xiaohongshuAccount: '',
    xiaohongshuCookieExpired: false,  // Cookie是否失效
    xiaohongshuStatusText: '去绑定',
    xiaohongshuStatusClass: '',
    
    // 微博
    weiboBinded: false,
    weiboPhone: '',
    
    // 抖音
    douyinBinded: false,
    douyinPhone: ''
  },

  onLoad() {
    this.loadBindingStatus();
  },

  onShow() {
    // 每次显示时重新加载绑定状态
    this.loadBindingStatus();
    // 同时从后端加载
    this.loadUserProfile();
  },

  // 从BACKEND加载用户信息（包含小红书绑定状态）
  async loadUserProfile() {
    try {
      const response = await EmployeeService.getProfile();
      
      if (response.code === 200 && response.data) {
        const userInfo = response.data;
        const isBound = userInfo.is_bound_xhs === 1;
        // 使用has_xhs_cookie字段判断，而不是xhs_cookie
        const hasCookie = userInfo.has_xhs_cookie === true;
        
        // 判断状态
        let statusText = '去绑定';
        let statusClass = '';
        let cookieExpired = false;
        
        if (isBound) {
          if (hasCookie) {
            // 已绑定且Cookie有效
            statusText = '已绑定';
            statusClass = 'binded';
          } else {
            // 已绑定但Cookie失效
            statusText = '已失效';
            statusClass = 'expired';
            cookieExpired = true;
          }
        }
        
        this.setData({
          xiaohongshuBinded: isBound,
          xiaohongshuAccount: userInfo.xhs_account || '',
          xiaohongshuPhone: userInfo.xhs_phone || '',
          xiaohongshuCookieExpired: cookieExpired,
          xiaohongshuStatusText: statusText,
          xiaohongshuStatusClass: statusClass
        });

        // 更新本地存储
        if (isBound) {
          const bindings = wx.getStorageSync('socialBindings') || {};
          bindings.xiaohongshu = {
            phone: userInfo.xhs_phone,
            xhs_account: userInfo.xhs_account,
            bindTime: userInfo.bound_at || new Date().getTime(),
            cookieExpired: cookieExpired
          };
          wx.setStorageSync('socialBindings', bindings);
        }
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
    }
  },

  // 加载绑定状态
  loadBindingStatus() {
    const bindings = wx.getStorageSync('socialBindings') || {};
    
    this.setData({
      xiaohongshuBinded: !!bindings.xiaohongshu,
      xiaohongshuPhone: (bindings.xiaohongshu && bindings.xiaohongshu.phone) || '',
      
      weiboBinded: !!bindings.weibo,
      weiboPhone: (bindings.weibo && bindings.weibo.phone) || '',
      
      douyinBinded: !!bindings.douyin,
      douyinPhone: (bindings.douyin && bindings.douyin.phone) || ''
    });
  },

  // 跳转到平台绑定页面
  goToPlatformBind(e: any) {
    const platform = e.currentTarget.dataset.platform;
    
    // 如果是小红书
    if (platform === 'xiaohongshu') {
      // Cookie失效，直接跳转重新绑定
      if (this.data.xiaohongshuCookieExpired) {
        wx.navigateTo({
          url: '/pages/profile/xhs-login/xhs-login'
        });
        return;
      }
      
      // 已绑定且Cookie有效，显示解绑确认
      if (this.data.xiaohongshuBinded && !this.data.xiaohongshuCookieExpired) {
        this.handleUnbindXHS();
        return;
      }
      
      // 未绑定，跳转到绑定页
      wx.navigateTo({
        url: '/pages/profile/xhs-login/xhs-login'
      });
      return;
    }

    wx.navigateTo({
      url: `/pages/profile/platform-bind/platform-bind?platform=${platform}`
    });
  },

  // 解绑小红书
  handleUnbindXHS() {
    wx.showModal({
      title: '确认解绑',
      content: '确定要解绑小红书账号吗？',
      confirmText: '解绑',
      confirmColor: '#FF6B6B',
      success: async (res) => {
        if (res.confirm) {
          try {
            const response = await EmployeeService.unbindXHS();
            
            if (response.code === 200) {
              wx.showToast({
                title: '解绑成功',
                icon: 'success'
              });

              // 清除本地存储
              const bindings = wx.getStorageSync('socialBindings') || {};
              delete bindings.xiaohongshu;
              wx.setStorageSync('socialBindings', bindings);

              // 刷新页面
              this.setData({
                xiaohongshuBinded: false,
                xiaohongshuPhone: '',
                xiaohongshuAccount: ''
              });
            }
          } catch (error) {
            console.error('解绑失败:', error);
          }
        }
      }
    });
  }
});
