<template>
  <view class="edit-auth-container">
    <!-- 自定义头部 -->
    <view class="custom-header">
      <view class="header-left" @click="navBack">
        <image class="back-icon" src="/static/icons/chevron_right_dark.svg" style="transform: rotate(180deg);"></image>
      </view>
      <text class="header-title">修改认证信息</text>
      <view class="header-right"></view>
    </view>
    <view class="header-placeholder"></view>

    <!-- 顶部警告提示 -->
    <view class="warning-tip">
      <text class="warning-icon">⚠</text>
      <text class="warning-text">若修改认证信息，将在审核通过后生效</text>
    </view>

    <!-- 身份认证 -->
    <view class="section-card">
      <view class="section-title">身份认证</view>
      <text class="section-subtitle">点击图片修改</text>
      
      <view class="id-card-row">
        <!-- 身份证正面 -->
        <view class="id-card-upload" @click="chooseImage('front')">
          <image v-if="idCardFront" :src="idCardFront" class="id-card-img" mode="aspectFill"></image>
          <view v-else class="id-card-placeholder">
            <text class="placeholder-text">ID Front</text>
          </view>
          <view class="delete-btn" v-if="idCardFront" @click.stop="deleteImage('front')">×</view>
          <view class="corner-tag">人像面</view>
        </view>

        <!-- 身份证反面 -->
        <view class="id-card-upload" @click="chooseImage('back')">
          <image v-if="idCardBack" :src="idCardBack" class="id-card-img" mode="aspectFill"></image>
          <view v-else class="id-card-placeholder">
            <text class="placeholder-text">ID Back</text>
          </view>
          <view class="delete-btn" v-if="idCardBack" @click.stop="deleteImage('back')">×</view>
          <view class="corner-tag">国徽面</view>
        </view>
      </view>
    </view>

    <!-- 服务类型 -->
    <view class="section-card">
      <view class="section-title">服务类型</view>
      <text class="section-subtitle">可多选</text>
      
      <view class="service-list">
        <view 
          class="service-item" 
          v-for="(service, index) in serviceOptions" 
          :key="service.id"
          @click="toggleService(service)"
        >
          <text class="service-name">{{ service.name }}</text>
          <view class="check-icon" :class="{ active: selectedServices.map(String).includes(String(service.id)) }">
            <text v-if="selectedServices.map(String).includes(String(service.id))">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 资质证书 -->
    <view class="section-card">
      <view class="section-title">资质证书</view>
      <text class="section-subtitle">请上传对应服务的资质</text>
      
      <!-- 动态渲染每个服务类型的资质上传 -->
      <view v-for="(serviceId, index) in selectedServices" :key="serviceId" class="qual-section">
        <text class="qual-title">{{ getServiceName(serviceId) }}资质</text>
        
        <view class="qual-upload-row">
          <!-- 已上传的资质图片 -->
          <view 
            class="qual-item" 
            v-for="(img, imgIndex) in qualifications[getServiceName(serviceId)]" 
            :key="imgIndex"
            @click="previewImage(getServiceName(serviceId), imgIndex)"
          >
            <image :src="img" class="qual-img" mode="aspectFill"></image>
            <view class="delete-btn" @click.stop="deleteQualImage(getServiceName(serviceId), imgIndex)">×</view>
          </view>
          
          <!-- 上传按钮 -->
          <view class="qual-upload-btn" @click="chooseQualImage(getServiceName(serviceId))">
            <text class="plus-icon">+</text>
          </view>
        </view>
      </view>

      <text v-if="selectedServices.length === 0" class="empty-hint">请先选择服务类型</text>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-btn-area">
      <button class="submit-btn" @click="submitAuth">提交审核</button>
    </view>
  </view>
</template>

<script>
import { getAuthInfo, updateAuthInfo } from '@/api/fulfiller/fulfiller'
import { uploadFile, getServiceTypes } from '@/api/fulfiller/app'

