import { uploadFile } from '@/api/fulfiller'

export default {
    data() {
        return {
            formData: {
                idType: '居民身份证',
                name: '',
                idNumber: '',
                expiryDate: ''
            },
            idCardFront: '',      // 身份证正面本地预览路径
            idCardBack: '',       // 身份证反面本地预览路径
            idCardFrontOssId: '', // 身份证正面 OSS ID
            idCardBackOssId: '',  // 身份证反面 OSS ID
            showDatePicker: false,
            pickerValue: [0, 0, 0], // YYYY-MM-DD
            years: [],
            months: [],
            days: [],
            serviceType: [] // 接收上一页的服务类型
        }
    },
    onLoad(options) {
        if (options.services) {
            try {
                this.serviceType = JSON.parse(options.services);
            } catch (e) {
                console.error('Parse services failed', e);
            }
        }
        this.initDateData();
        // 从本地缓存恢复实名认证数据（返回上一级再进来时不丢失）
        this.restoreAuthData();
    },
    methods: {
        // --- 日期选择器逻辑 (简化版, 仅示意) ---
        initDateData() {
            const date = new Date();
            const year = date.getFullYear();
            for (let i = year; i <= year + 20; i++) {
                this.years.push(i);
            }
            for (let i = 1; i <= 12; i++) {
                this.months.push(i);
            }
            for (let i = 1; i <= 31; i++) {
                this.days.push(i);
            }
        },
        openDatePicker() {
            // this.showDatePicker = true; 
            // 简单起见，这里可以用 uni.chooseImage 逻辑，但日期通常用 picker
            // 为了完全还原UI的自定义picker，这里先用原生 picker 简化，或者复用 form 的逻辑
            // 鉴于图1是普通的列表选择样式，这里暂时使用普通 picker 或者 input禁用+点击事件
        },
        onDateChange(e) {
            this.formData.expiryDate = e.detail.value;
        },

        // --- 数据持久化（防止返回上一级丢失） ---
        restoreAuthData() {
            try {
                const saved = uni.getStorageSync('recruit_auth_data');
                if (saved) {
                    const d = JSON.parse(saved);
                    this.formData.name = d.name || '';
                    this.formData.idNumber = d.idNumber || '';
                    this.formData.expiryDate = d.expiryDate || '';
                    this.idCardFront = d.idCardFront || '';
                    this.idCardBack = d.idCardBack || '';
                    this.idCardFrontOssId = d.idCardFrontOssId || '';
                    this.idCardBackOssId = d.idCardBackOssId || '';
                }
            } catch (e) {
                console.error('恢复认证数据失败', e);
            }
        },
        saveAuthData() {
            try {
                uni.setStorageSync('recruit_auth_data', JSON.stringify({
                    name: this.formData.name,
                    idNumber: this.formData.idNumber,
                    expiryDate: this.formData.expiryDate,
                    idCardFront: this.idCardFront,
                    idCardBack: this.idCardBack,
                    idCardFrontOssId: this.idCardFrontOssId,
                    idCardBackOssId: this.idCardBackOssId
                }));
            } catch (e) {
                console.error('保存认证数据失败', e);
            }
        },

        // --- 图片上传（选择后自动上传到OSS） ---
        chooseImage(side) {
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: async (res) => {
                    const tempPath = res.tempFilePaths[0];
                    if (side === 'front') {
                        this.idCardFront = tempPath;
                    } else {
                        this.idCardBack = tempPath;
                    }
                    // 上传到OSS
                    try {
                        uni.showLoading({ title: '上传中...' });
                        const uploadRes = await uploadFile(tempPath);
                        if (side === 'front') {
                            this.idCardFrontOssId = uploadRes.data.ossId;
                        } else {
                            this.idCardBackOssId = uploadRes.data.ossId;
                        }
                        uni.hideLoading();
                        this.saveAuthData();
                    } catch (err) {
                        uni.hideLoading();
                        console.error('上传身份证图片失败:', err);
                    }
                }
            });
        },

        // --- 提交 ---
        goToQualifications() {
            // 简单校验
            // 简单校验
            /*
            if (!this.formData.name || !this.formData.idNumber) {
                uni.showToast({ title: '请完善信息', icon: 'none' });
                return;
            }
            if (!this.idCardFront || !this.idCardBack) {
                uni.showToast({ title: '请上传证件照', icon: 'none' });
                return;
            }
            */

            // 保存认证数据到缓存
            this.saveAuthData();

            // 合并身份认证数据到已暂存的招募表单
            try {
                const stored = uni.getStorageSync('recruit_form_data')
                if (stored) {
                    const data = JSON.parse(stored)
                    data.realName = this.formData.name
                    data.idNumber = this.formData.idNumber
                    data.expiryDate = this.formData.expiryDate
                    data.idCardFrontOssId = this.idCardFrontOssId
                    data.idCardBackOssId = this.idCardBackOssId
                    uni.setStorageSync('recruit_form_data', JSON.stringify(data))
                }
            } catch (e) {
                console.error('保存认证数据失败', e)
            }

            // 传递数据
            const services = JSON.stringify(this.serviceType);
            uni.navigateTo({
                url: `/pages/recruit/qualifications?services=${services}`
            });
        }
    }
}
