<template>
  <step-layout 
    title="填写个人信息" 
    :showSkip="!isEditMode"
    @next="goNext" 
    @skip="goSkip">
    
    <view class="form-list">
      <!-- Avatar -->
      <view class="form-item avatar-item" @tap="chooseAvatar">
        <text class="label">头像</text>
        <view class="right-content">
          <text class="hint-text">上传真实头像，你的简历更加分</text>
          <image class="avatar-img" :src="formData.avatarUrl" mode="aspectFill"></image>
          <text class="arrow" />
        </view>
      </view>
      
      <!-- Name -->
      <view class="form-item">
        <text class="label">姓名</text>
        <view class="input-box">
          <input type="text" v-model="formData.name" placeholder="请输入您的真实姓名" placeholder-class="ph-style" />
        </view>
      </view>
      
      <!-- Gender -->
      <view class="form-item">
        <text class="label">性别</text>
        <view class="gender-switch">
          <view :class="['g-slider', genderSliderClass]"></view>
          <view
            v-for="item in genderOptions"
            :key="item.dictValue"
            :class="['g-item', formData.gender === item.dictValue ? 'active' : '']"
            @tap="setGender(item.dictValue)">
            {{ item.dictLabel }}
          </view>
        </view>
      </view>
      
      <!-- ID Card -->
      <view class="form-item">
        <text class="label">身份证号</text>
        <view class="input-box">
          <input type="idcard" v-model="formData.idCard" placeholder="请输入您的身份证号" placeholder-class="ph-style" />
        </view>
      </view>
      
      <!-- Email -->
      <view class="form-item">
        <text class="label">邮箱</text>
        <view class="input-box">
          <input type="text" v-model="formData.email" placeholder="请输入您的邮箱" placeholder-class="ph-style" />
        </view>
      </view>
    </view>
    
  </step-layout>
</template>

<script setup lang="js">
import { computed, reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { updateStudent, getStudent } from '../../api/student';
import { getDicts } from '../../api/dict';
import { UPLOAD_URL } from '../../utils/request';

const isEditMode = ref(false);
const genderOptions = ref([
    { dictLabel: '男', dictValue: '0' },
    { dictLabel: '女', dictValue: '1' }
]);

const normalizeGenderValue = (value) => {
    if (value === undefined || value === null || value === '') {
        return '0';
    }
    const gender = String(value).trim().toUpperCase();
    if (gender === 'M') return '0';
    if (gender === 'F') return '1';
    if (gender === '0' || gender === '1' || gender === '2') return gender;
    return '0';
};

const loadGenderDict = async () => {
    try {
        const res = await getDicts('sys_user_sex');
        const data = res?.data || [];
        if (Array.isArray(data) && data.length > 0) {
            genderOptions.value = data
                .filter(item => item && item.dictValue !== '2')
                .map(item => ({
                    dictLabel: item.dictLabel,
                    dictValue: String(item.dictValue)
                }));
        }
    } catch (error) {
        console.error('加载性别字典失败', error);
    }
};

const genderSliderClass = computed(() => {
    const currentIndex = genderOptions.value.findIndex(item => item.dictValue === formData.gender);
    if (currentIndex <= 0) {
        return currentIndex === 0 ? 'left' : 'none';
    }
    return 'right';
});

onLoad(async (options) => {
    await loadGenderDict();

    if (options.editMode === '1') {
        isEditMode.value = true;
        
        // 从后端获取真实数据进行回显
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo && userInfo.studentId) {
            try {
                uni.showLoading({ title: '加载中...' });
                const res = await getStudent(userInfo.studentId);
                uni.hideLoading();
                
                if (res && res.data) {
                    const data = res.data;
                    Object.assign(formData, {
                        avatarUrl: data.avatarUrl || '/static/images/default-avatar.svg',
                        avatarId: data.avatar || null,
                        name: data.name || '',
                        gender: normalizeGenderValue(data.gender),
                        idCard: data.idCardNumber || '',
                        email: data.email || ''
                    });
                }
            } catch (err) {
                uni.hideLoading();
                console.error('获取用户信息失败', err);
                uni.showToast({ title: '加载数据失败', icon: 'none' });
            }
        }
    }
});

const formData = reactive({
    avatarUrl: '/static/images/default-avatar.svg', // 用于展示
    avatarId: null, // 用于传给后端
    name: '',
    gender: '0',
    idCard: '',
    email: ''
});

const chooseAvatar = () => {
    uni.chooseImage({
        count: 1,
        success: (res) => {
            const tempFilePath = res.tempFilePaths[0];
            formData.avatarUrl = tempFilePath; // 先本地展示
            
            // 执行上传
            uni.showLoading({ title: '上传头像中...' });
            uni.uploadFile({
                url: UPLOAD_URL + '/portal/oss/upload', 
                filePath: tempFilePath,
                name: 'file',
                header: {
                    'clientid': 'e5cd7e4891bf95d1d19206ce24a7b32e',
                    'PLATFORM_CODE': 'PINGTAIDUAN',
                    'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : ''
                },
                success: (uploadFileRes) => {
                    uni.hideLoading();
                    const data = JSON.parse(uploadFileRes.data);
                    if (data.code === 200) {
                        formData.avatarId = data.data.ossId; // 保存返回的ID
                        uni.showToast({ title: '上传成功', icon: 'success' });
                    } else {
                        uni.showToast({ title: data.msg || '上传失败', icon: 'none' });
                    }
                },
                fail: (err) => {
                    uni.hideLoading();
                    console.error('上传失败', err);
                    uni.showToast({ title: '上传失败', icon: 'none' });
                }
            });
        }
    });
};

const setGender = (val) => {
    formData.gender = val;
};

const goNext = async () => {
    // 校验姓名必填
    if (!formData.name) {
        uni.showToast({ title: '请输入您的真实姓名', icon: 'none' });
        return;
    }

    // 校验身份证号格式（如果填写了的话）
    if (formData.idCard) {
        const idCardReg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
        if (!idCardReg.test(formData.idCard)) {
            uni.showToast({ title: '请输入正确的身份证号', icon: 'none' });
            return;
        }
    }

    // 校验邮箱格式（如果填写了的话）
    if (formData.email) {
        const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailReg.test(formData.email)) {
            uni.showToast({ title: '请输入正确的邮箱地址', icon: 'none' });
            return;
        }
    }

    uni.showLoading({ title: '保存中...' });
    
    try {
        const userInfo = uni.getStorageSync('userInfo');
        const studentId = userInfo ? userInfo.studentId : null;

        if (!studentId) {
            uni.hideLoading();
            uni.showToast({ title: '用户信息失效，请重新登录', icon: 'none' });
            return;
        }

        const res = await updateStudent({
            id: studentId,
            name: formData.name,
            gender: formData.gender,
            email: formData.email,
            idCardNumber: formData.idCard,
            avatar: formData.avatarId // 传入上传后的 ossId, 是 Long 类型的
        });

        uni.hideLoading();
        if (res.code === 200) {
            const url = isEditMode.value ? '/pages/experience/experience?editMode=1' : '/pages/experience/experience';
            uni.navigateTo({ url });
        } else {
            uni.showToast({
                title: res.msg || '保存失败',
                icon: 'none'
            });
        }
    } catch (err) {
        uni.hideLoading();
        console.error('保存个人信息异常', err);
        uni.showToast({ title: '网络异常，请重试', icon: 'none' });
    }
};

const goSkip = () => {
    uni.navigateTo({
        url: '/pages/experience/experience'
    });
};
</script>

<style lang="scss" scoped>
@import './profile.scss';
</style>
