<script setup lang="ts">
import {
  onMounted,
  getCurrentInstance
} from 'vue';
import Search from "@/pages/home/components/tabbar-home/components/search.vue";
const { t } = useI18n();
import {useAddressStore} from "@/pages/address/store/address";
import {appUserAddressListPost} from "@/service";
const addressStore = useAddressStore()



const addressesList = ref([])
const currentAddressId = ref('')
// 从 checkout 等页面通过 URL 传入的地址 id，用于进入页面时保持正确选中项
const initialAddressIdFromQuery = ref('')
function getAddressList() {
  appUserAddressListPost({
    params: {
      pageNum: 1,
      pageSize: 100,
    }
  }).then(res => {
    console.log('获取用户地址列表', res)
    addressesList.value = res.rows
    if(res.rows.length > 0) {
      // 若有从上一页传入的 id 且该 id 在列表中，则保持选中该地址；否则选中第一个
      const fromQuery = initialAddressIdFromQuery.value
      const existsInList = res.rows.some((row: any) => String(row.id) === String(fromQuery))
      if (fromQuery && existsInList) {
        currentAddressId.value = fromQuery
      } else {
        currentAddressId.value = res.rows[0].id
      }
    }
  })
}
function handleClickSearch() {
  uni.navigateTo({
    url: '/pages-user/pages/search-address/index',
    events: {
      chooseAddress: (data: any) => {
        console.log('搜索的地址信息', data)
        if (!data) return

        // 先判断是否已有相同地址
        const exist = addressesList.value.find((item: any) => {
          return (
              item.formattedAddress === data.formattedAddress &&
              (item.displayName || '') === (data.displayName || '')
          )
        })

        if (exist) {
          // 已存在：直接选择这个地址，走原有 chooseAddress 流程
          chooseAddress(exist)
        } else {
          // 不存在：走新增地址流程（建筑类型首次在保存页以弹窗呈现）
          addressStore.clearAddressInfo()
          addressStore.setAddressLocation({
            displayName: data.displayName,
            formattedAddress: data.formattedAddress,
            longitude: data.location.lng,
            latitude: data.location.lat,
          })
          addressStore.pendingIntroBuildingType = true
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/address/save-address/other'
            })
          }, 300)
        }
      }
    }
  });
}

onShow(()=> {
  getAddressList()
})
onLoad((options: any)=> {
  if(options.id) {
    initialAddressIdFromQuery.value = options.id
    currentAddressId.value = options.id
  }
})

function chooseAddress(item: any) {
  if(String(item.id) === String(currentAddressId.value)) return
  currentAddressId.value = item.id
  eventChannel.emit('acceptDataFromOpenedPage', {
    data: currentAddressId.value,
    deliveryRemark: item.deliveryRemark,
    deliveryType: item.deliveryType,
  });
  setTimeout(()=> {
    uni.navigateBack()
  }, 300)
}

let instance = null
let eventChannel = null
onMounted(()=> {
  instance = getCurrentInstance().proxy
  eventChannel = instance.getOpenerEventChannel();
})
onUnload(()=> {
  instance = null
  eventChannel = null
})
</script>

<template>
  <view>
    <navbar :title="t('pages.address.title')" />
    <view class="mt-32rpx px-30rpx">
      <search :is-auto-jump="false" @clickSearch="handleClickSearch" />
    </view>
    <view class="mt-64rpx text-40rpx lh-40rpx text-#333 font-bold pl-30rpx pb-24rpx">
      {{ t('pages.address.savedAddresses') }}
    </view>
    <template v-for="item in addressesList">
      <view @click="chooseAddress(item)" :class="[String(item.id) === String(currentAddressId) ? 'bg-#F3F3F3' : '']" class="w-full h-156rpx flex-center-sb px-30rpx">
        <view class="flex items-center">
          <image v-if="String(item.id) === String(currentAddressId)" src="@img/chef/143.png" class="w-44rpx h-44rpx shrink-0 mr-28rpx"></image>
          <image v-else src="@img/chef/145.png" class="w-44rpx h-44rpx shrink-0 mr-28rpx"></image>
          <view class="flex-1 h-156rpx pt-40rpx">
            <view class="text-32rpx lh-32rpx text-#333 font-500 mb-16rpx line-clamp-1">{{ item.formattedAddress }}</view>
            <view class="text-28rpx lh-28rpx text-#6D6D6D">{{ item.displayName || '' }}</view>
          </view>
        </view>
        <image
            :src="
                  String(item.id) === String(currentAddressId)
                  ? '/static/images/chef/133.png'
                   : '/static/images/chef/134.png'
                  "
            class="w-44rpx h-44rpx shrink-0 pl-30rpx"
            mode="aspectFit"
        />
      </view>
    </template>
    <template v-if="addressesList.length === 0">
      <view class="py-100rpx center">
        <image class="w-250rpx h-250rpx" src="@img/chef/100.png"></image>
      </view>
    </template>
  </view>
</template>
<style>
page {
  background-color: #fff;
}
</style>