import { baseUrl } from "../../../request";
import { requestAsync } from "../../../utils/request";
import { validate } from "../../../utils/validate";

// pages/loginModule/register/register.js
Page({

  data: {
    role: '', // 用户角色
    placeholder: '', // 输入框显示文本
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options--->',options);
    this.setData({
      role: options.role
    })
    const scene = decodeURIComponent(options.scene)
    if (scene !== 'undefined') {
      let [key, value] = scene.split('=');
      console.log(key, value)
      if (value === 'manager') value = 'supervisor'
      else if (value === 'supervisor') value = 'staff'
      else if (value === 'staff') value = 'user'
      this.setData({inviteCode: key, role: value})   
     }

    if (this.data.role === 'supervisor') {
      this.setData({
        placeholder: '请输入学校名称'
      })
    } else {
      this.setData({
        placeholder : '请输入昵称'
      })
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    nickname: '',
    phone: '',
    captcha: '',
    inviteCode: '',
    password: '',
    agree: false,
    sending: false,
    count: 60,
  },

  sendSmsCode() {
    const { phone, role } = this.data;
    if (!phone.trim()) {
      wx.showToast({ title: '请输入手机号', icon: 'none' });
      return;
    }
    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({ title: '请输入有效的手机号', icon: 'none' });
      return;
    }
    wx.request({
      url: baseUrl + '/userInfo/code/register',
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: {
        phoneNumber: phone,
        userRole: role
      },
      success: res => {
        // 假设后端返回 { success: true, ... }
        if (res.data.code === 1) {
          wx.showToast({ title: '验证码已发送' });
          this.startCountdown();
        } else {
          wx.showToast({
            title: res.data.message || '发送失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 验证码开始
  startCountdown() {
    this.setData({ sending: true, count: 60 });
    const timer = setInterval(() => {
      let { count } = this.data;
      if (count <= 1) {
        clearInterval(timer);
        this.setData({ sending: false });
      } else {
        this.setData({ count: count - 1 });
      }
    }, 1000);
  },

  // 通用输入事件处理函数
  onInput(e) {
    const field = e.currentTarget.dataset.field;  // 获取字段名
    const value = e.detail.value;                 // 获取输入内容
    this.setData({
      [field]: value                              // 动态更新对应字段
    });
  }, 

  // 复选框事件处理（如果使用 checkbox-group 推荐用 change）
  onCheckboxChange(e) {
    this.setData({
      agree: e.detail.value.length > 0
    });
  },
  validatePassword(password) {
    // 校验密码长度
    if (password.length < 6 || password.length > 10) {
        wx.showToast({
            title: '密码长度应在6到10个字符之间',
            icon: 'none',
            duration: 1000
        });
        return false;
    }

    // 校验是否包含字母、数字和下划线
    const regex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]+$/;
    if (!regex.test(password)) {
        wx.showToast({
            title: '密码必须包含字母和数字，且不包含特殊字符',
            icon: 'none',
            duration: 1000
        });
        return false;
    }
    return true;
  },

  // 注册按钮点击
  async onRegister() {
    // 调用通用校验，失败时已提示并 return
    if (!validate(this.data, {
      nickname:    '昵称不能为空',
      phone:       '手机号不能为空',
      captcha:     '验证码不能为空',
      inviteCode:  '邀请码不能为空',
      password:    '密码不能为空'
    })) {
      return;
    }
    const { nickname, phone, captcha, inviteCode, password } = this.data;
    if (!this.validatePassword(password)) return ;
    // 2. 再单独校验协议勾选
    if (!this.data.agree) {
      wx.showToast({ title: '请先同意用户协议', icon: 'none' });
      return;
    }
    wx.showLoading({
      title: '加载中',
      mask: true
    })

    const { role } = this.data;
    const res = await requestAsync({
      url: baseUrl + '/userInfo/register',
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: {
        nickName: nickname,
        phoneNumber: phone,
        verificationCode: captcha,
        invitationCode: inviteCode,
        userPassword: password,
        userRole: role
      }
    });
    console.log('注册信息---->',res.data);
    if (res.data.code === 1) {
      wx.showToast({
        title: '注册成功',
        icon: 'success',
        duration: 1000,
      });
      setTimeout(() => {
        wx.navigateTo({
          url: `/pages/loginModule/pwdLogin/pwdLogin?role=${role}`,
          success: () => {
            this.setData({ nickname:'', phone:'', captcha:'', inviteCode:'', password:'', agree:false });
          }
        });
      }, 1000);
    } else {
      console.log(res.data)
      wx.showToast({
        title: res.data.message || '注册失败',
        icon:  'none',
        duration: 1000
      });
      // wx.hideLoading()
    }
  },

 gotoLogin() {
   wx.navigateBack({
     delta: 1
   })
 },

 gotoAgreement() {
  wx.navigateTo({
    url: '/pages/loginModule/agreement/agreement',
  })
},

gotoPolicy() {
  wx.navigateTo({
    url: '/pages/loginModule/privacyPolicy/privacyPolicy',
  })
},
})