<template>
  <view>
    <add-component v-for="(item, index) in addInfoArr" :key="index"
      :ref="el => { if (el) addComponentRef[index] = el }"></add-component>
    <view class="Wrapper-Btn">
      <up-button @click="handleQux" type="error" :plain="true" :hairline="true" text="取消"
        :customStyle="hadlClickEdit"></up-button>
      <up-button type="error" text="确定" @click="handlOk" :customStyle="hadlClickEdit"></up-button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useraDdressData } from '@/api/userSettings.js'
import pickerAddress from '@/pages_home/components/pickerAddress/pickerAddress.vue' // 地区选择器组件
import addComponent from '@/pages_home/components/setupUserCopy/Add.vue'

const addComponentRef = ref([])

const addInfoArr = ref([{}])

function handleAdd() {
  if (addInfoArr.value.length < 4) addInfoArr.value.push({})
}

const handlOk = async () => {
  // 验证所有表单是否填写完整
  let isValid = true

  // 遍历所有地址组件，验证每个表单
  for (let i = 0; i < addComponentRef.value.length; i++) {
    const formRef = addComponentRef.value[i].$refs.formRef
    if (formRef) {
      try {
        // 触发表单验证，返回验证结果
        await formRef.validate().catch(error => {
          console.error('验证错误:', error)
          isValid = false
        })
      } catch (error) {
        console.error('验证出错:', error)
        isValid = false
      }
    }
  }

  // 只有全部验证通过才调用接口
  if (isValid) {
    const params = []
    addComponentRef.value.forEach((item) => {
      params.push(item.modelForm)
    })

    // 提交数据
    let success = true
    for (let i = 0; i < params.length; i++) {
      try {
        const res = await useraDdressData(params[i])
        if (res.code != 200) {
          success = false
        }
      } catch (error) {
        console.error('提交数据失败:', error)
        success = false
      }
    }
    
    if (success) {
      uni.showToast({
        title: '新增成功',
        icon: 'success',
        duration: 1500,
        mask: true,
      })
      
      // 成功后延迟返回上一页
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        })
      }, 1500)
    } else {
      uni.showToast({
        title: '新增失败',
        icon: 'none'
      })
    }
  } else {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
  }
}

const handleQux = () => {
  uni.navigateBack({
    delta: 2,
  })
}
const hadlClickEdit = {
  width: '240rpx',
  marginTop: '30rpx',
}
</script>
<style scoped lang="scss">
.address-inp {
  color: #929292;
}

.Wrapper-Btn {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
