import {url} from '../request'
import cityList from './city';
Page({
  data: {
    cityList,
        cascaderValue: ['34', '330'],
        cascaderVisible: false,
        businessName:'',
        person:'',
        phone:'',
        idcard:'',
        selectedOption:'',
        error:''
  },
  onLoad() {},
  ruzhu(){
    if (!this.validateForm()) {
      return;  // 验证未通过，阻止提交
    }
    my.getStorage({
      key: 'userInfo',
      success: (res) => {
        const userInfo = res.data;
        this.setData({
          id: userInfo.id, // 获取 id
        });
        console.log(this.data.id,);
        if (userInfo && userInfo.cookie) {
          my.request({
            url: url + '/api/manicurist/add',
            method: 'POST',
            data: {
                certificate_path: this.data.zhengshu,
                certification_number: this.data.idcard,
                email: this.data.person,
                gender: this.data.xingbie,
                issuing_authority: this.data.selectedOption,
                manicuristName: this.data.businessName,
                nameUser: this.data.businessName,
                phone: this.data.phone,
                specialties: this.data.shanchang,
                userId: this.data.id,
                manicuristAvatar: this.data.avatar,
            },
            headers: {
              'content-type': 'application/json',
              'Cookie': userInfo.cookie,
            },
            dataType: 'json',
            success: (res) => {
              this.setData({
                error:res.data.description
              })
              console.log(res);
             if(res.data.code===0){
              my.navigateBack();
              my.alert({content:'审核中请耐心等待'})
             }else{
              my.alert({content:this.data.error})
             }
            },
            fail: (error) => {
              console.error('请求失败: ', JSON.stringify(error));
              my.alert({ content: '请求失败，请稍后重试' });
            },
          });
        } else {
          my.alert({
            content: '您未登录，请先登录。',
            success: () => {
              my.navigateTo({
                url: '/pages/denglu/denglu',
              });
            },
          });
        }
      },
    });
    
  },
  businessName(e) {
    this.setData({
      businessName: e.detail.value,
    });
    console.log(e.detail.value);
  },
  shanchang(e) {
    this.setData({
      shanchang: e.detail.value,
    });
    console.log(e.detail.value);
  },
  xingbie(e) {
    if(e.detail.value=='男'){
      this.setData({
        xingbie: 0,
      });
    }
    if(e.detail.value=='女'){
      this.setData({
        xingbie: 1,
      });
    }
    console.log(e.detail.value);
    console.log(this.data.xingbie);
  },
  person(e) {
    this.setData({
      person: e.detail.value,
    });
    console.log(e.detail.value);
  },
  phone(e) {
    this.setData({
      phone: e.detail.value,
    });
    console.log(e.detail.value);
  },
  idcard(e) {
    this.setData({
      idcard: e.detail.value,
    });
    console.log(e.detail.value);
  },
  // 选择地址的方法
  handleCascaderPickerChange(cascaderValue, selectedOption, e) {
    console.log('cityChange', cascaderValue, selectedOption, e);
},
handleCascaderOnOk(cascaderValue, selectedOption, e) {
  console.log('cityOk', cascaderValue, selectedOption, e);
  const selectedCityLabels = selectedOption.map(option => option.label).join(' ');  

  this.setData({
    selectedOption: selectedCityLabels  
  });

  console.log('Selected cities:', this.data.selectedOption);
},

handleDismiss(e) {
  my.showToast({
      content: '取消操作',
  });
  console.log(e);
},
validateForm() {
  // 验证姓名（非空）
  if (!this.data.businessName) {
    my.showToast({
      content: '姓名不能为空',
      type: 'none',
      duration: 2000,
    });
    return false;
  }

  // 验证邮箱（简单的正则校验）
  const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
  if (!this.data.person || !emailRegex.test(this.data.person)) {
    my.showToast({
      content: '请输入有效的电子邮箱',
      type: 'none',
      duration: 2000,
    });
    return false;
  }

  // 验证电话（简单的正则校验）
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!this.data.phone || !phoneRegex.test(this.data.phone)) {
    my.showToast({
      content: '请输入有效的手机号码',
      type: 'none',
      duration: 2000,
    });
    return false;
  }

  // 验证身份证号（简单的正则校验）
  const idcardRegex = /^\d{17}(\d|X)$/;
  if (!this.data.idcard || !idcardRegex.test(this.data.idcard)) {
    my.showToast({
      content: '请输入有效的身份证号',
      type: 'none',
      duration: 2000,
    });
    return false;
  }

  // 验证是否选择了城市
  if (!this.data.selectedOption) {
    my.showToast({
      content: '请选择省市',
      type: 'none',
      duration: 2000,
    });
    return false;
  }
  if (!this.data.zhengshu) {
    my.showToast({
      content: '证书出错了',
      type: 'none',
      duration: 2000,
    });
    return false;
  }
  if (!this.data.shanchang) {
    my.showToast({
      content: '擅长项目有误',
      type: 'none',
      duration: 2000,
    });
    return false;
  }
 

  return true; // 所有验证通过
},
// 证明
onUpload(file) {
  return new Promise((resolve, reject) => {
    console.log('上传文件路径：', file); // 确保文件路径正确
    my.uploadFile({
      url: url + '/api/file/upload/server/not_login',
      fileType: 'image',
      name: 'file',
      filePath: file.path,
      formData: { 
        biz: 'card',
       },
      success: res => {
        resolve(file.path);
        console.log('上传成功:', res);
        const cunchu = JSON.parse(res.data)
        this.setData({
          zhengshu:cunchu.data,
        })
        console.log(this.data.zhengshu,'hhhhhhhhhhhhhhh'); 
      },
      fail: (err) => {
        console.log('上传失败:', err);
        reject();
      },
    });
  });
},
onUploada(file) {
  return new Promise((resolve, reject) => {
    console.log('上传文件路径：', file); // 确保文件路径正确
    my.uploadFile({
      url: url + '/api/file/upload/server/not_login',
      fileType: 'image',
      name: 'file',
      filePath: file.path,
      formData: { 
        biz: 'card',
       },
      success: res => {
        resolve(file.path);
        console.log('上传成功:', res);
        const touxiang = JSON.parse(res.data)
        this.setData({
          avatar:`${"https://"}${touxiang.data}`,
        })
        console.log(this.data.avatar,'avatar'); 
      },
      fail: (err) => {
        console.log('上传失败:', err);
        reject();
      },
    });
  });
},

});
