<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">
      <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 
        type="primary" 
        shape="circle"
        size="large"
        :loading="submitting"
        @click="submitApplication"
      >
        提交申请
      </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' }]
      },
      
      genderOptions: [['男', '女']],
      
      provinces: [], //省
      citys: [], //市
      areas: [], //区
      pickerValue: [0, 0, 0],
      defaultValue: [3442, 1, 2],
      
      // professionOptions: [[
      //   '学生', '教师', '医生', '工程师', '设计师', '销售', 
      //   '服务员', '公务员', '自由职业', '专业技术人员', '其他'
      // ]],
      
      // educationOptions: [[
      //   '高中及以下', '大专', '本科', '硕士', '博士'
      // ]]
    }
  },
  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)]
    },
  },
  onLoad(options) {
    // 如果是编辑模式，加载已有数据
    if (options.edit && options.data) {
      this.loadExistingData(JSON.parse(decodeURIComponent(options.data)));
    }
  },
  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;
        }
        
        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
      this.formData.career = this.$store.state.careerList.find(item => item.title === this.formData.career).id
      this.formData.qualifications = this.$store.state.qualificationList.find(item => item.title === this.formData.qualifications).id

      const res = await this.$api.home.applyVolunteer({...this.formData, ...this.emergencyData})
      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';

.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);
}

.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>