<template>
  <div class="address-book">
    <h1>收货地址簿</h1>
    <el-button type="primary" class="add-button" @click="dialogVisible = true">添加新地址</el-button>
    <el-dialog title="添加/编辑地址" :visible.sync="dialogVisible" width="80%">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">确定</el-button>
      </div>
    </el-dialog>
    <ul>
      <li v-for="(address, index) in addresses" :key="index" class="address-item">
        <div class="address-info">
          <span class="name">{{ address.name }}</span>
          <span class="phone">{{ address.phone }}</span>
          <span class="address">{{ address.address }}</span>
        </div>
        <div class="address-actions">
          <el-button type="text" @click="editAddress(index)">修改</el-button>
          <el-button type="text" @click="deleteAddress(index)">删除</el-button>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  data() {
    return {
      addresses: [],
      dialogVisible: false,
      form: {
        name: '',
        phone: '',
        address: ''
      },
      currentAddressIndex: null,
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.fetchAddresses();
  },
  methods: {
    async fetchAddresses() {
      try {
        const data = await request({
          url: '/api/addresses', // 后端 API 地址
          method: 'get',
          params: {
             userName: this.$store.state.user.name 
            }
        });
        this.addresses = data.data;
        console.log( this.addresses);
      } catch (error) {
        console.error('无法获取地址数据:', error);
      }
    },
    addAddress() {
      this.currentAddressIndex = null;
      this.form = { name: '', phone: '', address: '' };
      this.dialogVisible = true;
    },
    editAddress(index) {
      this.currentAddressIndex = index;
      this.form = { ...this.addresses[index] };
      this.dialogVisible = true;
    },
    async saveAddress() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.currentAddressIndex === null) {
              // 新建地址
              const response = await request({
                url: '/api/addresses',
                method: 'post',
                data: this.form
              });
              this.addresses.push(response);
            } else {
              // 更新地址
              const response = await request({
                url: `/api/addresses/${this.addresses[this.currentAddressIndex].id}`,
                method: 'put',
                data: this.form
              });
              this.$set(this.addresses, this.currentAddressIndex, response);
            }
            this.dialogVisible = false;
          } catch (error) {
            console.error('保存地址失败:', error);
          }
        }
      });
    },
    async deleteAddress(index) {
      try {
        const addressId = this.addresses[index].id;
        await request({
          url: `/api/addresses/${addressId}`,
          method: 'delete'
        });
        this.addresses.splice(index, 1);
      } catch (error) {
        console.error('删除地址失败:', error);
      }
    }
  }
};
</script>

<style scoped>
.address-book {
  max-width: 800px;
  width: 90%;
  margin: 20px auto;
  padding: 20px;
  border-radius: 8px;
  background-color: #f7f7f7;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

ul {
  padding: 0;
  width: 100%;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  margin-bottom: 10px;
  padding: 2%;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  list-style-type: none;
}

.address-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-right: 10px;
  width: 65%;
}

.name, .phone, .address {
  margin-bottom: 5px;
  color: #555;
}

.address-actions {
  display: flex;
  min-width: 100px;
  justify-content: flex-end;
  width: 30%;
}

.el-button {
  margin-left: 10px;
  white-space: nowrap;
}

.add-button {
  display: block;
  width: 80%;
  margin: 0 auto 20px;
}
</style>的 async saveAddress() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.currentAddressIndex === null) {
              // 新建地址
              const response = await request({
                url: '/api/addresses',
                method: 'post',
                data: this.form
              });
              this.addresses.push(response);
            } else {
              // 更新地址
              const response = await request({
                url: `/api/addresses/${this.addresses[this.currentAddressIndex].id}`,
                method: 'put',
                data: this.form
              });
              this.$set(this.addresses, this.currentAddressIndex, response);
            }
            this.dialogVisible = false;
          } catch (error) {
            console.error('保存地址失败:', error);
          }
        }
      });怎么加入 userName: this.$store.state.user.name 这个数据发给后端？