const { baseUrl } = require('../../../request');
const { validate } = require('../../../utils/validate');

Page({
  data: {
    name: '',
    phone: '',
    code: '',  // 验证码
    idcard: '',  // 身份证号
    codeSent: false,
    countdown: 0,        // 剩余秒数
    codeButtonText: '获取验证码',
    _timer: null,
    isUploading: false,
    resumeUploaded: false,
    resumeFilePath: '',
    fileCode: '',  // 上传文件后端返回的码
    credential: '', // 用户申请后的唯一凭证，用于查询用户是否审核通过
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      [field]: e.detail.value
    });
  },

  // 获取验证码（仅校验手机号）
  getSmsCode() {
    const { phone } = 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/register',
      method: 'POST',
      data: { 
        phoneNumber: phone,
        userRole: 'staff'
       },
      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;
    }
  },

  // 选择并上传简历
  chooseResume() {
    if (this.data.resumeUploaded) return;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: res => {
        const file = res.tempFiles[0];
        this.uploadResume(file);
      }
    });
  },

  // 上传简历
  uploadResume(file) {
    this.setData({ isUploading: true });
    wx.uploadFile({
      url: baseUrl + '/file/upload', 
      method: 'POST',
      name: 'file',
      header : {
        Authorization: wx.getStorageSync('token'),
      },
      formData: {
        biz: 'default',   // 传 biz 文本字段
      },
      filePath: file.path,
      success: res => {
        console.log('简历上传后端返回--->',JSON.parse(res.data));
        const data = JSON.parse(res.data);
        console.log('后端返回文件码--->',data.data);
        if (data.code === 1) {
          wx.showToast({ title: '上传成功', icon: 'success' });
          this.setData({
            isUploading: false,
            resumeUploaded: true,
            resumeFilePath: file.path,
            fileCode: data.data
          });
        } else {
          wx.showToast({ title: data.message || '上传失败', icon: 'none' });
          this.setData({ isUploading: false });
        }
      },
      fail: () => {
        wx.showToast({ title: '上传失败，请重试', icon: 'none' });
        this.setData({ isUploading: false });
      }
    });
  },

  // 提交表单
  handleSubmit() {
    const { name, phone, code, idcard, fileCode } = this.data;
  
    // 校验用户是否填写所有必要信息
    if (!name || !phone || !code || !idcard || !fileCode) {
      wx.showToast({ title: '请填写所有信息', icon: 'none' });
      return;
    }
  
    // 姓名只能中文或英文
    if (!/^[\u4e00-\u9fa5A-Za-z]+$/.test(name)) {
      wx.showToast({ title: '姓名只能为中英文', icon: 'none' });
      return;
    }

    // 校验身份证号
    const idCardReg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    if (!idCardReg.test(idcard)) {
      wx.showToast({
        title: '身份证号格式不正确',
        icon: 'none'
      })
      return ;
    }
  
    // 提交表单数据到后端
    wx.request({
      url: baseUrl + '/advancementApply/add',
      method: 'POST',
      header: {
        Authorization: wx.getStorageSync('token')
      },
      data: {
        name: name,
        phone: phone,
        verificationCode: code,
        idCard: idcard,
        resume: fileCode
      },
      success: res => {
        console.log('后端返回的申请---->', res);
        if (res.data.code === 1) {
          wx.showToast({ title: '提交成功', icon: 'success' });
          
          // 清空表单内容
          this.setData({
            name: '',
            phone: '',
            code: '',
            idcard: '',
            fileCode: '',
            resumeUploaded: false,  // 重置简历上传状态
            resumeFilePath: '',  // 清空简历文件路径
            credential: ''  // 清空凭证
          });
        } else {
          wx.showToast({ title: res.data.message, icon: 'none' });
        }
      }
    });
  },

  // 跳转申请须知
  gotoNotice() {
    wx.navigateTo({
      url: '/pages/loginModule/employeeAccountNotice/employeeAccountNotice',
    })
  },

  // 跳转我的申请记录
  gotoQuery() {
    wx.navigateTo({
      url: '/pages/loginModule/employeeApplyQuery/employeeApplyQuery',
    })
  },
});
