<template>
  <view class="edit-profile">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="handleBack">
        <text class="back-icon">←</text>
      </view>
      <text class="header-title">编辑资料</text>
      <view class="right-empty"></view>
    </view>

    <scroll-view scroll-y class="content">
      <!-- 头像展示区域（不可修改） -->
      <view class="avatar-section">
        <view class="avatar-container">
          <image class="avatar" :src="userInfo.avatar || defaultAvatar" mode="aspectFill"></image>
        </view>
        <text class="avatar-text">头像由平台统一设置，暂不支持修改</text>
      </view>

      <!-- 表单区域 -->
      <view class="form-section">
        <!-- 真实姓名 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-icon">👤</text>
            <text class="label-text">真实姓名</text>
          </view>
          <input
              class="form-input"
              v-model="userInfo.real_name"
              placeholder="请输入真实姓名"
              placeholder-style="color: #999"
          >
        </view>

        <!-- 性别 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-icon">⚧️</text>
            <text class="label-text">性别</text>
          </view>
          <picker class="form-picker gender-picker" @change="handleGenderChange" :value="genderIndex"
                  :range="genderOptions">
            <view class="picker-content">
              {{ genderLabel }}
            </view>
          </picker>
        </view>

        <!-- 出生日期 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-icon">📅</text>
            <text class="label-text">出生日期</text>
          </view>
          <picker class="form-picker" mode="date" :value="userInfo.birth_date" @change="handleBirthChange">
            <view class="picker-content">
              {{ userInfo.birth_date || '请选择出生日期' }}
            </view>
          </picker>
        </view>

        <!-- 邮箱 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-icon">📧</text>
            <text class="label-text">邮箱</text>
          </view>
          <input
              class="form-input"
              v-model="userInfo.email"
              placeholder="请输入邮箱"
              placeholder-style="color: #999"
              type="email"
          >
        </view>

        <!-- 所在地区 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-icon">📍</text>
            <text class="label-text">所在地区</text>
          </view>
          <picker
              class="form-picker"
              mode="multiSelector"
              :value="multiIndex"
              :range="multiArray"
              @columnchange="handleColumnChange"
              @change="handleMultiPickerChange"
          >
            <view class="picker-content">{{ selectedArea || '请选择地区' }}</view>
          </picker>
        </view>

        <!-- 详细地址 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-icon">🏠</text>
            <text class="label-text">详细地址</text>
          </view>
          <textarea
              class="form-textarea"
              v-model="userInfo.address_detail"
              placeholder="请输入详细地址"
              placeholder-style="color: #999"
              maxlength="255"
              auto-height
          ></textarea>
        </view>

        <!-- 个人简介 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-icon">📝</text>
            <text class="label-text">个人简介</text>
          </view>
          <textarea
              class="form-textarea"
              v-model="userInfo.profile"
              placeholder="请输入个人简介"
              placeholder-style="color: #999"
              maxlength="200"
              auto-height
          ></textarea>
        </view>
      </view>

      <!-- 保存按钮 -->
      <view class="save-btn-section">
        <button class="save-btn" @click="handleSave">保存</button>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import api from '../../utils/api.js'

