// pages/profile/platform-bind/platform-bind.ts
Page({
  data: {
    platformType: '',
    platformName: '',
    countryCode: '+86',
    phone: '',
    code: '',
    codeSending: false,
    countdown: 0,
    binded: false,
    bindTime: ''
  },

  onLoad(options: any) {
    const platform = options.platform || 'xiaohongshu';
    
    // 如果是小红书，跳转到专门的小红书登录页
    if (platform === 'xiaohongshu') {
      wx.redirectTo({
        url: '/pages/profile/xhs-login/xhs-login'
      });
      return;
    }
    
    const platformNames: Record<string, string> = {
      xiaohongshu: '小红书',
      weibo: '微博',
      douyin: '抖音'
    };

    this.setData({
      platformType: platform,
      platformName: platformNames[platform]
    });

    this.loadBindingStatus(platform);
  },

  // 加载绑定状态
  loadBindingStatus(platform: string) {
    const bindings = wx.getStorageSync('socialBindings') || {};
    const bindingInfo = bindings[platform];

    if (bindingInfo) {
      const bindTime = new Date(bindingInfo.bindTime);
      const formatTime = `${bindTime.getFullYear()}-${String(bindTime.getMonth() + 1).padStart(2, '0')}-${String(bindTime.getDate()).padStart(2, '0')} ${String(bindTime.getHours()).padStart(2, '0')}:${String(bindTime.getMinutes()).padStart(2, '0')}`;

      this.setData({
        binded: true,
        phone: bindingInfo.phone,
        bindTime: formatTime
      });
    }
  },

  // 选择国家区号
  selectCountryCode() {
    const codes = ['+86', '+852', '+853', '+886', '+1', '+44', '+81', '+82'];
    const names = ['中国大陆', '中国香港', '中国澳门', '中国台湾', '美国', '英国', '日本', '韩国'];
    
    wx.showActionSheet({
      itemList: names.map((name, index) => `${name} ${codes[index]}`),
      success: (res) => {
        this.setData({
          countryCode: codes[res.tapIndex]
        });
      }
    });
  },

  // 手机号输入
  onPhoneInput(e: any) {
    this.setData({
      phone: e.detail.value
    });
  },

  // 验证码输入
  onCodeInput(e: any) {
    this.setData({
      code: e.detail.value
    });
  },

  // 发送验证码
  sendCode() {
    const phone = this.data.phone;

    // 验证手机号
    if (!phone || phone.length !== 11) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    // 手机号格式验证
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return;
    }

    // 设置发送状态
    this.setData({
      codeSending: true
    });

    // 模拟发送验证码（实际应该调用后端API）
    wx.showLoading({
      title: '发送中...',
      mask: true
    });

    setTimeout(() => {
      wx.hideLoading();
      
      wx.showToast({
        title: '验证码已发送',
        icon: 'success'
      });

      // 开始倒计时
      this.startCountdown();
      
      // 在控制台输出模拟验证码（实际开发中删除）
      console.log(`验证码: 123456`);
    }, 1000);
  },

  // 倒计时
  startCountdown() {
    let countdown = 60;
    
    this.setData({
      countdown: countdown,
      codeSending: true
    });

    const timer = setInterval(() => {
      countdown--;
      
      if (countdown <= 0) {
        clearInterval(timer);
        this.setData({
          countdown: 0,
          codeSending: false
        });
      } else {
        this.setData({
          countdown: countdown
        });
      }
    }, 1000);
  },

  // 绑定账号
  bindAccount() {
    const phone = this.data.phone;
    const code = this.data.code;
    const platform = this.data.platformType;

    // 验证手机号
    if (!phone || phone.length !== 11) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    // 验证验证码
    if (!code || code.length !== 6) {
      wx.showToast({
        title: '请输入6位验证码',
        icon: 'none'
      });
      return;
    }

    // 模拟验证码验证（实际应该调用后端API）
    wx.showLoading({
      title: '绑定中...',
      mask: true
    });

    setTimeout(() => {
      wx.hideLoading();

      // 保存绑定信息
      const bindings = wx.getStorageSync('socialBindings') || {};
      const bindTime = new Date().getTime();
      bindings[platform] = {
        phone: phone,
        bindTime: bindTime
      };
      wx.setStorageSync('socialBindings', bindings);

      // 格式化时间
      const time = new Date(bindTime);
      const formatTime = `${time.getFullYear()}-${String(time.getMonth() + 1).padStart(2, '0')}-${String(time.getDate()).padStart(2, '0')} ${String(time.getHours()).padStart(2, '0')}:${String(time.getMinutes()).padStart(2, '0')}`;

      // 更新状态
      this.setData({
        binded: true,
        code: '',
        bindTime: formatTime
      });

      wx.showToast({
        title: '绑定成功',
        icon: 'success',
        duration: 1500
      });
    }, 1500);
  },

  // 跳转到用户协议
  goToUserAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/user-agreement/user-agreement'
    });
  },

  // 跳转到隐私政策
  goToPrivacy() {
    wx.navigateTo({
      url: '/pages/agreement/privacy-policy/privacy-policy'
    });
  },

  // 跳转到个人信息保护政策
  goToPersonalInfo() {
    // TODO: 创建个人信息保护政策页面
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 解除绑定
  unbindAccount() {
    const platform = this.data.platformType;
    const platformName = this.data.platformName;

    wx.showModal({
      title: '解除绑定',
      content: `确定要解除${platformName}账号绑定吗？`,
      confirmText: '解除',
      confirmColor: '#07c160',
      success: (res) => {
        if (res.confirm) {
          // 删除绑定信息
          const bindings = wx.getStorageSync('socialBindings') || {};
          delete bindings[platform];
          wx.setStorageSync('socialBindings', bindings);

          // 更新状态
          this.setData({
            binded: false,
            phone: '',
            code: '',
            bindTime: ''
          });

          wx.showToast({
            title: '已解除绑定',
            icon: 'success',
            duration: 1500,
            success: () => {
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
            }
          });
        }
      }
    });
  }
});