export default {
  data() {
    return {
      idCardFront: '',
      idCardBack: '',
      idCardFrontOssId: '',
      idCardBackOssId: '',
      serviceOptions: [],
      selectedServices: [],
      qualifications: {},
      qualOssIds: {}
    }
  },
  async onLoad() {
    await this.loadServiceOptions()
    this.loadAuthInfo()
  },
  methods: {
    async loadServiceOptions() {
      try {
        const res = await getServiceTypes()
        this.serviceOptions = (res.data || []).map(item => ({
          id: String(item.id),
          name: item.name
        }))
      } catch (e) {
        console.error('加载服务类型失败', e)
        uni.showToast({ title: e.message || e.msg || '请求失败', icon: 'none' })
      }
    },
    async loadAuthInfo() {
      try {
        uni.showLoading({ title: '加载中...' })
        const res = await getAuthInfo()
        if (res.code === 200 && res.data) {
          this.idCardFront = res.data.idCardFrontUrl || ''
          this.idCardBack = res.data.idCardBackUrl || ''
          this.idCardFrontOssId = res.data.idCardFront || ''
          this.idCardBackOssId = res.data.idCardBack || ''
          // 解析服务类型ID列表（逗号分隔，去重）
          let serviceIds = []
          if (res.data.serviceTypes) {
            serviceIds = [...new Set(
              String(res.data.serviceTypes).replace(/[\[\]"']/g, '').split(',')
                .map(s => s.trim())
                .filter(id => id && id !== '0' && id !== 'null' && id !== 'undefined')
            )]
          }
          this.selectedServices = serviceIds
          
          // 解析资质图片URL和OSS ID
          const qualUrlList = res.data.qualImageUrls ? res.data.qualImageUrls.split(',').filter(Boolean) : []
          const qualOssIdList = res.data.qualImages ? res.data.qualImages.replace(/[\[\]"]/g, '').split(',').map(s => s.trim()).filter(Boolean) : []
          
          // 收集有效的服务名称列表
          const validNames = serviceIds.map(sid => this.getServiceName(sid)).filter(Boolean)
          
          // 为每个已选服务类型初始化资质数据，并均匀分配已有图片
          validNames.forEach((name, idx) => {
            // 将已有资质图片按服务类型数量均匀分配
            const start = Math.floor(idx * qualUrlList.length / validNames.length)
            const end = Math.floor((idx + 1) * qualUrlList.length / validNames.length)
            this.$set(this.qualifications, name, qualUrlList.slice(start, end))
            this.$set(this.qualOssIds, name, qualOssIdList.slice(start, end))
          })
        }
        uni.hideLoading()
      } catch (e) {
        uni.hideLoading()
        console.error('加载认证信息失败', e)
        uni.showToast({ title: e.message || '加载失败', icon: 'none' })
      }
    },
    navBack() {
      uni.navigateBack({ delta: 1 })
    },
    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
          }
          
          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()
            uni.showToast({ title: '上传成功', icon: 'success' })
          } catch (err) {
            uni.hideLoading()
            console.error('上传身份证图片失败:', err)
            uni.showToast({ title: err.message || '上传失败', icon: 'none' })
          }
        }
      })
    },
    deleteImage(side) {
      if (side === 'front') {
        this.idCardFront = ''
        this.idCardFrontOssId = ''
      } else {
        this.idCardBack = ''
        this.idCardBackOssId = ''
      }
    },
    getServiceName(serviceId) {
      const found = this.serviceOptions.find(s => String(s.id) === String(serviceId))
      return found ? found.name : ''
    },
    toggleService(service) {
      const index = this.selectedServices.indexOf(service.id)
      if (index > -1) {
        this.selectedServices.splice(index, 1)
        this.$delete(this.qualifications, service.name)
        this.$delete(this.qualOssIds, service.name)
      } else {
        this.selectedServices.push(service.id)
        this.$set(this.qualifications, service.name, [])
        this.$set(this.qualOssIds, service.name, [])
      }
      this.$forceUpdate()
    },
    chooseQualImage(service) {
      uni.chooseImage({
        count: 9,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          if (!this.qualifications[service]) {
            this.qualifications[service] = []
            this.qualOssIds[service] = []
          }
          
          for (const tempPath of res.tempFilePaths) {
            this.qualifications[service].push(tempPath)
            this.$forceUpdate()
            
            try {
              uni.showLoading({ title: '上传中...' })
              const uploadRes = await uploadFile(tempPath)
              this.qualOssIds[service].push(uploadRes.data.ossId)
              uni.hideLoading()
            } catch (err) {
              uni.hideLoading()
              console.error('上传资质图片失败:', err)
              uni.showToast({ title: err.message || err.msg || '请求失败', icon: 'none' })
            }
          }
        }
      })
    },
    deleteQualImage(service, index) {
      this.qualifications[service].splice(index, 1)
      if (this.qualOssIds[service]) {
        this.qualOssIds[service].splice(index, 1)
      }
      this.$forceUpdate()
    },
    previewImage(service, index) {
      uni.previewImage({
        urls: this.qualifications[service],
        current: index
      })
    },
    async submitAuth() {
      if (!this.idCardFront || !this.idCardBack) {
        uni.showToast({ title: '请上传身份证正反面', icon: 'none' })
        return
      }
      
      if (this.selectedServices.length === 0) {
        uni.showToast({ title: '请选择服务类型', icon: 'none' })
        return
      }
      
      for (const serviceId of this.selectedServices) {
        const name = this.getServiceName(serviceId)
        if (!this.qualifications[name] || this.qualifications[name].length === 0) {
          uni.showToast({ title: `请上传${name}资质`, icon: 'none' })
          return
        }
      }
      
      uni.showModal({
        title: '提示',
        content: '修改认证信息需要重新审核，审核期间无法接单，确定要继续吗？',
        success: (res) => {
          if (res.confirm) {
            this.doSubmit()
          }
        }
      })
    },
    async doSubmit() {
      const allQualOssIds = []
      Object.values(this.qualOssIds).forEach(ids => {
        allQualOssIds.push(...ids)
      })
      
      const submitData = {
        idCardFront: this.idCardFrontOssId,
        idCardBack: this.idCardBackOssId,
        serviceTypes: this.selectedServices.join(','),  // 逗号分隔的服务类型ID
        qualifications: allQualOssIds.join(',')  // 逗号分隔的资质图片OSS ID
      }
      
      try {
        uni.showLoading({ title: '提交中...' })
        await updateAuthInfo(submitData)
        uni.hideLoading()
        uni.showToast({ title: '提交成功，等待审核', icon: 'none', duration: 2000 })
        setTimeout(() => {
          uni.navigateBack({ delta: 1 })
        }, 1500)
      } catch (err) {
        uni.hideLoading()
        console.error('提交失败:', err)
        uni.showToast({ title: err.message || '提交失败', icon: 'none' })
      }
    }
  }
}
</script>

