<template>
  <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="900px"
      class="address-book-dialog"
      @close="handleClose"
  >
    <!-- 搜索框 -->
    <div class="search-wrapper">
      <div class="search-container">
        <el-input
            v-model="queryParams.searchKeyword"
            placeholder="请输入姓名、手机号或地址进行搜索"
            clearable
            class="search-input"
            @input="handleSearch"
            @clear="handleClearSearch"
        >
          <template #prefix>
            <i class="search-icon">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M7.33333 12.6667C10.2789 12.6667 12.6667 10.2789 12.6667 7.33333C12.6667 4.38781 10.2789 2 7.33333 2C4.38781 2 2 4.38781 2 7.33333C2 10.2789 4.38781 12.6667 7.33333 12.6667Z" stroke="#999999" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M14 14L11.1 11.1" stroke="#999999" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </i>
          </template>
        </el-input>
      </div>
    </div>

    <div class="address-list">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-wrapper">
        <div class="loading-spinner"></div>
        <div class="loading-text">加载中...</div>
      </div>

      <!-- 两列布局，每行显示两个地址 -->
      <div
          v-for="(addressRow, rowIndex) in addressRows"
          :key="rowIndex"
          class="address-row"
      >
        <div
            v-for="address in addressRow"
            :key="address?.addressId || rowIndex"
            class="address-item"
            :class="{ 'active': selectedAddressId === address?.addressId, 'empty': !address }"
            @click="address && handleSelectAddress(address)"
        >
          <div v-if="address" class="address-content">
            <div class="address-header">
              <span class="address-name">{{ address.contactName }}</span>
              <span class="address-phone">{{ address.contactPhone }}</span>
            </div>
            <div class="address-body">
              <div class="address-detail">{{ address.provinceName }}{{ address.cityName }}{{ address.countyName }}{{ address.detailedAddress }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 无数据提示 -->
      <div v-if="!loading && addressList.length === 0" class="no-data">
        <el-empty description="暂无地址数据" />
      </div>
    </div>

    <!-- 分页器 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          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, reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import { listBook } from "@/api/logistics/book"

// 定义组件属性
const props = defineProps({
  // 是否显示弹窗
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  // 地址簿类型：sender 或 receiver
  addressBookType: {
    type: String,
    required: true,
    validator: (value) => ['sender', 'receiver'].includes(value)
  }
})

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

// 响应式数据
const data = reactive({
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 8, // 每页显示8个地址
    searchKeyword: ''
  },
  // 地址列表
  addressList: [],
  // 总条数
  total: 0,
  // 加载状态
  loading: false
})

const { queryParams, addressList, total, loading } = toRefs(data)

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

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

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

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

// 监听visible变化，显示时获取数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 重置选择状态
    selectedAddressId.value = null
    selectedAddress.value = null
    // 重置查询参数
    queryParams.value.pageNum = 1
    queryParams.value.searchKeyword = ''
    // 获取地址列表
    getAddressList()
  }
})

// 计算属性：将地址数据分组为每行2个
const addressRows = computed(() => {
  const rows = []

  // 直接使用当前页的地址列表（已经是分页后的数据）
  const currentPageAddresses = addressList.value

  // 将地址分组为每行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 getAddressList = () => {
  loading.value = true

  // 构建查询参数，添加地址类型
  const params = {
    ...queryParams.value,
    type: props.addressBookType === 'sender' ? 'sender' : 'receiver'
  }

  listBook(params).then(response => {
    addressList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(error => {
    console.error('获取地址列表失败:', error)
    addressList.value = []
    total.value = 0
    loading.value = false
  })
}

// 处理搜索
const handleSearch = () => {
  // 重置到第一页
  queryParams.value.pageNum = 1

  // 获取地址列表
  getAddressList()

  // 触发搜索事件
  emit('search', queryParams.value.searchKeyword)
}

// 处理清除搜索
const handleClearSearch = () => {
  queryParams.value.searchKeyword = ''
  queryParams.value.pageNum = 1

  // 获取地址列表
  getAddressList()

  emit('search', '')
}

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

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

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

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

  // 获取新页的数据
  getAddressList()
}

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

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

// 处理关闭
const handleClose = () => {
  selectedAddressId.value = null
  selectedAddress.value = null
  queryParams.value.searchKeyword = ''
  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;
}

/* 搜索框样式 */
.search-wrapper {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  position: relative;
}

.search-input {
  width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  padding: 0 16px;
  box-shadow: none;
  height: 40px;
}

.search-input :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
}

.search-input :deep(.el-input__inner) {
  height: 38px;
  line-height: 38px;
  font-size: 14px;
  color: #333;
  background-color: transparent;
}

.search-input :deep(.el-input__inner::placeholder) {
  color: #999;
}

.search-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  color: #999;
}

.search-input :deep(.el-input__prefix) {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
}

.search-input :deep(.el-input__suffix) {
  display: flex;
  align-items: center;
  margin-right: 8px;
}

/* 地址列表样式 - 两列布局 */
.address-list {
  padding: 0 20px 20px;
  max-height: 500px;
  overflow-y: auto;
  background-color: #fff;
  position: relative;
  min-height: 300px;
}

/* 加载状态 */
.loading-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 14px;
  color: #666;
}

.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;
  border: 1px solid transparent;
}

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

.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;
}

/* 无数据提示 */
.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  color: #999;
}

.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;
  }

  .search-wrapper {
    padding: 16px;
  }
}
</style>