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

export default {
    data() {
        return {
            serviceTypes: [], // 从上一页传递过来的服务类型列表
            qualifications: {}, // 存储本地预览路径 { '宠物接送': ['path1', ...], ... }
            qualOssIds: {},    // 存储OSS ID { '宠物接送': ['id1', ...], ... }
        }
    },
    onLoad(options) {
        if (options.services) {
            try {
                this.serviceTypes = JSON.parse(options.services);
                // 初始化 qualifications 对象
                this.serviceTypes.forEach(type => {
                    this.qualifications[type] = [];
                    this.qualOssIds[type] = [];
                });
            } catch (e) {
                console.error('Parse services failed', e);
            }
        }
    },
    methods: {
        chooseImage(serviceName) {
            uni.chooseImage({
                count: 9,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: async (res) => {
                    if (!this.qualifications[serviceName]) {
                        this.qualifications[serviceName] = [];
                        this.qualOssIds[serviceName] = [];
                    }
                    // 逐个上传到OSS
                    for (const tempPath of res.tempFilePaths) {
                        this.qualifications[serviceName].push(tempPath);
                        this.$forceUpdate();
                        try {
                            const uploadRes = await uploadFile(tempPath);
                            this.qualOssIds[serviceName].push(uploadRes.data.ossId);
                        } catch (err) {
                            console.error('上传资质图片失败:', err);
                        }
                    }
                }
            });
        },
        deleteImage(serviceName, index) {
            this.qualifications[serviceName].splice(index, 1);
            if (this.qualOssIds[serviceName]) {
                this.qualOssIds[serviceName].splice(index, 1);
            }
            this.$forceUpdate();
        },
        goBackToForm() {
            // 尝试返回填写页
            const pages = getCurrentPages();
            if (pages.length > 2) {
                uni.navigateBack({
                    delta: 2
                });
            } else {
                // 如果页面栈不够（比如直接进入该页），则重定向
                uni.reLaunch({
                    url: '/pages/recruit/form'
                });
            }
        },
        async submit() {
            // 收集前面页面暂存在本地的表单数据
            let recruitData = {}
            try {
                const stored = uni.getStorageSync('recruit_form_data')
                if (stored) {
                    recruitData = JSON.parse(stored)
                }
            } catch (e) {
                console.error('读取招募表单数据失败', e)
            }

            // 收集所有资质图片OSS ID
            const allQualOssIds = [];
            Object.values(this.qualOssIds).forEach(ids => {
                allQualOssIds.push(...ids);
            });

            // 组装提交数据（匹配 FlfAuditBo 字段）
            const auditData = {
                name: recruitData.name || '',
                phone: recruitData.mobile || '',
                password: recruitData.password || '',
                gender: recruitData.gender === 1 ? '0' : '1',
                birthday: recruitData.birthday || '',
                serviceTypes: JSON.stringify(recruitData.serviceType || []),
                city: recruitData.city || '',
                stationId: recruitData.stationId || null,
                realName: recruitData.realName || '',
                idCard: recruitData.idNumber || '',
                idValidDate: recruitData.expiryDate || '',
                idCardFront: recruitData.idCardFrontOssId || null,
                idCardBack: recruitData.idCardBackOssId || null,
                qualifications: JSON.stringify(allQualOssIds)
            }

            uni.showLoading({ title: '提交中...' })
            try {
                await submitAudit(auditData)
                uni.hideLoading()
                uni.reLaunch({
                    url: '/pages/recruit/success'
                })
            } catch (err) {
                uni.hideLoading()
                console.error('提交申请失败:', err)
            }
        }
    }
}
