<script setup lang="ts">
import { createGlobalLoadingMiddleware } from '@/api/core/middleware'
import { StaticUrl } from '@/config'
import router from '@/router'

definePage({
  name: 'common-addressList',
  islogin: true,
  style: {
    navigationBarTitleText: '收获地址',
  },
})
const defaultId = ref()
const { addresses } = storeToRefs(useUserStore())
const route = useRoute()
const { send: updateData } = useRequest(data => Apis.sys.updateAddresses({
  data,
}), { middleware: createGlobalLoadingMiddleware({ loadingText: '设置中。。。' }), immediate: false })

onShow(async () => {
  await useUserStore().getuserAddresslist()
  useUserStore().getSelectedAddress()
})
watch(() => addresses.value, () => {
  defaultId.value = addresses.value.find(item => item.defaulted === 1)?.id
})

async function handleChange(e: { value: number }) {
  const item = addresses.value.find(i => i.id === e.value)
  if (item) {
    updateData({ ...item, defaulted: 1 })
  }
}
function handleSelectAddress(item: Api.addressList) {
  if (!route.query?.type)
    return
  useUserStore().updateSelectedAddress(item)
  router.back()
}
async function handleAddAddress() {
  await isWxMiniProgram()
  router.push({ name: 'common-editAddress', params: { type: '1' } })
}

async function handleEditAddress(item: Api.addressList) {
  await isWxMiniProgram()
  router.push({ name: 'common-editAddress', params: { type: '2', id: `${item.id}` } })
}
</script>

<template>
  <view class="page">
    <view class="px24rpx py20rpx">
      <wd-radio-group v-model="defaultId" @change="handleChange">
        <view v-for="item in addresses" :key="item.id" class="mb20rpx rounded-16rpx bg-white p24rpx" @click="handleSelectAddress(item)">
          <view class="flex items-center justify-between">
            <view class="text-28rpx font-semibold">
              {{ item.consigneeName }} {{ item.consigneeMobile }}
            </view>
            <image
              :src="`${StaticUrl}/edit-address.png`"
              class="h40rpx w40rpx"
              @click.stop="handleEditAddress(item)"
            />
          </view>
          <view class="mt24rpx text-24rpx text-#AAAAAA">
            {{ item.province }}{{ item.city }}{{ item.detailAddress }}
          </view>
          <view class="my24rpx h2rpx w-full bg-#F0F0F0" />
          <wd-radio :value="item.id" shape="dot" inline>
            设为默认地址
          </wd-radio>
        </view>
        <view class="ios h120rpx" />
      </wd-radio-group>
      <wd-status-tip v-if="!addresses.length" image="content" tip="暂无内容" />
    </view>

    <view class="ios fixed bottom-0 left-0 box-border w-full rounded-t-32rpx bg-white px24rpx">
      <view class="w-full py20rpx">
        <wd-button size="large" block @click="handleAddAddress">
          新增收货地址
        </wd-button>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.page{
  :deep(){
    .wd-radio-group{
      background-color: unset !important;
    }
  }
}
</style>