<style scoped>
page {
  background-color: #F8F8F8;
}

.custom-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 88rpx;
  padding-top: var(--status-bar-height);
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 30rpx;
  padding-right: 30rpx;
  box-sizing: content-box;
  z-index: 100;
}

.header-placeholder {
  height: calc(88rpx + var(--status-bar-height));
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

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

.header-right {
  width: 40rpx;
}

.edit-auth-container {
  padding: 20rpx 30rpx;
  padding-bottom: 180rpx;
}

.warning-tip {
  background: linear-gradient(90deg, #FFF3E0 0%, #FFE0B2 100%);
  border-radius: 16rpx;
  padding: 24rpx 30rpx;
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.warning-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
}

.warning-text {
  font-size: 26rpx;
  color: #E65100;
  flex: 1;
}

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

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.section-subtitle {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 30rpx;
}

.id-card-row {
  display: flex;
  justify-content: space-between;
}

.id-card-upload {
  width: 48%;
  height: 200rpx;
  border-radius: 16rpx;
  position: relative;
  overflow: hidden;
  background-color: #E8F5E9;
}

.id-card-img {
  width: 100%;
  height: 100%;
}

.id-card-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-text {
  font-size: 36rpx;
  color: #4CAF50;
  font-weight: bold;
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(255, 87, 34, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
}

.corner-tag {
  position: absolute;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 10rpx;
  border-top-left-radius: 8rpx;
}

.service-list {
  display: flex;
  flex-direction: column;
}

.service-item {
  background-color: #FFF8E1;
  border-radius: 16rpx;
  padding: 24rpx 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.service-item:last-child {
  margin-bottom: 0;
}

.service-name {
  font-size: 28rpx;
  color: #333;
}

.check-icon {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #FF9800;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 24rpx;
}

.check-icon.active {
  background-color: #FF9800;
}

.qual-section {
  margin-top: 30rpx;
}

.qual-section:first-child {
  margin-top: 0;
}

.qual-title {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 20rpx;
}

.qual-upload-row {
  display: flex;
  flex-wrap: wrap;
}

.qual-item {
  width: 150rpx;
  height: 150rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  position: relative;
  overflow: hidden;
}

.qual-img {
  width: 100%;
  height: 100%;
}

.qual-upload-btn {
  width: 150rpx;
  height: 150rpx;
  border-radius: 12rpx;
  border: 2rpx dashed #ccc;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #F5F5F5;
}

.plus-icon {
  font-size: 60rpx;
  color: #999;
}

.empty-hint {
  font-size: 26rpx;
  color: #999;
  text-align: center;
  display: block;
  padding: 40rpx 0;
}

.bottom-btn-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 40rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  z-index: 99;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background-color: #FF5722;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  border: none;
  line-height: 88rpx;
  text-align: center;
  margin: 0 auto;
  padding: 0;
}
</style>
