<template>
  <view class="qual-container">
    <!-- 顶部提示 -->
    <view class="top-tip">根据国家政策要求，请尽快完成实名认证与健康认证，否则无法开展配送业务。我们承诺将严格保管好您的个人信息。</view>

    <!-- 如果没有选择服务类型 -->
    <view class="empty-state" v-if="serviceTypes.length === 0">
      <text class="empty-tip">请返回第一步选择服务类型</text>
      <button class="back-btn" @click="goBackToForm">返回选择</button>
    </view>

    <!-- 动态渲染资质卡片 -->
    <view class="qual-card" v-for="(item, index) in serviceTypes" :key="item.id">
      <view class="card-title">{{ item.name }}服务资质</view>

      <view class="upload-wrapper">
        <!-- 已有图片列表 -->
        <view class="img-item" v-for="(img, imgIndex) in qualifications[item.name]" :key="imgIndex">
          <image :src="img" class="preview-img" mode="aspectFill" @click="previewImage(item.name, imgIndex)"></image>
          <view class="delete-btn" @click.stop="deleteImage(item.name, imgIndex)">×</view>
        </view>

        <!-- 上传/添加按钮 -->
        <view class="upload-box" @click="chooseImage(item.name)">
          <text class="plus-icon">+</text>
          <text class="upload-text">上传</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer-actions">
      <button class="submit-btn" @click="submit">立即提交</button>
    </view>

  </view>
</template>

<script>
import { submitAudit, uploadFile } from '@/api/fulfiller/app'

export default {
  data() {
    return {
      serviceTypes: [],
      qualifications: {},
      qualOssIds: {},
    }
  },
  onLoad(options) {
    if (options.services) {
      try {
        this.serviceTypes = JSON.parse(decodeURIComponent(options.services));
        this.serviceTypes.forEach(item => {
          this.qualifications[item.name] = this.qualifications[item.name] || [];
          this.qualOssIds[item.name] = this.qualOssIds[item.name] || [];
        });
      } catch (e) { console.error('Parse services failed', e); uni.showToast({ title: e.message || e.msg || '请求失败', icon: 'none' }); }
    }
    this.restoreQualData();
  },
  methods: {
    saveQualData() {
      try { uni.setStorageSync('recruit_qual_data', JSON.stringify({ qualifications: this.qualifications, qualOssIds: this.qualOssIds })); }
      catch (e) { console.error('保存资质数据失败', e); uni.showToast({ title: e.message || e.msg || '请求失败', icon: 'none' }); }
    },
    restoreQualData() {
      try {
        const saved = uni.getStorageSync('recruit_qual_data');
        if (saved) { const d = JSON.parse(saved); this.qualifications = d.qualifications || {}; this.qualOssIds = d.qualOssIds || {}; this.$forceUpdate(); }
      } catch (e) { console.error('恢复资质数据失败', e); uni.showToast({ title: e.message || e.msg || '请求失败', icon: 'none' }); }
    },
    chooseImage(serviceName) {
      uni.chooseImage({
        count: 6, sizeType: ['compressed'], sourceType: ['album', 'camera'],
        success: async (res) => {
          if (!this.qualifications[serviceName]) { this.qualifications[serviceName] = []; this.qualOssIds[serviceName] = []; }
          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); this.saveQualData(); }
            catch (err) { console.error('上传资质图片失败:', err); uni.showToast({ title: err.message || err.msg || '上传失败', icon: 'none' }); }
          }
        }
      });
    },
    deleteImage(serviceName, index) {
      this.qualifications[serviceName].splice(index, 1);
      if (this.qualOssIds[serviceName]) this.qualOssIds[serviceName].splice(index, 1);
      this.saveQualData(); this.$forceUpdate();
    },
    goBackToForm() {
      const pages = getCurrentPages();
      if (pages.length > 2) uni.navigateBack({ delta: 2 });
      else uni.reLaunch({ url: '/pages/recruit/form/index' });
    },
    previewImage(serviceName, index) {
      const urls = this.qualifications[serviceName] || [];
      uni.previewImage({ current: index, urls });
    },
    async submit() {
      let recruitData = {};
      try { const stored = uni.getStorageSync('recruit_form_data'); if (stored) recruitData = JSON.parse(stored); }
      catch (e) { console.error('读取招募表单数据失败', e); uni.showToast({ title: e.message || e.msg || '请求失败', icon: 'none' }); }
      const allQualOssIds = [];
      Object.values(this.qualOssIds).forEach(ids => allQualOssIds.push(...ids));
      const auditData = {
        name: recruitData.name || '', phone: recruitData.mobile || '', password: recruitData.password || '',
        gender: recruitData.gender === 1 ? '0' : '1', birthday: recruitData.birthday || '',
        serviceTypes: (recruitData.serviceType || []).join(','), city: recruitData.areaPath || '',
        stationId: recruitData.stationId || null, realName: recruitData.realName || '',
        idCard: recruitData.idNumber || '', idValidDate: recruitData.expiryDate || '',
        idCardFront: recruitData.idCardFrontOssId || null, idCardBack: recruitData.idCardBackOssId || null,
        qualifications: allQualOssIds.join(',')
      };
      uni.showLoading({ title: '提交中...' });
      try {
        await submitAudit(auditData); uni.hideLoading();
        const s = encodeURIComponent(recruitData.station || '');
        const n = encodeURIComponent(recruitData.name || '');
        const p = recruitData.mobile || '';
        uni.removeStorageSync('recruit_form_data'); uni.removeStorageSync('recruit_auth_data'); uni.removeStorageSync('recruit_qual_data');
        uni.reLaunch({ url: `/pages/recruit/success/index?station=${s}&name=${n}&phone=${p}` });
      } catch (err) { uni.hideLoading(); console.error('提交申请失败:', err); uni.showToast({ title: err.message || err.msg || '提交失败', icon: 'none' }); }
    }
  }
}
</script>

<style>
page {
  background-color: #F8F8F8;
  padding-bottom: 200rpx;
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Segoe UI, Arial, Roboto, 'PingFang SC', 'miui', 'Hiragino Sans GB', 'Microsoft Yahei', sans-serif;
}

.qual-container {
  padding: 20rpx;
}

.top-tip {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 20rpx;
  padding: 0 10rpx;
  line-height: 1.5;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 100rpx;
  padding-bottom: 60rpx;
}

.empty-tip {
  font-size: 30rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.back-btn {
  width: 300rpx;
  height: 80rpx;
  line-height: 80rpx;
  border: 2rpx solid #FF5722;
  color: #FF5722;
  background-color: #fff;
  border-radius: 40rpx;
  font-size: 30rpx;
}

.qual-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.card-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.upload-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.img-item {
  width: 200rpx;
  height: 200rpx;
  position: relative;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.upload-box {
  width: 200rpx;
  height: 200rpx;
  background-color: #F8F8F8;
  border: 2rpx dashed #eee;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}

.plus-icon {
  font-size: 60rpx;
  color: #ccc;
  font-weight: 300;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.preview-img {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.delete-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 36rpx;
  height: 36rpx;
  background-color: #FF5722;
  border-radius: 50%;
  color: #fff;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  border: 2rpx solid #fff;
}

.footer-actions {
  margin-top: 60rpx;
  padding: 0 20rpx;
}

.submit-btn {
  background: linear-gradient(90deg, #FF6F00 0%, #FF5722 100%);
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  box-shadow: 0 10rpx 20rpx rgba(255, 87, 34, 0.2);
}

.submit-btn::after {
  border: none;
}
</style>
