<template>
  <view class="volunteer-apply-page">
    <!-- 头部背景图 -->
    <view class="header-section">
      <image src="../static/volunteer_bg@2x.png" class="bg-image" mode="aspectFit"></image>
    </view>
    
    <!-- 提示信息 -->
    <view class="tip-section">
      <uv-icon name="info-circle-fill" color="#1488DB" size="32"></uv-icon>
      <text class="tip-text">以下内容均为必填项，请根据您的实际情况认真填写！</text>
    </view>
    
    <!-- 表单内容 -->
     <!-- 如何一键禁用整个表单元素 可不可以设置一个大容器 直接禁止内容的任何点击？ -->
      
    <view class="form-section">
      <view v-if="status === '0' || status === '1'" class="overlay"></view>
      <uv-form ref="form" :model="formData" :rules="rules" labelPosition="left" labelWidth="120">
        <!-- 姓名 -->
        <uv-form-item label="姓名" prop="name" borderBottom>
          <uv-input 
            v-model="formData.name" 
            placeholder="请输入您的姓名"
            border="none"
            clearable
          ></uv-input>
        </uv-form-item>
        
        <!-- 手机号 -->
        <uv-form-item label="手机号" prop="phone" borderBottom>
          <uv-input 
            v-model="formData.phone" 
            placeholder="请输入您的手机号"
            border="none"
            clearable
            type="number"
          ></uv-input>
        </uv-form-item>
        
        <!-- 性别 -->
        <uv-form-item label="性别" prop="sex" borderBottom @click="openGenderPicker">
          <uv-input 
            v-model="formData.sex" 
            placeholder="请选择"
            border="none"
            readonly
            
            suffixIcon="arrow-right"
          ></uv-input>
        </uv-form-item>
        
        <!-- 所在地区 -->
        <uv-form-item label="所在地区" prop="area" borderBottom @click="openRegionPicker">
          <uv-input 
            v-model="formData.area" 
            placeholder="请选择"
            border="none"
            readonly
            suffixIcon="arrow-right"
          ></uv-input>
        </uv-form-item>
        
        <!-- 详细地址 -->
        <uv-form-item label="详细地址" prop="address" borderBottom>
          <uv-input 
            v-model="formData.address" 
            placeholder="请输入详细地址"
            border="none"
            clearable
          ></uv-input>
        </uv-form-item>
        
        <!-- 职业类型 -->
        <uv-form-item label="职业类型" prop="career" borderBottom @click="openProfessionPicker">
          <uv-input 
            v-model="formData.career" 
            placeholder="请选择"
            border="none"
            readonly
            suffixIcon="arrow-right"
          ></uv-input>
        </uv-form-item>
        
        <!-- 最高学历 -->
        <uv-form-item label="最高学历" prop="qualifications" borderBottom @click="openEducationPicker">
          <uv-input 
            v-model="formData.qualifications" 
            placeholder="请选择"
            border="none"
            readonly
            suffixIcon="arrow-right"
          ></uv-input>
        </uv-form-item>
        
        <!-- 技能特长 -->
        <uv-form-item label="技能特长" prop="skill">
          <uv-textarea 
            v-model="formData.skill" 
            placeholder="请输入您的技能特长"
            border="none"
            :maxlength="200"
            count
            height="120"
          ></uv-textarea>
        </uv-form-item>
      </uv-form>
      
      <!-- 紧急联系人信息 -->
      <view class="emergency-section">
        <view class="section-title">紧急联系人信息</view>
        
        <uv-form ref="emergencyForm" :model="emergencyData" labelPosition="left" labelWidth="120">
          <!-- 联系人姓名 -->
          <uv-form-item label="姓名" prop="emergencyName" borderBottom>
            <uv-input 
              v-model="emergencyData.emergencyName" 
              placeholder="请输入您的紧急联系人姓名"
              border="none"
              clearable
            ></uv-input>
          </uv-form-item>
          
          <!-- 联系人手机号 -->
          <uv-form-item label="手机号" prop="emergencyPhone" borderBottom>
            <uv-input 
              v-model="emergencyData.emergencyPhone" 
              placeholder="请输入您的紧急联系人手机号"
              border="none"
              clearable
              type="number"
            ></uv-input>
          </uv-form-item>
        </uv-form>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-section">
      <!-- 圆角的 -->

      <!-- 如果还在审核中 按钮无法点击 -->
      <uv-button 
        v-if="status !== '1'"
        type="primary" 
        shape="circle"
        size="large"
        :loading="submitting"
        :disabled="status === '0'"
        @click="submitApplication"
      >
      
        {{statusTips}}
      </uv-button>
    </view>
    
    <!-- 性别选择器 -->
    <uv-picker
      ref="genderPicker"
      :columns="genderOptions"
      @confirm="onGenderConfirm"
    ></uv-picker>
    
    <!-- 地区选择器 -->
    <uv-picker
      ref="regionPicker"
      :columns="addressList"
      @confirm="onAddressConfirm"
      @change="onAddressChange"
      keyName="name"
    ></uv-picker>
    
    <!-- 职业选择器 -->
    <uv-picker
      ref="professionPicker"
      :columns="professionOptions"
      @confirm="onProfessionConfirm"
    ></uv-picker>
    
    <!-- 学历选择器 -->
    <uv-picker
      ref="educationPicker"
      :columns="educationOptions"
      @confirm="onEducationConfirm"
    ></uv-picker>
  </view>
