// pages/profile/xhs-login/xhs-login.ts
import { EmployeeService } from '../../../services/employee';

Page({
  data: {
    countryCode: '+86',
    phone: '',
    code: '',
    codeSending: false,
    countdown: 0,
    agreedToTerms: false,
    showAgreementModal: false
  },

  // 选择国家区号
  selectCountryCode() {
    const codes = ['+86', '+852', '+853', '+886'];
    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
    });
  },

  // 协议勾选变化
  onAgreementChange(e: any) {
    this.setData({
      agreedToTerms: e.detail.value.length > 0
    });
  },

  // 发送验证码
  async 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;
    }

    // 防止重复发送
    if (this.data.codeSending || this.data.countdown > 0) {
      return;
    }

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

    try {
      // 调用后端API发送验证码
      const response = await EmployeeService.sendXHSCode(phone);
      
      if (response.code === 200) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
        this.startCountdown();
      } else {
        wx.showToast({
          title: response.message || '发送失败',
          icon: 'none'
        });
        this.setData({
          codeSending: false
        });
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      wx.showToast({
        title: '发送失败，请重试',
        icon: 'none'
      });
      this.setData({
        codeSending: false
      });
    }
  },

  // 倒计时
  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);
  },

  // 登录
  async login() {
    const phone = this.data.phone;
    const code = this.data.code;

    // 检查是否同意协议
    if (!this.data.agreedToTerms) {
      this.setData({
        showAgreementModal: true
      });
      return;
    }

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

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

    try {
      // 调用后端API绑定小红书
      const response = await EmployeeService.bindXHS(phone, code);

      if (response.code === 200) {
        // 绑定成功，保存绑定信息
        const bindings = wx.getStorageSync('socialBindings') || {};
        bindings.xiaohongshu = {
          phone: phone,
          bindTime: new Date().getTime(),
          xhs_account: (response.data && response.data.xhs_account) || ''
        };
        wx.setStorageSync('socialBindings', bindings);

        wx.showToast({
          title: '绑定成功',
          icon: 'success',
          duration: 1500
        });
        
        // 延迟500毫秒后返回，让用户看到成功提示
        setTimeout(() => {
          // 返回上一页（社交账号绑定页）
          wx.navigateBack({
            delta: 1
          });
        }, 1500);
      }
    } catch (error) {
      console.error('绑定小红书失败:', error);
    }
  },

  // 关闭协议弹窗
  closeAgreementModal() {
    this.setData({
      showAgreementModal: false
    });
  },

  // 同意并登录
  agreeAndLogin() {
    this.setData({
      agreedToTerms: true,
      showAgreementModal: false
    });
    
    // 延迟执行登录，让用户看到勾选效果
    setTimeout(() => {
      this.login();
    }, 300);
  },

  // 阻止事件冒泡
  stopPropagation() {},

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

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