// pages/login/login.js
const { baseUrl } = require('../../../request');
const { validate } = require('../../../utils/validate');
const roleMap = new Map([
  ['manager',    '经理'],
  ['supervisor', '主管'],
  ['staff',      '员工'],
  ['user',       '用户'],
]);

Page({
  data: {
    loginType: 'password',    // 'password' 或 'sms'
    phone: '',
    credential: '',
    isAgree: false,           // 用户协议是否勾选
    countdown: 0,             // 剩余秒数
    codeButtonText: '获取验证码',
    _timer: null,
    defaultType: true,  // 
    passwordType: true,
    role: '', // 登录角色
    showRole: '',
    isShowRegister: true
  },

  onLoad(options) {
    const role = options.role || ''
    const showRole = roleMap.get(role) || ''
    this.setData({ role, showRole })
    if (role === 'manager') this.setData({isShowRegister: false})
  },

  // 切换到“密码登录”，只清空表单字段
  switchToPassword() {
    this.setData({
      loginType: 'password',
      phone: '',
      credential: ''
      // 不清除 countdown、codeButtonText、_timer
    });
  },

  // 切换到“验证码登录”，只清空表单字段
  switchToSms() {
    this.setData({
      loginType: 'sms',
      phone: '',
      credential: ''
      // 不清除 countdown、codeButtonText、_timer
    });
  },

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

  // 密码/验证码输入
  onCredentialInput(e) {
    this.setData({ credential: e.detail.value });
  },

  // 协议勾选
  onAgreeChange(e) {
    this.setData({ isAgree: e.detail.value.includes('agree') });
  },

  // 获取验证码（仅校验手机号）
  getSmsCode() {
    const { phone, role } = this.data;

    // 1. 非空校验
    if (!validate(this.data, { phone: '请输入手机号' })) {
      return;
    }
    // 2. 格式校验
    if (!/^1\d{10}$/.test(phone)) {
      return wx.showToast({ title: '手机号格式不正确', icon: 'none' });
    }

    // 3. 发送验证码请求
    wx.request({
      url: baseUrl + '/userInfo/code/pwd',
      method: 'POST',
      data: { 
        phoneNumber: phone,
        userRole: role
      },
      success: (res) => {
        console.log('验证码发送--->',res.data);
        if (res.data.code === 1) {
          wx.showToast({ title: '验证码已发送', icon: 'none' });
          this._startCountdown(60);
        } else {
          wx.showToast({ title: res.data.message, icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '发送失败，请重试', icon: 'none' });
      }
    });
  },

  // 开始倒计时
  _startCountdown(seconds) {
    this.setData({
      countdown: seconds,
      codeButtonText: `${seconds}s后重试`
    });
    // 如果已有定时器，不重复创建
    if (this.data._timer) return;
    this.data._timer = setInterval(() => {
      const cd = this.data.countdown - 1;
      if (cd <= 0) {
        this._clearTimer();
        this.setData({
          countdown: 0,
          codeButtonText: '获取验证码'
        });
      } else {
        this.setData({
          countdown: cd,
          codeButtonText: `${cd}s后重试`
        });
      }
    }, 1000);
  },

  // 清除倒计时定时器
  _clearTimer() {
    if (this.data._timer) {
      clearInterval(this.data._timer);
      this.data._timer = null;
    }
  },

  // 登录
  onLogin() {
    const { loginType, phone, credential, isAgree } = this.data;

    // 非空校验（手机号、密码/验证码、协议）
    if (!phone.trim()) {
      wx.showToast({ title: '请输入手机号', icon: 'none' });
      return;
    }
    // 手机号格式校验
    if (!/^1\d{10}$/.test(phone)) {
      return wx.showToast({ title: '手机号格式不正确', icon: 'none' });
    }
    if (!validate(this.data, {
      credential: loginType === 'password' ? '请输入密码' : '请输入验证码',
    })) {
      return;
    }
    // 2. 再单独校验协议勾选
  if (!this.data.isAgree) {
    wx.showToast({ title: '请先同意用户协议', icon: 'none' });
    return;
  }

  const { role } = this.data
    // 组装请求
    const url = loginType === 'password'
      ? baseUrl + '/userInfo/mini/pwd/login'
      : baseUrl + '/userInfo/mini/vcd/login';
    const payload = loginType === 'password'
      ? { phoneNumber: phone, userPassword: credential, userRole: role }
      : { phoneNumber: phone, verificationCode: credential, userRole: role };

    wx.request({
      url,
      method: 'POST',
      data: payload,
      success: res => {
        console.log('--->',res.data.data);
        if (res.data.code === 1) {
          // ← 新增：从返回数据中取出 token
          const token = res.data.data.token || res.data.data;
          // ← 新增：将 token 存到本地缓存
          wx.setStorageSync('token', token);
          wx.setStorageSync('role', role)
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1000
          });
        
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/course/homepage/homepage',
            })
          }, 1000); // 1000ms = 1秒
        } else {
          wx.showToast({
            title: res.data.message || '登录失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误，请重试', icon: 'none' });
      }
    });
  },

  // 跳转忘记密码
  gotoForgetPwd() {

    const { role } = this.data;
    wx.navigateTo({
      url: `/pages/loginModule/forgetPwd/forgetPwd?role=${role}`,
    })
  },

  // 去注册
  gotoRegister() {

    const { role } = this.data;

    wx.navigateTo({
      url: `/pages/loginModule/register/register?role=${ role }`,
    })
  },

  // 页面卸载时清理定时器
  onUnload() {
    this._clearTimer();
  },

  // 跳转用户协议
  gotoAgreement() {
    wx.navigateTo({
      url: '/pages/loginModule/agreement/agreement',
    })
  },

  // 跳转隐私协议
  gotoPolicy() {
    wx.navigateTo({
      url: '/pages/loginModule/privacyPolicy/privacyPolicy',
    })
  },

  // 跳转职工账号页面
  joinUs() {
    wx.navigateTo({
      url: '/pages/loginModule/employeeAccountApply/employeeAccountApply',
    })
  },

});
