<template>
  <el-dialog v-model="visible" title="选择地址" width="800px" @close="handleClose">
    <el-table
      :data="addressList"
      border
      style="width: 100%"
      highlight-current-row
      @current-change="handleCurrentChange"
      @row-dblclick="handleRowDblClick"
    >
      <el-table-column label="选择" width="80" align="center">
        <template #default="scope">
          <el-radio v-model="selectedAddressId" :value="scope.row.id">
            <span></span>
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="consignee" label="收货人" width="120" />
      <el-table-column prop="phone" label="手机号" width="150" />
      <el-table-column prop="address" label="地址" show-overflow-tooltip>
        <template #default="scope"> {{ scope.row.provincialCityCountry }} {{ scope.row.address }} </template>
      </el-table-column>
    </el-table>

    <div v-if="addressList.length === 0" class="empty-data">暂无数据</div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { listShippingAddress } from '@/api/customer/customerFile/shippingAddress';
import { ShippingAddressVO, ShippingAddressQuery } from '@/api/customer/customerFile/shippingAddress/types';

interface Props {
  modelValue: boolean;
  customerId?: string | number;
  addressList?: ShippingAddressVO[];
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'confirm', address: ShippingAddressVO): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const visible = ref(false);
const selectedAddressId = ref<string | number>('');
const selectedAddress = ref<ShippingAddressVO | null>(null);

// 监听 modelValue 变化，同步到 visible
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
  },
  { immediate: true }
);

// 监听 visible 变化，同步到 modelValue
watch(visible, (newVal) => {
  emit('update:modelValue', newVal);
});

// 选中行变化
const handleCurrentChange = (row: ShippingAddressVO | null) => {
  if (row) {
    selectedAddressId.value = row.id;
    selectedAddress.value = row;
  }
};
// 双击行直接确认
const handleRowDblClick = (row: ShippingAddressVO) => {
  selectedAddress.value = row;
  selectedAddressId.value = row.id;
  handleConfirm();
};

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false);
  selectedAddressId.value = '';
  selectedAddress.value = null;
};

// 确认选择
const handleConfirm = () => {
  if (!selectedAddress.value) {
    return;
  }
  emit('confirm', selectedAddress.value);
  handleClose();
};
</script>

<style scoped lang="scss">
.empty-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
}

:deep(.el-radio__label) {
  display: none;
}
</style>