</template>

<script>
import chinaRegions from '@/static/china-regions.json'

export default {
  name: 'VolunteerApply',
  data() {
    return {
      submitting: false,
      
      formData: {
        name: '',
        phone: '',
        sex: '',
        // sexText: '',
        area: '',
        address: '',
        career: '',
        // careerText: '',
        qualifications: '',
        // qualificationsText: '',
        skill: ''
      },
      
      emergencyData: {
        emergencyName: '',
        emergencyPhone: ''
      },
      
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        area: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        career: [{ required: true, message: '请选择职业类型', trigger: 'change' }],
        qualifications: [{ required: true, message: '请选择最高学历', trigger: 'change' }]
      },
      
      // 页面的志愿者状态 0-审核中 1-已通过 2-未通过 3-未申请
      status: '3',

      genderOptions: [['男', '女']],
      
      provinces: [], //省
      citys: [], //市
      areas: [], //区
      pickerValue: [0, 0, 0],
      defaultValue: [3442, 1, 2],
    
    }
  },
  computed: {
    addressList() {
      return [this.provinces, this.citys, this.areas];
    },
    professionOptions() {
      return [this.$store.state.careerList.map(item => item.title)]
    },
    educationOptions() {
      return [this.$store.state.qualificationList.map(item => item.title)]
    },

    // 不同审核状态对应的提示语句
    statusTips() {
      if (this.status === '0') {
        return '您的申请正在审核中，请耐心等待。'
      } else if (this.status === '1') {
        return '恭喜您，志愿者申请已通过！'
      } else if (this.status === '2') {
        return '申请未通过，重新提交申请'
      } else if (this.status === '3') {
        return '申请志愿者'
      }
    }
  },

  async onLoad(options) {
    // 如果是编辑模式，加载已有数据
    if (options.edit && options.data) {
      this.loadExistingData(JSON.parse(decodeURIComponent(options.data)));
    }
    // 查询志愿者信息情况
    const {result:info} = await this.$api.home.queryVolunteer()
    // 审核状态为0或者1时 禁用整个表单元素
    // 审核状态为2时 只禁用提交按钮
    // 审核状态为3时 不禁用
    if (info !== {} && info.status !== null && info.status !== undefined ){
      // 如果有值了 说明申请过志愿者
      this.status = info.status
      // 回显数据
      this.formData = {
        name: info.name,
        phone: info.phone,
        sex: info.sex,
        // sexText: info.sex,
        area: info.area,
        address: info.address,
        career: info.careerName,
        // careerText: info.career,
        qualifications: info.qualificationsName,
        // qualificationsText: info.qualifications,
        skill: info.skill
      }
      // 回显紧急联系人
      this.emergencyData = {
        emergencyName: info.emergencyName,
        emergencyPhone: info.emergencyPhone
      }
    }else{
      this.status = '3'
    }
  },
  created() {
    this.getAddressData()
    // 调试store数据
    // console.log('Store careerList:', this.$store.state.careerList)
    // console.log('Store qualificationList:', this.$store.state.qualificationList)
  },
  methods: {
    // 加载已有数据（编辑模式）
    loadExistingData(data) {
      this.formData = {
        name: data.name || '李双欢',
        phone: data.phone || '15478451233',
        sex: data.sex || '男',
        // sexText: data.sex || '男',
        area: data.area || '湖南省长沙市区',
        areaText: data.area || '湖南省长沙市区',
        address: data.address || '阳光小区45栋二单元1203',
        career: data.career || '专业技术人员',
        // careerText: data.career || '专业技术人员',
        qualifications: data.qualifications || '本科',
        // qualificationsText: data.qualifications || '本科',
        skill: data.skill || '计算机、跑步'
      };
      
      this.emergencyData = {
        emergencyName: data.emergencyName || '李四',
        emergencyPhone: data.emergencyPhone || '14563236320'
      };
    },
    // 初始化地区数据
    getAddressData() {
      console.log('开始加载地区数据');
      try {
        // 直接使用导入的地区数据（已简化，只包含name字段）
        this.provinces = chinaRegions;
        // console.log('成功加载地区数据，省份数量:', this.provinces.length);
        this.handlePickValueDefault();
        // uni.showToast({
        //   title: '地区数据加载成功',
        //   icon: 'success'
        // });
      } catch (error) {
        // console.error('加载地区数据失败:', error);
        // uni.showToast({
        //   title: '地区数据加载失败',
        //   icon: 'error'
        // });
      }
    },
    handlePickValueDefault() {
      if (this.provinces.length > 0) {
        // 设置省（默认选择第一个省份）
        this.pickerValue[0] = 0;
        // 设置市（默认选择第一个市）
        this.citys = this.provinces[0]?.children || [];
        this.pickerValue[1] = 0;
        // 设置区（默认选择第一个区）
        this.areas = this.citys[0]?.children || [];
        this.pickerValue[2] = 0;
        
        console.log('初始化地区数据：', {
          provinces: this.provinces.length,
          citys: this.citys.length,
          areas: this.areas.length
        });
      }
    },
    // 打开性别选择器
    openGenderPicker() {
      // console.log('我点击了性别选择去');
      
      this.$refs.genderPicker.open();
    },
    
    // 打开地区选择器
    openRegionPicker() {
      this.$refs.regionPicker.open();
    },
    
    // 打开职业选择器
    openProfessionPicker() {
      this.$refs.professionPicker.open();
    },
    
    // 打开学历选择器
    openEducationPicker() {
      this.$refs.educationPicker.open();
    },
    
    // 性别选择确认
    onGenderConfirm(value) {
      this.formData.sex = value.value[0];
    },
    
    // 地区选择变化（三级联动）
    onAddressChange(e) {
      console.log('地区选择变化：', e);
      const { columnIndex, index, value } = e;
      
      if (columnIndex === 0) {
        // 选择省份时，更新市级数据
        this.citys = this.provinces[index]?.children || [];
        this.areas = this.citys[0]?.children || [];
        this.pickerValue = [index, 0, 0];
      } else if (columnIndex === 1) {
        // 选择市时，更新区级数据
        this.areas = this.citys[index]?.children || [];
        this.pickerValue[1] = index;
        this.pickerValue[2] = 0;
      } else if (columnIndex === 2) {
        // 选择区
        this.pickerValue[2] = index;
      }
    },
    
    // 地区选择确认
    onAddressConfirm(e) {
      console.log('确认选择的地区：', e);
      if (e.value && e.value.length >= 3) {
        const selectedArea = `${e.value[0].name}/${e.value[1].name}/${e.value[2].name}`;
        this.formData.area = selectedArea;  // 给area字段赋值用于表单验证
        uni.showToast({
          icon: 'success',
          title: '地区选择成功'
        });
      } else {
        uni.showToast({
          icon: 'none',
          title: '请选择完整的省市区信息'
        });
      }
    },
    
    // 职业选择确认
    onProfessionConfirm(value) {
      console.log('职业选择确认：', value.value[0]);
      this.formData.career = value.value[0];
    },
    
    // 学历选择确认
    onEducationConfirm(value) {
      console.log('学历选择确认：', value.value[0]);
      this.formData.qualifications = value.value[0];
    },
    
    // 提交申请
    async submitApplication() {
      try {
        // 验证主表单
        const valid = await this.$refs.form.validate();
        if (!valid) return;
        
        // 验证紧急联系人信息
        if (!this.emergencyData.emergencyName || !this.emergencyData.emergencyPhone) {
          uni.showToast({
            title: '请填写紧急联系人信息',
            icon: 'none'
          });
          return;
        }

        // 电话格式的校验
        if (!this.$utils.checkPhone(this.formData.phone)) {
          uni.showToast({
            title: '请输入正确的电话号码',
            icon: 'none'
          });
          return;
        }

        // 电话格式的校验
        if (!this.$utils.checkPhone(this.emergencyData.emergencyPhone)) {
          uni.showToast({
            title: '请输入正确的紧急联系人电话',
            icon: 'none'
          });
          return;
        }
        
        this.submitting = true;
        
        // 模拟提交
        await this.submitVolunteerApplication();
      } catch (error) {
        console.error('提交失败:', error);
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    },
    
    // 提交志愿者申请API
    async submitVolunteerApplication() {
      // 要求通过title获取id
      const career = this.$store.state.careerList.find(item => item.title === this.formData.career).id
      const qualifications = this.$store.state.qualificationList.find(item => item.title === this.formData.qualifications).id

      const res = await this.$api.home.applyVolunteer({...this.formData, ...this.emergencyData, career, qualifications})
      if (res.code === 200){
        uni.showToast({
          title: `${res.message}`,
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      }else {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }

    }
  }
}
</script>

<style lang="scss" scoped>
// @import '@/uni.scss';
.overlay {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.1);
  z-index: 10;
}
.volunteer-apply-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-section {
  position: relative;
  width: 96%;
  height: 290rpx;
  margin: 25rpx auto;

  .bg-image {
    
    width: 100%;
    height: 100%;

  }
  

}

.tip-section {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .tip-text {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #666;
    line-height: 1.5;
  }
}

.form-section {
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  position: relative;
}

.emergency-section {
  margin-top: 40rpx;
  padding-top: 40rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.submit-section {
  padding: 40rpx 30rpx;
  padding-bottom: 60rpx;
}

// 覆盖uvUI样式
:deep(.uv-form-item__body__right__content__input) {
  font-size: 28rpx !important;
}

:deep(.uv-form-item__body__left__text) {
  font-size: 28rpx !important;
  color: #333 !important;
}

:deep(.uv-input__content__field-wrapper__field) {
  font-size: 28rpx !important;
}

:deep(.uv-textarea__content__field) {
  font-size: 28rpx !important;
}
</style>