<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_mine/components/pickerAddress/pickerAddress.vue' // 地区选择器组件
import addComponent from '@/pages_mine/components/setupUser/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 {
        // 直接触发表单验证，会自动显示错误提示
        const valid = await formRef.validate()
        if (!valid) {
          isValid = false
        }
      } catch (error) {
        isValid = false
      }
    }
  }

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

    // 提交数据
    params.forEach(async (obj) => {
      const res = await useraDdressData(obj)
      if (res.code == 200) {
        uni.showToast({
          title: '新增成功',
          icon: 'success',
          duration: 1500,
          mask: true,
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages_mine/pages/selectAddress/index',
          })
        }, 1500)
      }
    })
  }
}

const handleQux = () => {
  uni.navigateBack({
    delta: 1,
  })
}
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>
