<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAddressListApi,
  createAddressApi,
  updateAddressApi,
  deleteAddressApi,
  setDefaultAddressApi
} from '@/api/address'
import type { Address, AddressSaveReq } from '@/types'
import { Location, Plus, MapLocation } from '@element-plus/icons-vue'

const addresses = ref<Address[]>([])
const dialogVisible = ref(false)
const editingId = ref<number | null>(null)

const form = reactive<AddressSaveReq>({
  receiver: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  tag: '',
  isDefault: 0
})

const rules = {
  receiver: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  detail: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

const formRef = ref()

async function loadList() {
  addresses.value = (await getAddressListApi()) || []
}

function openCreate() {
  editingId.value = null
  Object.assign(form, {
    receiver: '', phone: '', province: '', city: '', district: '', detail: '', tag: '', isDefault: 0
  })
  dialogVisible.value = true
}

function openEdit(addr: Address) {
  editingId.value = addr.id
  Object.assign(form, {
    id: addr.id,
    receiver: addr.receiver,
    phone: addr.phone,
    province: addr.province,
    city: addr.city,
    district: addr.district,
    detail: addr.detail,
    tag: addr.tag,
    isDefault: addr.isDefault
  })
  dialogVisible.value = true
}

async function onSubmit() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  if (editingId.value) {
    await updateAddressApi({ ...form, id: editingId.value })
    ElMessage.success('已更新')
  } else {
    await createAddressApi(form)
    ElMessage.success('已新增')
  }
  dialogVisible.value = false
  await loadList()
}

async function onDelete(id: number) {
  await ElMessageBox.confirm('确定删除该地址？', '提示', { type: 'warning' })
  await deleteAddressApi(id)
  ElMessage.success('已删除')
  await loadList()
}

async function onSetDefault(id: number) {
  await setDefaultAddressApi(id)
  ElMessage.success('已设为默认')
  await loadList()
}

onMounted(loadList)
</script>

<template>
  <div class="page container">
    <div class="page-header">
      <h2 class="page-title">收货地址</h2>
      <p class="page-subtitle">管理您的收货地址</p>
    </div>

    <div class="address-grid">
      <div
        v-for="addr in addresses"
        :key="addr.id"
        class="address-card"
        :class="{ default: addr.isDefault === 1 }"
      >
        <div class="card-header">
          <div class="user-info">
            <span class="receiver">{{ addr.receiver }}</span>
            <span class="phone">{{ addr.phone }}</span>
          </div>
          <div class="tags">
            <el-tag v-if="addr.tag" size="small" effect="plain" class="tag">{{ addr.tag }}</el-tag>
            <el-tag v-if="addr.isDefault === 1" type="danger" size="small" effect="dark" class="tag">默认</el-tag>
          </div>
        </div>
        <p class="address-text">
          <el-icon size="14"><MapLocation /></el-icon>
          {{ addr.fullAddress || `${addr.province || ''} ${addr.city || ''} ${addr.district || ''} ${addr.detail}` }}
        </p>
        <div class="card-actions">
          <el-button v-if="addr.isDefault !== 1" text type="primary" size="small" @click="onSetDefault(addr.id)">设为默认</el-button>
          <el-button text type="primary" size="small" @click="openEdit(addr)">编辑</el-button>
          <el-button text type="danger" size="small" @click="onDelete(addr.id)">删除</el-button>
        </div>
      </div>

      <div class="add-card" @click="openCreate">
        <div class="add-icon">
          <el-icon :size="32"><Plus /></el-icon>
        </div>
        <span>添加新地址</span>
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="editingId ? '编辑地址' : '新增地址'"
      width="520px"
      class="address-dialog"
      align-center
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收货人" prop="receiver"><el-input v-model="form.receiver" /></el-form-item>
        <el-form-item label="手机号" prop="phone"><el-input v-model="form.phone" maxlength="11" /></el-form-item>
        <el-form-item label="省">
          <el-col :span="8"><el-input v-model="form.province" placeholder="如:广东省" /></el-col>
          <el-col :span="8" :offset="0"><el-input v-model="form.city" placeholder="市" /></el-col>
          <el-col :span="8"><el-input v-model="form.district" placeholder="区/县" /></el-col>
        </el-form-item>
        <el-form-item label="详细地址" prop="detail"><el-input v-model="form.detail" type="textarea" :rows="2" /></el-form-item>
        <el-form-item label="标签"><el-input v-model="form.tag" maxlength="20" placeholder="家 / 公司 / 学校" /></el-form-item>
        <el-form-item label="默认">
          <el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page {
  padding: 24px 0 60px;
}
.page-header {
  margin-bottom: 24px;
}
.page-title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 4px;
}
.page-subtitle {
  color: var(--color-text-muted);
  font-size: 14px;
}

.address-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.address-card {
  background: #fff;
  border-radius: var(--radius-xl);
  padding: 24px;
  border: 2px solid var(--color-border-light);
  transition: all var(--transition-fast);
  position: relative;
}
.address-card:hover {
  border-color: var(--color-primary);
  box-shadow: var(--shadow-md);
}
.address-card.default {
  border-color: var(--color-primary);
  background: linear-gradient(135deg, #FFF0EB 0%, #FFF7ED 100%);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}
.receiver {
  font-weight: 700;
  font-size: 16px;
  color: var(--color-text);
}
.phone {
  color: var(--color-text-secondary);
  font-size: 14px;
}
.tags {
  display: flex;
  gap: 6px;
}
.tag {
  font-weight: 500;
}
.address-text {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  color: var(--color-text-secondary);
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 16px;
}
.card-actions {
  display: flex;
  gap: 8px;
}

.add-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  min-height: 180px;
  border: 2px dashed var(--color-border);
  border-radius: var(--radius-xl);
  font-size: 15px;
  color: var(--color-text-muted);
  cursor: pointer;
  transition: all var(--transition-fast);
  background: #fff;
}
.add-card:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
  background: var(--color-primary-light);
}
.add-icon {
  width: 56px;
  height: 56px;
  border-radius: var(--radius-full);
  background: var(--color-primary-light);
  color: var(--color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
}

@media (max-width: 768px) {
  .address-grid {
    grid-template-columns: 1fr;
  }
}
</style>
