<template>
  <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="900px"
      class="address-book-dialog"
      @close="handleClose"
  >
    <div class="address-list">
      <!-- 两列布局，每行显示两个地址 -->
      <div
          v-for="(addressRow, rowIndex) in addressRows"
          :key="rowIndex"
          class="address-row"
      >
        <div
            v-for="address in addressRow"
            :key="address?.id || rowIndex"
            class="address-item"
            :class="{ 'active': selectedAddressId === address?.id, 'empty': !address }"
            @click="address && handleSelectAddress(address)"
        >
          <div v-if="address" class="address-content">
            <div class="address-header">
              <span class="address-name">{{ address.name }}</span>
              <span class="address-phone">{{ address.phone }}</span>
<!--              <div class="address-tags">-->
<!--                <span class="tag default-tag" v-if="address.isDefault">默认</span>-->
<!--                <span class="tag home-tag" v-if="address.tag === 'home'">家庭</span>-->
<!--                <span class="tag company-tag" v-if="address.tag === 'company'">公司</span>-->
<!--              </div>-->
            </div>
            <div class="address-body">
              <div class="address-detail">{{ address.fullAddress }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <div class="pagination-wrapper">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalAddresses"
          layout="prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
      />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认选择</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'

// 定义组件属性
const props = defineProps({
  // 是否显示弹窗
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  // 地址簿类型：sender 或 receiver
  addressBookType: {
    type: String,
    required: true,
    validator: (value) => ['sender', 'receiver'].includes(value)
  },
  // 地址列表数据
  addressList: {
    type: Array,
    required: true,
    default: () => []
  },
  // 总地址数
  totalAddresses: {
    type: Number,
    default: 0
  },
  // 当前页码
  initialCurrentPage: {
    type: Number,
    default: 1
  },
  // 每页显示数量
  initialPageSize: {
    type: Number,
    default: 8
  }
})

// 定义组件事件
const emit = defineEmits([
  'update:visible',
  'select-address',
  'close',
  'cancel',
  'confirm',
  'page-change'
])

// 弹窗显示状态
const dialogVisible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

// 标题
const title = computed(() => {
  return `选择${props.addressBookType === 'sender' ? '寄件人' : '收件人'}地址`
})

// 当前页码
const currentPage = ref(props.initialCurrentPage)

// 每页显示数量
const pageSize = ref(props.initialPageSize)

// 选中的地址ID
const selectedAddressId = ref(null)

// 选中的地址
const selectedAddress = ref(null)

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 重置选择状态
    selectedAddressId.value = null
    selectedAddress.value = null
    currentPage.value = props.initialCurrentPage
  }
})

// 监听页码变化
watch(() => props.initialCurrentPage, (newVal) => {
  currentPage.value = newVal
})

// 计算属性：将地址数据分组为每行2个
const addressRows = computed(() => {
  const rows = []
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  const currentPageAddresses = props.addressList.slice(start, end)

  // 将地址分组为每行2个
  for (let i = 0; i < currentPageAddresses.length; i += 2) {
    const row = currentPageAddresses.slice(i, i + 2)
    // 如果这行只有1个地址，补一个空位保持布局
    if (row.length < 2) {
      row.push(null)
    }
    rows.push(row)
  }

  // 如果当前页没有地址，添加空行
  if (rows.length === 0) {
    rows.push([null, null])
  }

  return rows
})

// 处理选择地址
const handleSelectAddress = (address) => {
  if (!address) return

  selectedAddressId.value = address.id
  selectedAddress.value = { ...address }

  // 触发选择事件
  emit('select-address', address)
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  selectedAddressId.value = null
  selectedAddress.value = null

  // 触发分页变化事件
  emit('page-change', {
    page,
    pageSize: pageSize.value
  })
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
  emit('cancel')
}

// 处理确认
const handleConfirm = () => {
  if (selectedAddress.value) {
    emit('confirm', selectedAddress.value)
    dialogVisible.value = false
  } else {
    // 如果没有选中地址，可以选择触发一个错误提示
    emit('confirm', null)
  }
}

// 处理关闭
const handleClose = () => {
  selectedAddressId.value = null
  selectedAddress.value = null
  emit('close')
}
</script>

<style scoped>
.address-book-dialog :deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #e8e8e8;
}

.address-book-dialog :deep(.el-dialog__body) {
  padding: 0;
}

/* 地址列表样式 - 两列布局 */
.address-list {
  padding: 20px;
  max-height: 500px;
  overflow-y: auto;
}

.address-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.address-item {
  background: #F5F7FA;
  border-radius: 16px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  min-height: 100px;
}

.address-item:hover {
  background: #EAF1FF;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.address-item.active {
  border: 1px solid #2D71FF;
  background-color: #EAF1FF;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.address-item.empty {
  visibility: hidden;
  pointer-events: none;
}

.address-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.address-header {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  gap: 8px;
}

.address-name {
  font-size: 16px;
  font-weight: 600;
  color: #333333;

}

.address-phone {
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  margin-left: 20px;
}

.address-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.tag {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 2px;
  color: #fff;
  white-space: nowrap;
}

.default-tag {
  background-color: #1890ff;
}

.home-tag {
  background-color: #52c41a;
}

.company-tag {
  background-color: #722ed1;
}

.address-body {
  display: flex;
  align-items: center;
}

.address-detail {
  font-size: 14px;
  color: #333;
  line-height: 22px;
  word-break: break-all;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
  background-color: #fafafa;
  border-top: 1px solid #e8e8e8;
}

.address-book-dialog :deep(.el-dialog__footer) {
  padding: 12px 20px;
  border-top: 1px solid #e8e8e8;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .address-book-dialog {
    width: 95% !important;
  }

  .address-row {
    grid-template-columns: 1fr;
  }
}
</style>