export default {
  data() {
    return {
      // 默认头像
      defaultAvatar: 'https://q.qlogo.cn/qqapp/1105591438/05E13358B43B3D39D6AC2D6888828201/100',

      // 用户信息（与后端字段基本对应）
      userInfo: {
        avatar: '',
        real_name: '',
        gender: null, // 1: 男, 2: 女
        birth_date: '',
        email: '',
        province_id: null,
        city_id: null,
        area_id: null,
        address_detail: '',
        province_name: '',
        city_name: '',
        area_name: '',
        profile: ''
      },
      // 当前红娘ID（用于更新）
      matchmakerId: null,

      // 省市区多列选择器数据（名称数组）
      multiArray: [
        [], // 省
        [], // 市
        []  // 区
      ],
      multiIndex: [0, 0, 0],
      selectedArea: '',
      // 后端返回的省市区原始列表（包含id和name）
      provinces: [],
      cities: [],
      areas: [],

      // 性别选项
      genderOptions: ['男', '女'],
      genderIndex: -1
    }
  },
  computed: {
    genderLabel() {
      if (this.userInfo.gender === 1) return '男'
      if (this.userInfo.gender === 2) return '女'
      return '请选择性别'
    }
  },
  onLoad() {
    this.initPage()
  },
  methods: {
    async initPage() {
      await this.loadUserInfo()
      await this.loadProvincesAndInit()
    },

    // 加载红娘资料
    async loadUserInfo() {
      try {
        const basicUser = uni.getStorageSync('userInfo')
        const userId = basicUser && basicUser.userId ? basicUser.userId : null
        if (!userId) {
          uni.showToast({ title: '未登录，无法加载资料', icon: 'none' })
          return
        }

        const matchmakerInfo = await api.matchmaker.getByUserId(userId)
        if (matchmakerInfo) {
          // 映射后端字段到本地表单
          this.matchmakerId = matchmakerInfo.matchmakerId || matchmakerInfo.matchmaker_id || null
          this.userInfo.avatar = matchmakerInfo.avatar_url || ''
          this.userInfo.real_name = matchmakerInfo.real_name || ''
          this.userInfo.gender = typeof matchmakerInfo.gender === 'number' ? matchmakerInfo.gender : null
          this.userInfo.birth_date = matchmakerInfo.birth_date || ''
          this.userInfo.email = matchmakerInfo.email || ''
          this.userInfo.address_detail = matchmakerInfo.address_detail || ''
          this.userInfo.province_id = matchmakerInfo.province_id || null
          this.userInfo.city_id = matchmakerInfo.city_id || null
          this.userInfo.area_id = matchmakerInfo.area_id || null
          this.userInfo.province_name = matchmakerInfo.province_name || ''
          this.userInfo.city_name = matchmakerInfo.city_name || ''
          this.userInfo.area_name = matchmakerInfo.area_name || ''
          this.userInfo.profile = matchmakerInfo.profile || ''

          // 性别索引
          if (this.userInfo.gender === 1) this.genderIndex = 0
          else if (this.userInfo.gender === 2) this.genderIndex = 1

          // 如果后端返回了省市区名称，直接使用
          if (matchmakerInfo.province_name && matchmakerInfo.city_name && matchmakerInfo.area_name) {
            this.selectedArea = `${matchmakerInfo.province_name} ${matchmakerInfo.city_name} ${matchmakerInfo.area_name}`
          }
        }
      } catch (e) {
      
        uni.showToast({ title: '加载资料失败', icon: 'none' })
      }
    },
    // 从后端加载省列表并根据已有省市区初始化
    async loadProvincesAndInit() {
      try {
        const list = await api.area.getProvinces()
        this.provinces = list || []
        this.multiArray[0] = this.provinces.map(p => p.name)

        if (this.userInfo.province_id) {
          const pIndex = this.provinces.findIndex(p => p.id === this.userInfo.province_id)
          if (pIndex >= 0) {
            this.multiIndex[0] = pIndex
            await this.updateCityList(pIndex, true)
          }
        }
      } catch (e) {
        
      }
    },

    // 更新城市列表（根据省索引），init 表示是否按已有 city_id 初始化
    async updateCityList(provinceIndex, init = false) {
      const province = this.provinces[provinceIndex]
      if (!province) return
      try {
        const list = await api.area.getCities(province.id)
        this.cities = list || []
        this.multiArray[1] = this.cities.map(c => c.name)
        this.multiArray[2] = []
        this.multiIndex[1] = 0
        this.multiIndex[2] = 0

        if (init && this.userInfo.city_id) {
          const cIndex = this.cities.findIndex(c => c.id === this.userInfo.city_id)
          if (cIndex >= 0) {
            this.multiIndex[1] = cIndex
            await this.updateAreaList(provinceIndex, cIndex, true)
          }
        }
      } catch (e) {
    
      }
    },

    // 更新区县列表
    async updateAreaList(provinceIndex, cityIndex, init = false) {
      const city = this.cities[cityIndex]
      if (!city) return
      try {
        const list = await api.area.getAreas(city.id)
        this.areas = list || []
        this.multiArray[2] = this.areas.map(a => a.name)
        this.multiIndex[2] = 0

        if (init && this.userInfo.area_id) {
          const aIndex = this.areas.findIndex(a => a.id === this.userInfo.area_id)
          if (aIndex >= 0) {
            this.multiIndex[2] = aIndex
          }
        }
      } catch (e) {
        
      }
    },

    // 处理列变化
    handleColumnChange(e) {
      const column = e.detail.column
      const value = e.detail.value
      this.multiIndex[column] = value

      // 根据列索引更新对应的数据
      if (column === 0) {
        // 省份变化，更新城市和区县
        this.updateCityList(value, false)
      } else if (column === 1) {
        // 城市变化，更新区县
        this.updateAreaList(this.multiIndex[0], value, false)
      }
    },

    // 处理多列选择器确认
    handleMultiPickerChange(e) {
      this.multiIndex = e.detail.value
      const p = this.provinces[this.multiIndex[0]]
      const c = this.cities[this.multiIndex[1]]
      const a = this.areas[this.multiIndex[2]]

      const provinceName = p ? p.name : ''
      const cityName = c ? c.name : ''
      const areaName = a ? a.name : ''

      this.selectedArea = provinceName && cityName && areaName
        ? `${provinceName} ${cityName} ${areaName}`
        : ''

      // 更新用户信息中的 id 和名称
      this.userInfo.province_id = p ? p.id : null
      this.userInfo.city_id = c ? c.id : null
      this.userInfo.area_id = a ? a.id : null
      this.userInfo.province_name = provinceName
      this.userInfo.city_name = cityName
      this.userInfo.area_name = areaName
    },

    // 返回上一页
    async handleBack() {
      uni.navigateBack({
        delta: 1
      })
    },

    // 性别选择变化
    handleGenderChange(e) {
      const index = Number(e.detail.value)
      this.genderIndex = index
      this.userInfo.gender = index >= 0 ? index + 1 : null
    },

    // 出生日期选择
    handleBirthChange(e) {
      this.userInfo.birth_date = e.detail.value
    },

    // 保存资料
    async handleSave() {
      // 验证表单
      if (!this.userInfo.real_name) {
        uni.showToast({
          title: '请输入真实姓名',
          icon: 'none'
        })
        return
      }

      if (!this.userInfo.gender) {
        uni.showToast({
          title: '请选择性别',
          icon: 'none'
        })
        return
      }

      // 简单邮箱格式校验（若填写）
      if (this.userInfo.email) {
        const emailRegex = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
        if (!emailRegex.test(this.userInfo.email)) {
          uni.showToast({ title: '邮箱格式不正确', icon: 'none' })
          return
        }
      }

      try {
        if (!this.matchmakerId) {
          uni.showToast({ title: '红娘信息缺失，无法保存', icon: 'none' })
          return
        }

        const payload = {
          // 注意：后端 Jackson 使用了 SNAKE_CASE 策略
          // email、gender、profile 名字不变，其他字段用下划线命名
          email: this.userInfo.email,
          real_name: this.userInfo.real_name,
          gender: this.userInfo.gender,
          birth_date: this.userInfo.birth_date,
          address_detail: this.userInfo.address_detail,
          province_id: this.userInfo.province_id,
          city_id: this.userInfo.city_id,
          area_id: this.userInfo.area_id,
          profile: this.userInfo.profile
        }

        await api.matchmaker.updateProfile(this.matchmakerId, payload)

        uni.showToast({
          title: '资料保存成功',
          icon: 'success'
        })

        setTimeout(() => {
          this.handleBack()
        }, 1200)
      } catch (e) {
        
        uni.showToast({ title: '保存失败，请稍后重试', icon: 'none' })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-profile {
  min-height: 100vh;
  background: #FFFFFF;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 25rpx 30rpx;
  padding-top: calc(25rpx + env(safe-area-inset-top));
  background: #FFFFFF;
  border-bottom: 1rpx solid #F0F0F0;

  .back-btn {
    width: 44rpx;
    height: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .back-icon {
      font-size: 40rpx;
      color: #333;
    }
  }

  .header-title {
    font-size: 38rpx;
    font-weight: bold;
    color: #333;
  }

  .right-empty {
    width: 44rpx;
  }
}

.content {
  flex: 1;
  padding-bottom: 40rpx;
}

/* 头像上传区域 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  border-bottom: 1rpx solid #F0F0F0;

  .avatar-container {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    margin-bottom: 20rpx;

    .avatar {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background: #F5F5F5;
    }

    .avatar-upload-btn {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 48rpx;
      height: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #FFFFFF;
      border: 2rpx solid #E91E63;
      border-radius: 50%;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

      .upload-icon {
        font-size: 28rpx;
        color: #E91E63;
      }
    }
  }

  .avatar-text {
    font-size: 28rpx;
    color: #E91E63;
    font-weight: 500;
  }
}

/* 表单区域 */
.form-section {
  padding: 0 30rpx;

  .form-item {
    display: flex;
    flex-direction: column;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #F5F5F5;

    &:last-child {
      border-bottom: none;
    }

    .form-label {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;

      .label-icon {
        font-size: 28rpx;
        margin-right: 12rpx;
      }

      .label-text {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }

    .form-input,
    .form-picker {
      width: 90%;
      font-size: 28rpx;
      color: #333;
      padding: 18rpx 20rpx;
      background: #F9F9F9;
      border-radius: 12rpx;
      border: 1rpx solid #E0E0E0;

      &.readonly {
        background: #F5F5F5;
        color: #999;
      }
    }

    .form-picker {
      display: flex;
      align-items: center;

      .picker-content {
        flex: 1;
      }
    }

    /* 性别选择器特定样式 */
    .gender-picker {
      width: 25%;
    }

    .form-textarea {
      width: 90%;
      font-size: 28rpx;
      color: #333;
      padding: 20rpx;
      background: #F9F9F9;
      border-radius: 12rpx;
      border: 1rpx solid #E0E0E0;
      min-height: 160rpx;
      line-height: 1.5;
    }
  }
}

/* 保存按钮 */
.save-btn-section {
  padding: 40rpx 30rpx;

  .save-btn {
    width: 100%;
    height: 90rpx;
    background: linear-gradient(135deg, #E91E63 0%, #FF6B8A 100%);
    color: #FFFFFF;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 45rpx;
    border: none;
    box-shadow: 0 6rpx 20rpx rgba(233, 30, 99, 0.3);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
      box-shadow: 0 3rpx 10rpx rgba(233, 30, 99, 0.2);
    }
  }
}
</style>