<template>
  <uni-popup ref="popup" type="bottom" :mask-click="false">
    <view class="bg-white" :style="elderVarStyle">
      <view class="border-b flex items-center justify-between px-15 py-12">
        <view class="text-base text-dark">请选择收货地址</view>
        <uni-icons type="closeempty" :size="elderMode ? 32 : 24" color="#999" @click="close"></uni-icons>
      </view>
      <scroll-view scroll-y="true" class="popup-content-scroll">
        <view class="px-15 py-12">
          <view v-for="(i, idx) in list" :key="i.id" class="bg-white rounded shadow-lg" :class="idx > 0 ? 'mt-12' : ''"
            @click="select(i)">
            <view class="px-15 border-b">
              <view v-if="i.region && i.region.length" class="py-10 text-base text-gray">
                {{ i.region.join(' ') }}
              </view>
              <view class="pb-10 text-base text-dark">{{ i.address }}</view>
              <view class="pb-10 text-base text-dark">{{ i.name }} {{ i.phone }}</view>
            </view>
            <view class="flex items-center justify-between px-15 py-10">
              <view class="flex-shrink-0 text-base" :class="i.isDefault ? 'text-primary' : 'text-gray'"
                @click.stop="setDefault(i)">
                {{ i.isDefault ? '默认地址' : '设为默认地址' }}
              </view>
              <view class="flex">
                <view class="mr-10 text-base text-danger" @click.stop="remove(i.id)">删除</view>
                <view class="mr-10 text-base text-primary" @click.stop="changeAddress(i)">编辑</view>
              </view>
            </view>
          </view>

        </view>
      </scroll-view>
      <view class="text-danger p-15">
        <view class="text-base leading-normal">地址管理规则:</view>
        <view class="text-base leading-normal">1、每人最多可保存3个常用地址;</view>
        <view class="text-base leading-normal">2、任意变更操作(删除/修改)后，地址信息将锁定30天无法变更，请谨慎操作。</view>
      </view>
      <view v-if="list.length < 3" class="footer-buttons">
        <footer-buttons :showCancel="false" confirmText="新增地址" @confirm="changeAddress()" />
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import useElder from '@/hooks/useElder';
import { getAddressList, deleteAddress, updateAddress } from '@/utils/api';
import { set } from '@/utils/cache';
import { confirm, loading, hideLoading, toast } from '@/utils/widget';

import FooterButtons from '@/components/footer-buttons.vue';

const emits = defineEmits(['close', 'confirm'])
const props = defineProps({
  accountId: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const popup = ref()
const { elderMode, elderVarStyle } = useElder();
const list = ref([]);

function close() {
  emits('close')
}

function select(i) {
  emits('confirm', i)
}

function changeAddress(item) {
  if (item) {
    set('current-address', item)
  }
  uni.navigateTo({
    url: `/pages/member/address?id=${item ? item.id : ''}`
  })
}

async function getList() {
  loading('请求中...')
  const res = await getAddressList(props.accountId)
  hideLoading()
  list.value = res && Array.isArray(res.data) ? res.data : [];
  if (!res || !res.success) {
    toast(res && res.message ? res.message : '获取地址列表失败');
  }
}

async function remove(id) {
  await confirm('确定删除该地址吗？');
  const res = await deleteAddress(props.accountId, id)
  if (res && res.success) {
    toast('删除成功');
    list.value = list.value.filter(i => i.id !== id);
  } else {
    toast(res && res.message ? res.message : '删除失败');
  }
}

async function setDefault(i) {
  if (i.isDefault) return;
  const item = { ...i, isDefault: true, accountId: props.accountId }
  loading('请求中...')
  const res = await updateAddress(item);
  hideLoading()
  if (res && res.success) {
    list.value.forEach(j => {
      j.isDefault = j.id === i.id
    });
    await toast('设置默认地址成功');
  } else {
    toast(res && res.message ? res.message : '设置默认地址失败');
  }
}

watch(() => props.visible, n => {
  if (n) {
    popup.value && popup.value.open()
    getList()
  } else {
    popup.value && popup.value.close()
  }
})

onMounted(() => {
  uni.$on('change-account-address', getList)
})

onUnmounted(() => {
  uni.$off('change-account-address', getList)
})

</script>

<style lang="scss" scoped>
.popup-title {
  font-size: var(--text-base);
  font-weight: bold;
  color: #333;
}

.popup-content-scroll {
  max-height: 65vh;
  background-color: #f5f5f5;
}
</style>